blob: 8f6d5348e67331e5497bb90779cf018cdd28beca [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 }
1606 if (CI) {
1607 const Type *UIntPtrTy = TD->getIntPtrType();
1608 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
1609 if((CI->getType() == UIntPtrTy || CI->getType() == SIntPtrTy)
1610 && isa<PointerType>(CI->getOperand(0)->getType())) {
Evan Cheng453280b2006-09-20 01:10:02 +00001611 Instruction* I2 = new CastInst(CI->getOperand(0),
1612 PointerType::get(Type::SByteTy), "ctg", &I);
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001613 WorkList.push_back(I2);
1614 I2 = new GetElementPtrInst(I2, Other, "ctg", &I);
1615 WorkList.push_back(I2);
1616 return new CastInst(I2, CI->getType());
1617 }
1618 }
1619 }
1620
Chris Lattner113f4f42002-06-25 16:13:24 +00001621 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001622}
1623
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001624// isSignBit - Return true if the value represented by the constant only has the
1625// highest order bit set.
1626static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001627 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001628 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001629}
1630
Chris Lattner022167f2004-03-13 00:11:49 +00001631/// RemoveNoopCast - Strip off nonconverting casts from the value.
1632///
1633static Value *RemoveNoopCast(Value *V) {
1634 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1635 const Type *CTy = CI->getType();
1636 const Type *OpTy = CI->getOperand(0)->getType();
1637 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001638 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001639 return RemoveNoopCast(CI->getOperand(0));
1640 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1641 return RemoveNoopCast(CI->getOperand(0));
1642 }
1643 return V;
1644}
1645
Chris Lattner113f4f42002-06-25 16:13:24 +00001646Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001648
Chris Lattnere6794492002-08-12 21:17:25 +00001649 if (Op0 == Op1) // sub X, X -> 0
1650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001651
Chris Lattnere6794492002-08-12 21:17:25 +00001652 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001653 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001654 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001655
Chris Lattner81a7a232004-10-16 18:11:37 +00001656 if (isa<UndefValue>(Op0))
1657 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1658 if (isa<UndefValue>(Op1))
1659 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1660
Chris Lattner8f2f5982003-11-05 01:06:05 +00001661 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1662 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001663 if (C->isAllOnesValue())
1664 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001665
Chris Lattner8f2f5982003-11-05 01:06:05 +00001666 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001667 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001668 if (match(Op1, m_Not(m_Value(X))))
1669 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001670 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001671 // -((uint)X >> 31) -> ((int)X >> 31)
1672 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001673 if (C->isNullValue()) {
1674 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1675 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001676 if (SI->getOpcode() == Instruction::Shr)
1677 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1678 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001679 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001680 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001681 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001682 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001683 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001684 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001685 // Ok, the transformation is safe. Insert a cast of the incoming
1686 // value, then the new shift, then the new cast.
1687 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1688 SI->getOperand(0)->getName());
1689 Value *InV = InsertNewInstBefore(FirstCast, I);
1690 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1691 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001692 if (NewShift->getType() == I.getType())
1693 return NewShift;
1694 else {
1695 InV = InsertNewInstBefore(NewShift, I);
1696 return new CastInst(NewShift, I.getType());
1697 }
Chris Lattner92295c52004-03-12 23:53:13 +00001698 }
1699 }
Chris Lattner022167f2004-03-13 00:11:49 +00001700 }
Chris Lattner183b3362004-04-09 19:05:30 +00001701
1702 // Try to fold constant sub into select arguments.
1703 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001704 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001705 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001706
1707 if (isa<PHINode>(Op0))
1708 if (Instruction *NV = FoldOpIntoPhi(I))
1709 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001710 }
1711
Chris Lattnera9be4492005-04-07 16:15:25 +00001712 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1713 if (Op1I->getOpcode() == Instruction::Add &&
1714 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001715 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001716 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001717 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001718 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001719 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1720 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1721 // C1-(X+C2) --> (C1-C2)-X
1722 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1723 Op1I->getOperand(0));
1724 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001725 }
1726
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001727 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001728 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1729 // is not used by anyone else...
1730 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001731 if (Op1I->getOpcode() == Instruction::Sub &&
1732 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001733 // Swap the two operands of the subexpr...
1734 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1735 Op1I->setOperand(0, IIOp1);
1736 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737
Chris Lattner3082c5a2003-02-18 19:28:33 +00001738 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001739 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001740 }
1741
1742 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1743 //
1744 if (Op1I->getOpcode() == Instruction::And &&
1745 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1746 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1747
Chris Lattner396dbfe2004-06-09 05:08:07 +00001748 Value *NewNot =
1749 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001750 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001751 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001752
Chris Lattner0aee4b72004-10-06 15:08:25 +00001753 // -(X sdiv C) -> (X sdiv -C)
1754 if (Op1I->getOpcode() == Instruction::Div)
1755 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001756 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001757 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001758 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001759 ConstantExpr::getNeg(DivRHS));
1760
Chris Lattner57c8d992003-02-18 19:57:07 +00001761 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001762 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001763 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001764 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001765 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001766 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001767 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001768 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001769 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001770
Chris Lattner47060462005-04-07 17:14:51 +00001771 if (!Op0->getType()->isFloatingPoint())
1772 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1773 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001774 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1775 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1776 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1777 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001778 } else if (Op0I->getOpcode() == Instruction::Sub) {
1779 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1780 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001781 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001782
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001783 ConstantInt *C1;
1784 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1785 if (X == Op1) { // X*C - X --> X * (C-1)
1786 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1787 return BinaryOperator::createMul(Op1, CP1);
1788 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001789
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001790 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1791 if (X == dyn_castFoldableMul(Op1, C2))
1792 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1793 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001794 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001795}
1796
Chris Lattnere79e8542004-02-23 06:38:22 +00001797/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1798/// really just returns true if the most significant (sign) bit is set.
1799static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1800 if (RHS->getType()->isSigned()) {
1801 // True if source is LHS < 0 or LHS <= -1
1802 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1803 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1804 } else {
1805 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1806 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1807 // the size of the integer type.
1808 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001809 return RHSC->getValue() ==
1810 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001811 if (Opcode == Instruction::SetGT)
1812 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001813 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001814 }
1815 return false;
1816}
1817
Chris Lattner113f4f42002-06-25 16:13:24 +00001818Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001819 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001820 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001821
Chris Lattner81a7a232004-10-16 18:11:37 +00001822 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1823 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1824
Chris Lattnere6794492002-08-12 21:17:25 +00001825 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001826 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1827 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001828
1829 // ((X << C1)*C2) == (X * (C2 << C1))
1830 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1831 if (SI->getOpcode() == Instruction::Shl)
1832 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001833 return BinaryOperator::createMul(SI->getOperand(0),
1834 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001835
Chris Lattnercce81be2003-09-11 22:24:54 +00001836 if (CI->isNullValue())
1837 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1838 if (CI->equalsInt(1)) // X * 1 == X
1839 return ReplaceInstUsesWith(I, Op0);
1840 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001841 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001842
Chris Lattnercce81be2003-09-11 22:24:54 +00001843 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001844 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1845 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001846 return new ShiftInst(Instruction::Shl, Op0,
1847 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001848 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001849 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001850 if (Op1F->isNullValue())
1851 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001852
Chris Lattner3082c5a2003-02-18 19:28:33 +00001853 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1854 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1855 if (Op1F->getValue() == 1.0)
1856 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1857 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001858
1859 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1860 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1861 isa<ConstantInt>(Op0I->getOperand(1))) {
1862 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1863 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1864 Op1, "tmp");
1865 InsertNewInstBefore(Add, I);
1866 Value *C1C2 = ConstantExpr::getMul(Op1,
1867 cast<Constant>(Op0I->getOperand(1)));
1868 return BinaryOperator::createAdd(Add, C1C2);
1869
1870 }
Chris Lattner183b3362004-04-09 19:05:30 +00001871
1872 // Try to fold constant mul into select arguments.
1873 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001874 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001875 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001876
1877 if (isa<PHINode>(Op0))
1878 if (Instruction *NV = FoldOpIntoPhi(I))
1879 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001880 }
1881
Chris Lattner934a64cf2003-03-10 23:23:04 +00001882 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1883 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001884 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001885
Chris Lattner2635b522004-02-23 05:39:21 +00001886 // If one of the operands of the multiply is a cast from a boolean value, then
1887 // we know the bool is either zero or one, so this is a 'masking' multiply.
1888 // See if we can simplify things based on how the boolean was originally
1889 // formed.
1890 CastInst *BoolCast = 0;
1891 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1892 if (CI->getOperand(0)->getType() == Type::BoolTy)
1893 BoolCast = CI;
1894 if (!BoolCast)
1895 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1896 if (CI->getOperand(0)->getType() == Type::BoolTy)
1897 BoolCast = CI;
1898 if (BoolCast) {
1899 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1900 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1901 const Type *SCOpTy = SCIOp0->getType();
1902
Chris Lattnere79e8542004-02-23 06:38:22 +00001903 // If the setcc is true iff the sign bit of X is set, then convert this
1904 // multiply into a shift/and combination.
1905 if (isa<ConstantInt>(SCIOp1) &&
1906 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001907 // Shift the X value right to turn it into "all signbits".
1908 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001909 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001910 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001911 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001912 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1913 SCIOp0->getName()), I);
1914 }
1915
1916 Value *V =
1917 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1918 BoolCast->getOperand(0)->getName()+
1919 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001920
1921 // If the multiply type is not the same as the source type, sign extend
1922 // or truncate to the multiply type.
1923 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001924 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001925
Chris Lattner2635b522004-02-23 05:39:21 +00001926 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001927 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001928 }
1929 }
1930 }
1931
Chris Lattner113f4f42002-06-25 16:13:24 +00001932 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001933}
1934
Chris Lattner113f4f42002-06-25 16:13:24 +00001935Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001936 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001937
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001938 if (isa<UndefValue>(Op0)) // undef / X -> 0
1939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1940 if (isa<UndefValue>(Op1))
1941 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1942
1943 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001944 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001945 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001946 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001947
Chris Lattnere20c3342004-04-26 14:01:59 +00001948 // div X, -1 == -X
1949 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001950 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001951
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001952 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001953 if (LHS->getOpcode() == Instruction::Div)
1954 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001955 // (X / C1) / C2 -> X / (C1*C2)
1956 return BinaryOperator::createDiv(LHS->getOperand(0),
1957 ConstantExpr::getMul(RHS, LHSRHS));
1958 }
1959
Chris Lattner3082c5a2003-02-18 19:28:33 +00001960 // Check to see if this is an unsigned division with an exact power of 2,
1961 // if so, convert to a right shift.
1962 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1963 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001964 if (isPowerOf2_64(Val)) {
1965 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001966 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001967 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001968 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001969
Chris Lattner4ad08352004-10-09 02:50:40 +00001970 // -X/C -> X/-C
1971 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001972 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001973 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1974
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001975 if (!RHS->isNullValue()) {
1976 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001977 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001978 return R;
1979 if (isa<PHINode>(Op0))
1980 if (Instruction *NV = FoldOpIntoPhi(I))
1981 return NV;
1982 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001983 }
1984
Chris Lattnerd79dc792006-09-09 20:26:32 +00001985 // Handle div X, Cond?Y:Z
1986 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1987 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1988 // same basic block, then we replace the select with Y, and the condition of
1989 // the select with false (if the cond value is in the same BB). If the
1990 // select has uses other than the div, this allows them to be simplified
1991 // also.
1992 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1993 if (ST->isNullValue()) {
1994 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1995 if (CondI && CondI->getParent() == I.getParent())
1996 UpdateValueUsesWith(CondI, ConstantBool::False);
1997 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1998 I.setOperand(1, SI->getOperand(2));
1999 else
2000 UpdateValueUsesWith(SI, SI->getOperand(2));
2001 return &I;
2002 }
2003 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2004 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2005 if (ST->isNullValue()) {
2006 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2007 if (CondI && CondI->getParent() == I.getParent())
2008 UpdateValueUsesWith(CondI, ConstantBool::True);
2009 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2010 I.setOperand(1, SI->getOperand(1));
2011 else
2012 UpdateValueUsesWith(SI, SI->getOperand(1));
2013 return &I;
2014 }
2015
2016 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2017 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002018 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2019 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002020 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00002021 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002022 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2023 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00002024 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2025 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2026 TC, SI->getName()+".t");
2027 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002028
Chris Lattner42362612005-04-08 04:03:26 +00002029 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2030 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2031 FC, SI->getName()+".f");
2032 FSI = InsertNewInstBefore(FSI, I);
2033 return new SelectInst(SI->getOperand(0), TSI, FSI);
2034 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002035 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002037
Chris Lattner3082c5a2003-02-18 19:28:33 +00002038 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002039 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002040 if (LHS->equalsInt(0))
2041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2042
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002043 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002044 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002045 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002046 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2047 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002048 const Type *NTy = Op0->getType()->getUnsignedVersion();
2049 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2050 InsertNewInstBefore(LHS, I);
2051 Value *RHS;
2052 if (Constant *R = dyn_cast<Constant>(Op1))
2053 RHS = ConstantExpr::getCast(R, NTy);
2054 else
2055 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2056 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2057 InsertNewInstBefore(Div, I);
2058 return new CastInst(Div, I.getType());
2059 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002060 } else {
2061 // Known to be an unsigned division.
2062 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2063 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2064 if (RHSI->getOpcode() == Instruction::Shl &&
2065 isa<ConstantUInt>(RHSI->getOperand(0))) {
2066 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2067 if (isPowerOf2_64(C1)) {
2068 unsigned C2 = Log2_64(C1);
2069 Value *Add = RHSI->getOperand(1);
2070 if (C2) {
2071 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2072 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2073 "tmp"), I);
2074 }
2075 return new ShiftInst(Instruction::Shr, Op0, Add);
2076 }
2077 }
2078 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002079 }
2080
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002081 return 0;
2082}
2083
2084
Chris Lattner85dda9a2006-03-02 06:50:58 +00002085/// GetFactor - If we can prove that the specified value is at least a multiple
2086/// of some factor, return that factor.
2087static Constant *GetFactor(Value *V) {
2088 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2089 return CI;
2090
2091 // Unless we can be tricky, we know this is a multiple of 1.
2092 Constant *Result = ConstantInt::get(V->getType(), 1);
2093
2094 Instruction *I = dyn_cast<Instruction>(V);
2095 if (!I) return Result;
2096
2097 if (I->getOpcode() == Instruction::Mul) {
2098 // Handle multiplies by a constant, etc.
2099 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2100 GetFactor(I->getOperand(1)));
2101 } else if (I->getOpcode() == Instruction::Shl) {
2102 // (X<<C) -> X * (1 << C)
2103 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2104 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2105 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2106 }
2107 } else if (I->getOpcode() == Instruction::And) {
2108 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2109 // X & 0xFFF0 is known to be a multiple of 16.
2110 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2111 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2112 return ConstantExpr::getShl(Result,
2113 ConstantUInt::get(Type::UByteTy, Zeros));
2114 }
2115 } else if (I->getOpcode() == Instruction::Cast) {
2116 Value *Op = I->getOperand(0);
2117 // Only handle int->int casts.
2118 if (!Op->getType()->isInteger()) return Result;
2119 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2120 }
2121 return Result;
2122}
2123
Chris Lattner113f4f42002-06-25 16:13:24 +00002124Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002126
2127 // 0 % X == 0, we don't need to preserve faults!
2128 if (Constant *LHS = dyn_cast<Constant>(Op0))
2129 if (LHS->isNullValue())
2130 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2131
2132 if (isa<UndefValue>(Op0)) // undef % X -> 0
2133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2134 if (isa<UndefValue>(Op1))
2135 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2136
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002137 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002138 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002139 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002140 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002141 // X % -Y -> X % Y
2142 AddUsesToWorkList(I);
2143 I.setOperand(1, RHSNeg);
2144 return &I;
2145 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002146
2147 // If the top bits of both operands are zero (i.e. we can prove they are
2148 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002149 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2150 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002151 const Type *NTy = Op0->getType()->getUnsignedVersion();
2152 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2153 InsertNewInstBefore(LHS, I);
2154 Value *RHS;
2155 if (Constant *R = dyn_cast<Constant>(Op1))
2156 RHS = ConstantExpr::getCast(R, NTy);
2157 else
2158 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2159 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2160 InsertNewInstBefore(Rem, I);
2161 return new CastInst(Rem, I.getType());
2162 }
2163 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002164
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002165 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002166 // X % 0 == undef, we don't need to preserve faults!
2167 if (RHS->equalsInt(0))
2168 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2169
Chris Lattner3082c5a2003-02-18 19:28:33 +00002170 if (RHS->equalsInt(1)) // X % 1 == 0
2171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2172
2173 // Check to see if this is an unsigned remainder with an exact power of 2,
2174 // if so, convert to a bitwise and.
2175 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002176 if (isPowerOf2_64(C->getValue()))
2177 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002178
Chris Lattnerb70f1412006-02-28 05:49:21 +00002179 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2180 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2181 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2182 return R;
2183 } else if (isa<PHINode>(Op0I)) {
2184 if (Instruction *NV = FoldOpIntoPhi(I))
2185 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002186 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002187
2188 // X*C1%C2 --> 0 iff C1%C2 == 0
2189 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2190 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002191 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002192 }
2193
Chris Lattner2e90b732006-02-05 07:54:04 +00002194 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2195 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2196 if (I.getType()->isUnsigned() &&
2197 RHSI->getOpcode() == Instruction::Shl &&
2198 isa<ConstantUInt>(RHSI->getOperand(0))) {
2199 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2200 if (isPowerOf2_64(C1)) {
2201 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2202 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2203 "tmp"), I);
2204 return BinaryOperator::createAnd(Op0, Add);
2205 }
2206 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002207
2208 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2209 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002210 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2211 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2212 // the same basic block, then we replace the select with Y, and the
2213 // condition of the select with false (if the cond value is in the same
2214 // BB). If the select has uses other than the div, this allows them to be
2215 // simplified also.
2216 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2217 if (ST->isNullValue()) {
2218 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2219 if (CondI && CondI->getParent() == I.getParent())
2220 UpdateValueUsesWith(CondI, ConstantBool::False);
2221 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2222 I.setOperand(1, SI->getOperand(2));
2223 else
2224 UpdateValueUsesWith(SI, SI->getOperand(2));
2225 return &I;
2226 }
2227 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2228 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2229 if (ST->isNullValue()) {
2230 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2231 if (CondI && CondI->getParent() == I.getParent())
2232 UpdateValueUsesWith(CondI, ConstantBool::True);
2233 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2234 I.setOperand(1, SI->getOperand(1));
2235 else
2236 UpdateValueUsesWith(SI, SI->getOperand(1));
2237 return &I;
2238 }
2239
2240
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002241 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2242 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002243 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002244
2245 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2246 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2247 SubOne(STO), SI->getName()+".t"), I);
2248 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2249 SubOne(SFO), SI->getName()+".f"), I);
2250 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2251 }
2252 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002253 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002254 }
2255
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002256 return 0;
2257}
2258
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002259// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002260static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002261 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2262 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002263
2264 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002265
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002266 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002267 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002268 int64_t Val = INT64_MAX; // All ones
2269 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2270 return CS->getValue() == Val-1;
2271}
2272
2273// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002274static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002275 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2276 return CU->getValue() == 1;
2277
2278 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002279
2280 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002281 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002282 int64_t Val = -1; // All ones
2283 Val <<= TypeBits-1; // Shift over to the right spot
2284 return CS->getValue() == Val+1;
2285}
2286
Chris Lattner35167c32004-06-09 07:59:58 +00002287// isOneBitSet - Return true if there is exactly one bit set in the specified
2288// constant.
2289static bool isOneBitSet(const ConstantInt *CI) {
2290 uint64_t V = CI->getRawValue();
2291 return V && (V & (V-1)) == 0;
2292}
2293
Chris Lattner8fc5af42004-09-23 21:46:38 +00002294#if 0 // Currently unused
2295// isLowOnes - Return true if the constant is of the form 0+1+.
2296static bool isLowOnes(const ConstantInt *CI) {
2297 uint64_t V = CI->getRawValue();
2298
2299 // There won't be bits set in parts that the type doesn't contain.
2300 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2301
2302 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2303 return U && V && (U & V) == 0;
2304}
2305#endif
2306
2307// isHighOnes - Return true if the constant is of the form 1+0+.
2308// This is the same as lowones(~X).
2309static bool isHighOnes(const ConstantInt *CI) {
2310 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002311 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002312
2313 // There won't be bits set in parts that the type doesn't contain.
2314 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2315
2316 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2317 return U && V && (U & V) == 0;
2318}
2319
2320
Chris Lattner3ac7c262003-08-13 20:16:26 +00002321/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2322/// are carefully arranged to allow folding of expressions such as:
2323///
2324/// (A < B) | (A > B) --> (A != B)
2325///
2326/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2327/// represents that the comparison is true if A == B, and bit value '1' is true
2328/// if A < B.
2329///
2330static unsigned getSetCondCode(const SetCondInst *SCI) {
2331 switch (SCI->getOpcode()) {
2332 // False -> 0
2333 case Instruction::SetGT: return 1;
2334 case Instruction::SetEQ: return 2;
2335 case Instruction::SetGE: return 3;
2336 case Instruction::SetLT: return 4;
2337 case Instruction::SetNE: return 5;
2338 case Instruction::SetLE: return 6;
2339 // True -> 7
2340 default:
2341 assert(0 && "Invalid SetCC opcode!");
2342 return 0;
2343 }
2344}
2345
2346/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2347/// opcode and two operands into either a constant true or false, or a brand new
2348/// SetCC instruction.
2349static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2350 switch (Opcode) {
2351 case 0: return ConstantBool::False;
2352 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2353 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2354 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2355 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2356 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2357 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2358 case 7: return ConstantBool::True;
2359 default: assert(0 && "Illegal SetCCCode!"); return 0;
2360 }
2361}
2362
2363// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2364struct FoldSetCCLogical {
2365 InstCombiner &IC;
2366 Value *LHS, *RHS;
2367 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2368 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2369 bool shouldApply(Value *V) const {
2370 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2371 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2372 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2373 return false;
2374 }
2375 Instruction *apply(BinaryOperator &Log) const {
2376 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2377 if (SCI->getOperand(0) != LHS) {
2378 assert(SCI->getOperand(1) == LHS);
2379 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2380 }
2381
2382 unsigned LHSCode = getSetCondCode(SCI);
2383 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2384 unsigned Code;
2385 switch (Log.getOpcode()) {
2386 case Instruction::And: Code = LHSCode & RHSCode; break;
2387 case Instruction::Or: Code = LHSCode | RHSCode; break;
2388 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002389 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002390 }
2391
2392 Value *RV = getSetCCValue(Code, LHS, RHS);
2393 if (Instruction *I = dyn_cast<Instruction>(RV))
2394 return I;
2395 // Otherwise, it's a constant boolean value...
2396 return IC.ReplaceInstUsesWith(Log, RV);
2397 }
2398};
2399
Chris Lattnerba1cb382003-09-19 17:17:26 +00002400// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2401// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2402// guaranteed to be either a shift instruction or a binary operator.
2403Instruction *InstCombiner::OptAndOp(Instruction *Op,
2404 ConstantIntegral *OpRHS,
2405 ConstantIntegral *AndRHS,
2406 BinaryOperator &TheAnd) {
2407 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002408 Constant *Together = 0;
2409 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002410 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002411
Chris Lattnerba1cb382003-09-19 17:17:26 +00002412 switch (Op->getOpcode()) {
2413 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002414 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002415 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2416 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002417 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002418 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002419 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002420 }
2421 break;
2422 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002423 if (Together == AndRHS) // (X | C) & C --> C
2424 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002425
Chris Lattner86102b82005-01-01 16:22:27 +00002426 if (Op->hasOneUse() && Together != OpRHS) {
2427 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2428 std::string Op0Name = Op->getName(); Op->setName("");
2429 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2430 InsertNewInstBefore(Or, TheAnd);
2431 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002432 }
2433 break;
2434 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002435 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002436 // Adding a one to a single bit bit-field should be turned into an XOR
2437 // of the bit. First thing to check is to see if this AND is with a
2438 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002439 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002440
2441 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002442 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002443
2444 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002445 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002446 // Ok, at this point, we know that we are masking the result of the
2447 // ADD down to exactly one bit. If the constant we are adding has
2448 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002449 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002450
Chris Lattnerba1cb382003-09-19 17:17:26 +00002451 // Check to see if any bits below the one bit set in AndRHSV are set.
2452 if ((AddRHS & (AndRHSV-1)) == 0) {
2453 // If not, the only thing that can effect the output of the AND is
2454 // the bit specified by AndRHSV. If that bit is set, the effect of
2455 // the XOR is to toggle the bit. If it is clear, then the ADD has
2456 // no effect.
2457 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2458 TheAnd.setOperand(0, X);
2459 return &TheAnd;
2460 } else {
2461 std::string Name = Op->getName(); Op->setName("");
2462 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002463 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002464 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002465 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002466 }
2467 }
2468 }
2469 }
2470 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002471
2472 case Instruction::Shl: {
2473 // We know that the AND will not produce any of the bits shifted in, so if
2474 // the anded constant includes them, clear them now!
2475 //
2476 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002477 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2478 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002479
Chris Lattner7e794272004-09-24 15:21:34 +00002480 if (CI == ShlMask) { // Masking out bits that the shift already masks
2481 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2482 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002483 TheAnd.setOperand(1, CI);
2484 return &TheAnd;
2485 }
2486 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002487 }
Chris Lattner2da29172003-09-19 19:05:02 +00002488 case Instruction::Shr:
2489 // We know that the AND will not produce any of the bits shifted in, so if
2490 // the anded constant includes them, clear them now! This only applies to
2491 // unsigned shifts, because a signed shr may bring in set bits!
2492 //
2493 if (AndRHS->getType()->isUnsigned()) {
2494 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002495 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2496 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2497
2498 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2499 return ReplaceInstUsesWith(TheAnd, Op);
2500 } else if (CI != AndRHS) {
2501 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002502 return &TheAnd;
2503 }
Chris Lattner7e794272004-09-24 15:21:34 +00002504 } else { // Signed shr.
2505 // See if this is shifting in some sign extension, then masking it out
2506 // with an and.
2507 if (Op->hasOneUse()) {
2508 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2509 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2510 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002511 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002512 // Make the argument unsigned.
2513 Value *ShVal = Op->getOperand(0);
2514 ShVal = InsertCastBefore(ShVal,
2515 ShVal->getType()->getUnsignedVersion(),
2516 TheAnd);
2517 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2518 OpRHS, Op->getName()),
2519 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002520 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2521 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2522 TheAnd.getName()),
2523 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002524 return new CastInst(ShVal, Op->getType());
2525 }
2526 }
Chris Lattner2da29172003-09-19 19:05:02 +00002527 }
2528 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002529 }
2530 return 0;
2531}
2532
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002533
Chris Lattner6862fbd2004-09-29 17:40:11 +00002534/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2535/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2536/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2537/// insert new instructions.
2538Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2539 bool Inside, Instruction &IB) {
2540 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2541 "Lo is not <= Hi in range emission code!");
2542 if (Inside) {
2543 if (Lo == Hi) // Trivially false.
2544 return new SetCondInst(Instruction::SetNE, V, V);
2545 if (cast<ConstantIntegral>(Lo)->isMinValue())
2546 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002547
Chris Lattner6862fbd2004-09-29 17:40:11 +00002548 Constant *AddCST = ConstantExpr::getNeg(Lo);
2549 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2550 InsertNewInstBefore(Add, IB);
2551 // Convert to unsigned for the comparison.
2552 const Type *UnsType = Add->getType()->getUnsignedVersion();
2553 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2554 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2555 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2556 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2557 }
2558
2559 if (Lo == Hi) // Trivially true.
2560 return new SetCondInst(Instruction::SetEQ, V, V);
2561
2562 Hi = SubOne(cast<ConstantInt>(Hi));
2563 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2564 return new SetCondInst(Instruction::SetGT, V, Hi);
2565
2566 // Emit X-Lo > Hi-Lo-1
2567 Constant *AddCST = ConstantExpr::getNeg(Lo);
2568 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2569 InsertNewInstBefore(Add, IB);
2570 // Convert to unsigned for the comparison.
2571 const Type *UnsType = Add->getType()->getUnsignedVersion();
2572 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2573 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2574 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2575 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2576}
2577
Chris Lattnerb4b25302005-09-18 07:22:02 +00002578// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2579// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2580// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2581// not, since all 1s are not contiguous.
2582static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2583 uint64_t V = Val->getRawValue();
2584 if (!isShiftedMask_64(V)) return false;
2585
2586 // look for the first zero bit after the run of ones
2587 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2588 // look for the first non-zero bit
2589 ME = 64-CountLeadingZeros_64(V);
2590 return true;
2591}
2592
2593
2594
2595/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2596/// where isSub determines whether the operator is a sub. If we can fold one of
2597/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002598///
2599/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2600/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2601/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2602///
2603/// return (A +/- B).
2604///
2605Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2606 ConstantIntegral *Mask, bool isSub,
2607 Instruction &I) {
2608 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2609 if (!LHSI || LHSI->getNumOperands() != 2 ||
2610 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2611
2612 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2613
2614 switch (LHSI->getOpcode()) {
2615 default: return 0;
2616 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002617 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2618 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2619 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2620 break;
2621
2622 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2623 // part, we don't need any explicit masks to take them out of A. If that
2624 // is all N is, ignore it.
2625 unsigned MB, ME;
2626 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002627 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2628 Mask >>= 64-MB+1;
2629 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002630 break;
2631 }
2632 }
Chris Lattneraf517572005-09-18 04:24:45 +00002633 return 0;
2634 case Instruction::Or:
2635 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002636 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2637 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2638 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002639 break;
2640 return 0;
2641 }
2642
2643 Instruction *New;
2644 if (isSub)
2645 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2646 else
2647 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2648 return InsertNewInstBefore(New, I);
2649}
2650
Chris Lattner113f4f42002-06-25 16:13:24 +00002651Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002652 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002653 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002654
Chris Lattner81a7a232004-10-16 18:11:37 +00002655 if (isa<UndefValue>(Op1)) // X & undef -> 0
2656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2657
Chris Lattner86102b82005-01-01 16:22:27 +00002658 // and X, X = X
2659 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002660 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002661
Chris Lattner5b2edb12006-02-12 08:02:11 +00002662 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002663 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002664 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002665 if (!isa<PackedType>(I.getType()) &&
2666 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002667 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002668 return &I;
2669
Chris Lattner86102b82005-01-01 16:22:27 +00002670 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002671 uint64_t AndRHSMask = AndRHS->getZExtValue();
2672 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002673 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002674
Chris Lattnerba1cb382003-09-19 17:17:26 +00002675 // Optimize a variety of ((val OP C1) & C2) combinations...
2676 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2677 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002678 Value *Op0LHS = Op0I->getOperand(0);
2679 Value *Op0RHS = Op0I->getOperand(1);
2680 switch (Op0I->getOpcode()) {
2681 case Instruction::Xor:
2682 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002683 // If the mask is only needed on one incoming arm, push it up.
2684 if (Op0I->hasOneUse()) {
2685 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2686 // Not masking anything out for the LHS, move to RHS.
2687 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2688 Op0RHS->getName()+".masked");
2689 InsertNewInstBefore(NewRHS, I);
2690 return BinaryOperator::create(
2691 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002692 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002693 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002694 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2695 // Not masking anything out for the RHS, move to LHS.
2696 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2697 Op0LHS->getName()+".masked");
2698 InsertNewInstBefore(NewLHS, I);
2699 return BinaryOperator::create(
2700 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2701 }
2702 }
2703
Chris Lattner86102b82005-01-01 16:22:27 +00002704 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002705 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002706 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2707 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2708 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2709 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2710 return BinaryOperator::createAnd(V, AndRHS);
2711 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2712 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002713 break;
2714
2715 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002716 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2717 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2718 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2719 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2720 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002721 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002722 }
2723
Chris Lattner16464b32003-07-23 19:25:52 +00002724 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002725 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002726 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002727 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2728 const Type *SrcTy = CI->getOperand(0)->getType();
2729
Chris Lattner2c14cf72005-08-07 07:03:10 +00002730 // If this is an integer truncation or change from signed-to-unsigned, and
2731 // if the source is an and/or with immediate, transform it. This
2732 // frequently occurs for bitfield accesses.
2733 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2734 if (SrcTy->getPrimitiveSizeInBits() >=
2735 I.getType()->getPrimitiveSizeInBits() &&
2736 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002737 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002738 if (CastOp->getOpcode() == Instruction::And) {
2739 // Change: and (cast (and X, C1) to T), C2
2740 // into : and (cast X to T), trunc(C1)&C2
2741 // This will folds the two ands together, which may allow other
2742 // simplifications.
2743 Instruction *NewCast =
2744 new CastInst(CastOp->getOperand(0), I.getType(),
2745 CastOp->getName()+".shrunk");
2746 NewCast = InsertNewInstBefore(NewCast, I);
2747
2748 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2749 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2750 return BinaryOperator::createAnd(NewCast, C3);
2751 } else if (CastOp->getOpcode() == Instruction::Or) {
2752 // Change: and (cast (or X, C1) to T), C2
2753 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2754 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2755 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2756 return ReplaceInstUsesWith(I, AndRHS);
2757 }
2758 }
Chris Lattner33217db2003-07-23 19:36:21 +00002759 }
Chris Lattner183b3362004-04-09 19:05:30 +00002760
2761 // Try to fold constant and into select arguments.
2762 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002763 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002764 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002765 if (isa<PHINode>(Op0))
2766 if (Instruction *NV = FoldOpIntoPhi(I))
2767 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002768 }
2769
Chris Lattnerbb74e222003-03-10 23:06:50 +00002770 Value *Op0NotVal = dyn_castNotVal(Op0);
2771 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002772
Chris Lattner023a4832004-06-18 06:07:51 +00002773 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2774 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2775
Misha Brukman9c003d82004-07-30 12:50:08 +00002776 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002777 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002778 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2779 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002780 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002781 return BinaryOperator::createNot(Or);
2782 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002783
2784 {
2785 Value *A = 0, *B = 0;
2786 ConstantInt *C1 = 0, *C2 = 0;
2787 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2788 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2789 return ReplaceInstUsesWith(I, Op1);
2790 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2791 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2792 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002793
2794 if (Op0->hasOneUse() &&
2795 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2796 if (A == Op1) { // (A^B)&A -> A&(A^B)
2797 I.swapOperands(); // Simplify below
2798 std::swap(Op0, Op1);
2799 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2800 cast<BinaryOperator>(Op0)->swapOperands();
2801 I.swapOperands(); // Simplify below
2802 std::swap(Op0, Op1);
2803 }
2804 }
2805 if (Op1->hasOneUse() &&
2806 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2807 if (B == Op0) { // B&(A^B) -> B&(B^A)
2808 cast<BinaryOperator>(Op1)->swapOperands();
2809 std::swap(A, B);
2810 }
2811 if (A == Op0) { // A&(A^B) -> A & ~B
2812 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2813 InsertNewInstBefore(NotB, I);
2814 return BinaryOperator::createAnd(A, NotB);
2815 }
2816 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002817 }
2818
Chris Lattner3082c5a2003-02-18 19:28:33 +00002819
Chris Lattner623826c2004-09-28 21:48:02 +00002820 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2821 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2823 return R;
2824
Chris Lattner623826c2004-09-28 21:48:02 +00002825 Value *LHSVal, *RHSVal;
2826 ConstantInt *LHSCst, *RHSCst;
2827 Instruction::BinaryOps LHSCC, RHSCC;
2828 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2829 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2830 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2831 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002832 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002833 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2834 // Ensure that the larger constant is on the RHS.
2835 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2836 SetCondInst *LHS = cast<SetCondInst>(Op0);
2837 if (cast<ConstantBool>(Cmp)->getValue()) {
2838 std::swap(LHS, RHS);
2839 std::swap(LHSCst, RHSCst);
2840 std::swap(LHSCC, RHSCC);
2841 }
2842
2843 // At this point, we know we have have two setcc instructions
2844 // comparing a value against two constants and and'ing the result
2845 // together. Because of the above check, we know that we only have
2846 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2847 // FoldSetCCLogical check above), that the two constants are not
2848 // equal.
2849 assert(LHSCst != RHSCst && "Compares not folded above?");
2850
2851 switch (LHSCC) {
2852 default: assert(0 && "Unknown integer condition code!");
2853 case Instruction::SetEQ:
2854 switch (RHSCC) {
2855 default: assert(0 && "Unknown integer condition code!");
2856 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2857 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2858 return ReplaceInstUsesWith(I, ConstantBool::False);
2859 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2860 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2861 return ReplaceInstUsesWith(I, LHS);
2862 }
2863 case Instruction::SetNE:
2864 switch (RHSCC) {
2865 default: assert(0 && "Unknown integer condition code!");
2866 case Instruction::SetLT:
2867 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2868 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2869 break; // (X != 13 & X < 15) -> no change
2870 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2871 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2872 return ReplaceInstUsesWith(I, RHS);
2873 case Instruction::SetNE:
2874 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2875 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2876 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2877 LHSVal->getName()+".off");
2878 InsertNewInstBefore(Add, I);
2879 const Type *UnsType = Add->getType()->getUnsignedVersion();
2880 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2881 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2882 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2883 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2884 }
2885 break; // (X != 13 & X != 15) -> no change
2886 }
2887 break;
2888 case Instruction::SetLT:
2889 switch (RHSCC) {
2890 default: assert(0 && "Unknown integer condition code!");
2891 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2892 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2893 return ReplaceInstUsesWith(I, ConstantBool::False);
2894 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2895 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2896 return ReplaceInstUsesWith(I, LHS);
2897 }
2898 case Instruction::SetGT:
2899 switch (RHSCC) {
2900 default: assert(0 && "Unknown integer condition code!");
2901 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2902 return ReplaceInstUsesWith(I, LHS);
2903 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2904 return ReplaceInstUsesWith(I, RHS);
2905 case Instruction::SetNE:
2906 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2907 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2908 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002909 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2910 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002911 }
2912 }
2913 }
2914 }
2915
Chris Lattner3af10532006-05-05 06:39:07 +00002916 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2917 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002918 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002919 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002920 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002921 // Only do this if the casts both really cause code to be generated.
2922 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2923 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002924 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2925 Op1C->getOperand(0),
2926 I.getName());
2927 InsertNewInstBefore(NewOp, I);
2928 return new CastInst(NewOp, I.getType());
2929 }
2930 }
2931
Chris Lattner113f4f42002-06-25 16:13:24 +00002932 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002933}
2934
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002935/// CollectBSwapParts - Look to see if the specified value defines a single byte
2936/// in the result. If it does, and if the specified byte hasn't been filled in
2937/// yet, fill it in and return false.
2938static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2939 Instruction *I = dyn_cast<Instruction>(V);
2940 if (I == 0) return true;
2941
2942 // If this is an or instruction, it is an inner node of the bswap.
2943 if (I->getOpcode() == Instruction::Or)
2944 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2945 CollectBSwapParts(I->getOperand(1), ByteValues);
2946
2947 // If this is a shift by a constant int, and it is "24", then its operand
2948 // defines a byte. We only handle unsigned types here.
2949 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2950 // Not shifting the entire input by N-1 bytes?
2951 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2952 8*(ByteValues.size()-1))
2953 return true;
2954
2955 unsigned DestNo;
2956 if (I->getOpcode() == Instruction::Shl) {
2957 // X << 24 defines the top byte with the lowest of the input bytes.
2958 DestNo = ByteValues.size()-1;
2959 } else {
2960 // X >>u 24 defines the low byte with the highest of the input bytes.
2961 DestNo = 0;
2962 }
2963
2964 // If the destination byte value is already defined, the values are or'd
2965 // together, which isn't a bswap (unless it's an or of the same bits).
2966 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2967 return true;
2968 ByteValues[DestNo] = I->getOperand(0);
2969 return false;
2970 }
2971
2972 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2973 // don't have this.
2974 Value *Shift = 0, *ShiftLHS = 0;
2975 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2976 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2977 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2978 return true;
2979 Instruction *SI = cast<Instruction>(Shift);
2980
2981 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2982 if (ShiftAmt->getRawValue() & 7 ||
2983 ShiftAmt->getRawValue() > 8*ByteValues.size())
2984 return true;
2985
2986 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2987 unsigned DestByte;
2988 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2989 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2990 break;
2991 // Unknown mask for bswap.
2992 if (DestByte == ByteValues.size()) return true;
2993
2994 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2995 unsigned SrcByte;
2996 if (SI->getOpcode() == Instruction::Shl)
2997 SrcByte = DestByte - ShiftBytes;
2998 else
2999 SrcByte = DestByte + ShiftBytes;
3000
3001 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3002 if (SrcByte != ByteValues.size()-DestByte-1)
3003 return true;
3004
3005 // If the destination byte value is already defined, the values are or'd
3006 // together, which isn't a bswap (unless it's an or of the same bits).
3007 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3008 return true;
3009 ByteValues[DestByte] = SI->getOperand(0);
3010 return false;
3011}
3012
3013/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3014/// If so, insert the new bswap intrinsic and return it.
3015Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3016 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3017 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3018 return 0;
3019
3020 /// ByteValues - For each byte of the result, we keep track of which value
3021 /// defines each byte.
3022 std::vector<Value*> ByteValues;
3023 ByteValues.resize(I.getType()->getPrimitiveSize());
3024
3025 // Try to find all the pieces corresponding to the bswap.
3026 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3027 CollectBSwapParts(I.getOperand(1), ByteValues))
3028 return 0;
3029
3030 // Check to see if all of the bytes come from the same value.
3031 Value *V = ByteValues[0];
3032 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3033
3034 // Check to make sure that all of the bytes come from the same value.
3035 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3036 if (ByteValues[i] != V)
3037 return 0;
3038
3039 // If they do then *success* we can turn this into a bswap. Figure out what
3040 // bswap to make it into.
3041 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003042 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003043 if (I.getType() == Type::UShortTy)
3044 FnName = "llvm.bswap.i16";
3045 else if (I.getType() == Type::UIntTy)
3046 FnName = "llvm.bswap.i32";
3047 else if (I.getType() == Type::ULongTy)
3048 FnName = "llvm.bswap.i64";
3049 else
3050 assert(0 && "Unknown integer type!");
3051 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3052
3053 return new CallInst(F, V);
3054}
3055
3056
Chris Lattner113f4f42002-06-25 16:13:24 +00003057Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003058 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003060
Chris Lattner81a7a232004-10-16 18:11:37 +00003061 if (isa<UndefValue>(Op1))
3062 return ReplaceInstUsesWith(I, // X | undef -> -1
3063 ConstantIntegral::getAllOnesValue(I.getType()));
3064
Chris Lattner5b2edb12006-02-12 08:02:11 +00003065 // or X, X = X
3066 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003067 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003068
Chris Lattner5b2edb12006-02-12 08:02:11 +00003069 // See if we can simplify any instructions used by the instruction whose sole
3070 // purpose is to compute bits we don't care about.
3071 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003072 if (!isa<PackedType>(I.getType()) &&
3073 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003074 KnownZero, KnownOne))
3075 return &I;
3076
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003077 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003078 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003079 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003080 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3081 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003082 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3083 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003084 InsertNewInstBefore(Or, I);
3085 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3086 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003087
Chris Lattnerd4252a72004-07-30 07:50:03 +00003088 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3089 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3090 std::string Op0Name = Op0->getName(); Op0->setName("");
3091 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3092 InsertNewInstBefore(Or, I);
3093 return BinaryOperator::createXor(Or,
3094 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003095 }
Chris Lattner183b3362004-04-09 19:05:30 +00003096
3097 // Try to fold constant and into select arguments.
3098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003100 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003101 if (isa<PHINode>(Op0))
3102 if (Instruction *NV = FoldOpIntoPhi(I))
3103 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003104 }
3105
Chris Lattner330628a2006-01-06 17:59:59 +00003106 Value *A = 0, *B = 0;
3107 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003108
3109 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3110 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3111 return ReplaceInstUsesWith(I, Op1);
3112 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3113 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3114 return ReplaceInstUsesWith(I, Op0);
3115
Chris Lattnerb7845d62006-07-10 20:25:24 +00003116 // (A | B) | C and A | (B | C) -> bswap if possible.
3117 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003118 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003119 match(Op1, m_Or(m_Value(), m_Value())) ||
3120 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3121 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003122 if (Instruction *BSwap = MatchBSwap(I))
3123 return BSwap;
3124 }
3125
Chris Lattnerb62f5082005-05-09 04:58:36 +00003126 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3127 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003128 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003129 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3130 Op0->setName("");
3131 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3132 }
3133
3134 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3135 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003136 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003137 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3138 Op0->setName("");
3139 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3140 }
3141
Chris Lattner15212982005-09-18 03:42:07 +00003142 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003143 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003144 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3145
3146 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3147 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3148
3149
Chris Lattner01f56c62005-09-18 06:02:59 +00003150 // If we have: ((V + N) & C1) | (V & C2)
3151 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3152 // replace with V+N.
3153 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003154 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003155 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3156 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3157 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003158 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003159 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003160 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003161 return ReplaceInstUsesWith(I, A);
3162 }
3163 // Or commutes, try both ways.
3164 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3165 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3166 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003167 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003168 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003169 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003170 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003171 }
3172 }
3173 }
Chris Lattner812aab72003-08-12 19:11:07 +00003174
Chris Lattnerd4252a72004-07-30 07:50:03 +00003175 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3176 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003177 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003178 ConstantIntegral::getAllOnesValue(I.getType()));
3179 } else {
3180 A = 0;
3181 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003182 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003183 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3184 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003185 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003186 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003187
Misha Brukman9c003d82004-07-30 12:50:08 +00003188 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003189 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3190 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3191 I.getName()+".demorgan"), I);
3192 return BinaryOperator::createNot(And);
3193 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003194 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003195
Chris Lattner3ac7c262003-08-13 20:16:26 +00003196 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003197 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003198 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3199 return R;
3200
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003201 Value *LHSVal, *RHSVal;
3202 ConstantInt *LHSCst, *RHSCst;
3203 Instruction::BinaryOps LHSCC, RHSCC;
3204 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3205 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3206 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3207 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003208 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003209 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3210 // Ensure that the larger constant is on the RHS.
3211 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3212 SetCondInst *LHS = cast<SetCondInst>(Op0);
3213 if (cast<ConstantBool>(Cmp)->getValue()) {
3214 std::swap(LHS, RHS);
3215 std::swap(LHSCst, RHSCst);
3216 std::swap(LHSCC, RHSCC);
3217 }
3218
3219 // At this point, we know we have have two setcc instructions
3220 // comparing a value against two constants and or'ing the result
3221 // together. Because of the above check, we know that we only have
3222 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3223 // FoldSetCCLogical check above), that the two constants are not
3224 // equal.
3225 assert(LHSCst != RHSCst && "Compares not folded above?");
3226
3227 switch (LHSCC) {
3228 default: assert(0 && "Unknown integer condition code!");
3229 case Instruction::SetEQ:
3230 switch (RHSCC) {
3231 default: assert(0 && "Unknown integer condition code!");
3232 case Instruction::SetEQ:
3233 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3234 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3235 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3236 LHSVal->getName()+".off");
3237 InsertNewInstBefore(Add, I);
3238 const Type *UnsType = Add->getType()->getUnsignedVersion();
3239 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3240 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3241 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3242 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3243 }
3244 break; // (X == 13 | X == 15) -> no change
3245
Chris Lattner5c219462005-04-19 06:04:18 +00003246 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3247 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003248 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3249 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3250 return ReplaceInstUsesWith(I, RHS);
3251 }
3252 break;
3253 case Instruction::SetNE:
3254 switch (RHSCC) {
3255 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003256 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3257 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3258 return ReplaceInstUsesWith(I, LHS);
3259 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003260 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003261 return ReplaceInstUsesWith(I, ConstantBool::True);
3262 }
3263 break;
3264 case Instruction::SetLT:
3265 switch (RHSCC) {
3266 default: assert(0 && "Unknown integer condition code!");
3267 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3268 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003269 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3270 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003271 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3272 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3273 return ReplaceInstUsesWith(I, RHS);
3274 }
3275 break;
3276 case Instruction::SetGT:
3277 switch (RHSCC) {
3278 default: assert(0 && "Unknown integer condition code!");
3279 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3280 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3281 return ReplaceInstUsesWith(I, LHS);
3282 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3283 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3284 return ReplaceInstUsesWith(I, ConstantBool::True);
3285 }
3286 }
3287 }
3288 }
Chris Lattner3af10532006-05-05 06:39:07 +00003289
3290 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3291 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003292 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003293 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003294 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003295 // Only do this if the casts both really cause code to be generated.
3296 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3297 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003298 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3299 Op1C->getOperand(0),
3300 I.getName());
3301 InsertNewInstBefore(NewOp, I);
3302 return new CastInst(NewOp, I.getType());
3303 }
3304 }
3305
Chris Lattner15212982005-09-18 03:42:07 +00003306
Chris Lattner113f4f42002-06-25 16:13:24 +00003307 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003308}
3309
Chris Lattnerc2076352004-02-16 01:20:27 +00003310// XorSelf - Implements: X ^ X --> 0
3311struct XorSelf {
3312 Value *RHS;
3313 XorSelf(Value *rhs) : RHS(rhs) {}
3314 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3315 Instruction *apply(BinaryOperator &Xor) const {
3316 return &Xor;
3317 }
3318};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003319
3320
Chris Lattner113f4f42002-06-25 16:13:24 +00003321Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003322 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003324
Chris Lattner81a7a232004-10-16 18:11:37 +00003325 if (isa<UndefValue>(Op1))
3326 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3327
Chris Lattnerc2076352004-02-16 01:20:27 +00003328 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3329 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3330 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003331 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003332 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003333
3334 // See if we can simplify any instructions used by the instruction whose sole
3335 // purpose is to compute bits we don't care about.
3336 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003337 if (!isa<PackedType>(I.getType()) &&
3338 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003339 KnownZero, KnownOne))
3340 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003341
Chris Lattner97638592003-07-23 21:37:07 +00003342 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003343 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003344 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003345 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003346 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003347 return new SetCondInst(SCI->getInverseCondition(),
3348 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003349
Chris Lattner8f2f5982003-11-05 01:06:05 +00003350 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003351 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3352 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003353 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3354 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003355 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003356 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003357 }
Chris Lattner023a4832004-06-18 06:07:51 +00003358
3359 // ~(~X & Y) --> (X | ~Y)
3360 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3361 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3362 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3363 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003364 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003365 Op0I->getOperand(1)->getName()+".not");
3366 InsertNewInstBefore(NotY, I);
3367 return BinaryOperator::createOr(Op0NotVal, NotY);
3368 }
3369 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003370
Chris Lattner97638592003-07-23 21:37:07 +00003371 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003372 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003373 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003374 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003375 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3376 return BinaryOperator::createSub(
3377 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003378 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003379 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003380 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003381 } else if (Op0I->getOpcode() == Instruction::Or) {
3382 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3383 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3384 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3385 // Anything in both C1 and C2 is known to be zero, remove it from
3386 // NewRHS.
3387 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3388 NewRHS = ConstantExpr::getAnd(NewRHS,
3389 ConstantExpr::getNot(CommonBits));
3390 WorkList.push_back(Op0I);
3391 I.setOperand(0, Op0I->getOperand(0));
3392 I.setOperand(1, NewRHS);
3393 return &I;
3394 }
Chris Lattner97638592003-07-23 21:37:07 +00003395 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003396 }
Chris Lattner183b3362004-04-09 19:05:30 +00003397
3398 // Try to fold constant and into select arguments.
3399 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003400 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003401 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003402 if (isa<PHINode>(Op0))
3403 if (Instruction *NV = FoldOpIntoPhi(I))
3404 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003405 }
3406
Chris Lattnerbb74e222003-03-10 23:06:50 +00003407 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003408 if (X == Op1)
3409 return ReplaceInstUsesWith(I,
3410 ConstantIntegral::getAllOnesValue(I.getType()));
3411
Chris Lattnerbb74e222003-03-10 23:06:50 +00003412 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003413 if (X == Op0)
3414 return ReplaceInstUsesWith(I,
3415 ConstantIntegral::getAllOnesValue(I.getType()));
3416
Chris Lattnerdcd07922006-04-01 08:03:55 +00003417 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003418 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003419 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003420 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003421 I.swapOperands();
3422 std::swap(Op0, Op1);
3423 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003424 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003425 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003426 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003427 } else if (Op1I->getOpcode() == Instruction::Xor) {
3428 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3429 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3430 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3431 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003432 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3433 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3434 Op1I->swapOperands();
3435 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3436 I.swapOperands(); // Simplified below.
3437 std::swap(Op0, Op1);
3438 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003439 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003440
Chris Lattnerdcd07922006-04-01 08:03:55 +00003441 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003442 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003443 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003444 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003445 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003446 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3447 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003448 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003449 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003450 } else if (Op0I->getOpcode() == Instruction::Xor) {
3451 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3452 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3453 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3454 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003455 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3456 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3457 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003458 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3459 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003460 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3461 InsertNewInstBefore(N, I);
3462 return BinaryOperator::createAnd(N, Op1);
3463 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003464 }
3465
Chris Lattner3ac7c262003-08-13 20:16:26 +00003466 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3467 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3468 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3469 return R;
3470
Chris Lattner3af10532006-05-05 06:39:07 +00003471 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3472 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003473 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003474 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003475 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003476 // Only do this if the casts both really cause code to be generated.
3477 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3478 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003479 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3480 Op1C->getOperand(0),
3481 I.getName());
3482 InsertNewInstBefore(NewOp, I);
3483 return new CastInst(NewOp, I.getType());
3484 }
3485 }
3486
Chris Lattner113f4f42002-06-25 16:13:24 +00003487 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003488}
3489
Chris Lattner6862fbd2004-09-29 17:40:11 +00003490/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3491/// overflowed for this type.
3492static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3493 ConstantInt *In2) {
3494 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3495 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3496}
3497
3498static bool isPositive(ConstantInt *C) {
3499 return cast<ConstantSInt>(C)->getValue() >= 0;
3500}
3501
3502/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3503/// overflowed for this type.
3504static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3505 ConstantInt *In2) {
3506 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3507
3508 if (In1->getType()->isUnsigned())
3509 return cast<ConstantUInt>(Result)->getValue() <
3510 cast<ConstantUInt>(In1)->getValue();
3511 if (isPositive(In1) != isPositive(In2))
3512 return false;
3513 if (isPositive(In1))
3514 return cast<ConstantSInt>(Result)->getValue() <
3515 cast<ConstantSInt>(In1)->getValue();
3516 return cast<ConstantSInt>(Result)->getValue() >
3517 cast<ConstantSInt>(In1)->getValue();
3518}
3519
Chris Lattner0798af32005-01-13 20:14:25 +00003520/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3521/// code necessary to compute the offset from the base pointer (without adding
3522/// in the base pointer). Return the result as a signed integer of intptr size.
3523static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3524 TargetData &TD = IC.getTargetData();
3525 gep_type_iterator GTI = gep_type_begin(GEP);
3526 const Type *UIntPtrTy = TD.getIntPtrType();
3527 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3528 Value *Result = Constant::getNullValue(SIntPtrTy);
3529
3530 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003531 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003532
Chris Lattner0798af32005-01-13 20:14:25 +00003533 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3534 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003535 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003536 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3537 SIntPtrTy);
3538 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3539 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003540 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003541 Scale = ConstantExpr::getMul(OpC, Scale);
3542 if (Constant *RC = dyn_cast<Constant>(Result))
3543 Result = ConstantExpr::getAdd(RC, Scale);
3544 else {
3545 // Emit an add instruction.
3546 Result = IC.InsertNewInstBefore(
3547 BinaryOperator::createAdd(Result, Scale,
3548 GEP->getName()+".offs"), I);
3549 }
3550 }
3551 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003552 // Convert to correct type.
3553 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3554 Op->getName()+".c"), I);
3555 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003556 // We'll let instcombine(mul) convert this to a shl if possible.
3557 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3558 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003559
3560 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003561 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003562 GEP->getName()+".offs"), I);
3563 }
3564 }
3565 return Result;
3566}
3567
3568/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3569/// else. At this point we know that the GEP is on the LHS of the comparison.
3570Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3571 Instruction::BinaryOps Cond,
3572 Instruction &I) {
3573 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003574
3575 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3576 if (isa<PointerType>(CI->getOperand(0)->getType()))
3577 RHS = CI->getOperand(0);
3578
Chris Lattner0798af32005-01-13 20:14:25 +00003579 Value *PtrBase = GEPLHS->getOperand(0);
3580 if (PtrBase == RHS) {
3581 // As an optimization, we don't actually have to compute the actual value of
3582 // OFFSET if this is a seteq or setne comparison, just return whether each
3583 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003584 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3585 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003586 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3587 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003588 bool EmitIt = true;
3589 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3590 if (isa<UndefValue>(C)) // undef index -> undef.
3591 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3592 if (C->isNullValue())
3593 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003594 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3595 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003596 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003597 return ReplaceInstUsesWith(I, // No comparison is needed here.
3598 ConstantBool::get(Cond == Instruction::SetNE));
3599 }
3600
3601 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003602 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003603 new SetCondInst(Cond, GEPLHS->getOperand(i),
3604 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3605 if (InVal == 0)
3606 InVal = Comp;
3607 else {
3608 InVal = InsertNewInstBefore(InVal, I);
3609 InsertNewInstBefore(Comp, I);
3610 if (Cond == Instruction::SetNE) // True if any are unequal
3611 InVal = BinaryOperator::createOr(InVal, Comp);
3612 else // True if all are equal
3613 InVal = BinaryOperator::createAnd(InVal, Comp);
3614 }
3615 }
3616 }
3617
3618 if (InVal)
3619 return InVal;
3620 else
3621 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3622 ConstantBool::get(Cond == Instruction::SetEQ));
3623 }
Chris Lattner0798af32005-01-13 20:14:25 +00003624
3625 // Only lower this if the setcc is the only user of the GEP or if we expect
3626 // the result to fold to a constant!
3627 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3628 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3629 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3630 return new SetCondInst(Cond, Offset,
3631 Constant::getNullValue(Offset->getType()));
3632 }
3633 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003634 // If the base pointers are different, but the indices are the same, just
3635 // compare the base pointer.
3636 if (PtrBase != GEPRHS->getOperand(0)) {
3637 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003638 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003639 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003640 if (IndicesTheSame)
3641 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3642 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3643 IndicesTheSame = false;
3644 break;
3645 }
3646
3647 // If all indices are the same, just compare the base pointers.
3648 if (IndicesTheSame)
3649 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3650 GEPRHS->getOperand(0));
3651
3652 // Otherwise, the base pointers are different and the indices are
3653 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003654 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003655 }
Chris Lattner0798af32005-01-13 20:14:25 +00003656
Chris Lattner81e84172005-01-13 22:25:21 +00003657 // If one of the GEPs has all zero indices, recurse.
3658 bool AllZeros = true;
3659 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3660 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3661 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3662 AllZeros = false;
3663 break;
3664 }
3665 if (AllZeros)
3666 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3667 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003668
3669 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003670 AllZeros = true;
3671 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3672 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3673 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3674 AllZeros = false;
3675 break;
3676 }
3677 if (AllZeros)
3678 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3679
Chris Lattner4fa89822005-01-14 00:20:05 +00003680 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3681 // If the GEPs only differ by one index, compare it.
3682 unsigned NumDifferences = 0; // Keep track of # differences.
3683 unsigned DiffOperand = 0; // The operand that differs.
3684 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3685 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003686 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3687 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003688 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003689 NumDifferences = 2;
3690 break;
3691 } else {
3692 if (NumDifferences++) break;
3693 DiffOperand = i;
3694 }
3695 }
3696
3697 if (NumDifferences == 0) // SAME GEP?
3698 return ReplaceInstUsesWith(I, // No comparison is needed here.
3699 ConstantBool::get(Cond == Instruction::SetEQ));
3700 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003701 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3702 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003703
3704 // Convert the operands to signed values to make sure to perform a
3705 // signed comparison.
3706 const Type *NewTy = LHSV->getType()->getSignedVersion();
3707 if (LHSV->getType() != NewTy)
3708 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3709 LHSV->getName()), I);
3710 if (RHSV->getType() != NewTy)
3711 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3712 RHSV->getName()), I);
3713 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003714 }
3715 }
3716
Chris Lattner0798af32005-01-13 20:14:25 +00003717 // Only lower this if the setcc is the only user of the GEP or if we expect
3718 // the result to fold to a constant!
3719 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3720 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3721 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3722 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3723 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3724 return new SetCondInst(Cond, L, R);
3725 }
3726 }
3727 return 0;
3728}
3729
3730
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003731Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003732 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3734 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003735
3736 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003737 if (Op0 == Op1)
3738 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003739
Chris Lattner81a7a232004-10-16 18:11:37 +00003740 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3741 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3742
Chris Lattner15ff1e12004-11-14 07:33:16 +00003743 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3744 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3746 isa<ConstantPointerNull>(Op0)) &&
3747 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003748 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003749 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3750
3751 // setcc's with boolean values can always be turned into bitwise operations
3752 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003753 switch (I.getOpcode()) {
3754 default: assert(0 && "Invalid setcc instruction!");
3755 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003756 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003757 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003758 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003759 }
Chris Lattner4456da62004-08-11 00:50:51 +00003760 case Instruction::SetNE:
3761 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003762
Chris Lattner4456da62004-08-11 00:50:51 +00003763 case Instruction::SetGT:
3764 std::swap(Op0, Op1); // Change setgt -> setlt
3765 // FALL THROUGH
3766 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3767 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3768 InsertNewInstBefore(Not, I);
3769 return BinaryOperator::createAnd(Not, Op1);
3770 }
3771 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003772 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003773 // FALL THROUGH
3774 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3775 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3776 InsertNewInstBefore(Not, I);
3777 return BinaryOperator::createOr(Not, Op1);
3778 }
3779 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003780 }
3781
Chris Lattner2dd01742004-06-09 04:24:29 +00003782 // See if we are doing a comparison between a constant and an instruction that
3783 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003784 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003785 // Check to see if we are comparing against the minimum or maximum value...
3786 if (CI->isMinValue()) {
3787 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3788 return ReplaceInstUsesWith(I, ConstantBool::False);
3789 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3790 return ReplaceInstUsesWith(I, ConstantBool::True);
3791 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3792 return BinaryOperator::createSetEQ(Op0, Op1);
3793 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3794 return BinaryOperator::createSetNE(Op0, Op1);
3795
3796 } else if (CI->isMaxValue()) {
3797 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3798 return ReplaceInstUsesWith(I, ConstantBool::False);
3799 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3800 return ReplaceInstUsesWith(I, ConstantBool::True);
3801 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3802 return BinaryOperator::createSetEQ(Op0, Op1);
3803 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3804 return BinaryOperator::createSetNE(Op0, Op1);
3805
3806 // Comparing against a value really close to min or max?
3807 } else if (isMinValuePlusOne(CI)) {
3808 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3809 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3810 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3811 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3812
3813 } else if (isMaxValueMinusOne(CI)) {
3814 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3815 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3816 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3817 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3818 }
3819
3820 // If we still have a setle or setge instruction, turn it into the
3821 // appropriate setlt or setgt instruction. Since the border cases have
3822 // already been handled above, this requires little checking.
3823 //
3824 if (I.getOpcode() == Instruction::SetLE)
3825 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3826 if (I.getOpcode() == Instruction::SetGE)
3827 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3828
Chris Lattneree0f2802006-02-12 02:07:56 +00003829
3830 // See if we can fold the comparison based on bits known to be zero or one
3831 // in the input.
3832 uint64_t KnownZero, KnownOne;
3833 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3834 KnownZero, KnownOne, 0))
3835 return &I;
3836
3837 // Given the known and unknown bits, compute a range that the LHS could be
3838 // in.
3839 if (KnownOne | KnownZero) {
3840 if (Ty->isUnsigned()) { // Unsigned comparison.
3841 uint64_t Min, Max;
3842 uint64_t RHSVal = CI->getZExtValue();
3843 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3844 Min, Max);
3845 switch (I.getOpcode()) { // LE/GE have been folded already.
3846 default: assert(0 && "Unknown setcc opcode!");
3847 case Instruction::SetEQ:
3848 if (Max < RHSVal || Min > RHSVal)
3849 return ReplaceInstUsesWith(I, ConstantBool::False);
3850 break;
3851 case Instruction::SetNE:
3852 if (Max < RHSVal || Min > RHSVal)
3853 return ReplaceInstUsesWith(I, ConstantBool::True);
3854 break;
3855 case Instruction::SetLT:
3856 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3857 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3858 break;
3859 case Instruction::SetGT:
3860 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3861 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3862 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)
3873 return ReplaceInstUsesWith(I, ConstantBool::False);
3874 break;
3875 case Instruction::SetNE:
3876 if (Max < RHSVal || Min > RHSVal)
3877 return ReplaceInstUsesWith(I, ConstantBool::True);
3878 break;
3879 case Instruction::SetLT:
3880 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3881 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3882 break;
3883 case Instruction::SetGT:
3884 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3885 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3886 break;
3887 }
3888 }
3889 }
3890
3891
Chris Lattnere1e10e12004-05-25 06:32:08 +00003892 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003893 switch (LHSI->getOpcode()) {
3894 case Instruction::And:
3895 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3896 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00003897 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3898
3899 // If an operand is an AND of a truncating cast, we can widen the
3900 // and/compare to be the input width without changing the value
3901 // produced, eliminating a cast.
3902 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
3903 // We can do this transformation if either the AND constant does not
3904 // have its sign bit set or if it is an equality comparison.
3905 // Extending a relational comparison when we're checking the sign
3906 // bit would not work.
3907 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
3908 (I.isEquality() ||
3909 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
3910 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
3911 ConstantInt *NewCST;
3912 ConstantInt *NewCI;
3913 if (Cast->getOperand(0)->getType()->isSigned()) {
3914 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
3915 AndCST->getZExtValue());
3916 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
3917 CI->getZExtValue());
3918 } else {
3919 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
3920 AndCST->getZExtValue());
3921 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
3922 CI->getZExtValue());
3923 }
3924 Instruction *NewAnd =
3925 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
3926 LHSI->getName());
3927 InsertNewInstBefore(NewAnd, I);
3928 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
3929 }
3930 }
3931
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003932 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3933 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3934 // happens a LOT in code produced by the C front-end, for bitfield
3935 // access.
3936 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003937
3938 // Check to see if there is a noop-cast between the shift and the and.
3939 if (!Shift) {
3940 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3941 if (CI->getOperand(0)->getType()->isIntegral() &&
3942 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3943 CI->getType()->getPrimitiveSizeInBits())
3944 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3945 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003946
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003947 ConstantUInt *ShAmt;
3948 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003949 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3950 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003951
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003952 // We can fold this as long as we can't shift unknown bits
3953 // into the mask. This can only happen with signed shift
3954 // rights, as they sign-extend.
3955 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003956 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003957 if (!CanFold) {
3958 // To test for the bad case of the signed shr, see if any
3959 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003960 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3961 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3962
3963 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003964 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003965 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3966 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003967 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3968 CanFold = true;
3969 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003970
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003971 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003972 Constant *NewCst;
3973 if (Shift->getOpcode() == Instruction::Shl)
3974 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3975 else
3976 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003977
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003978 // Check to see if we are shifting out any of the bits being
3979 // compared.
3980 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3981 // If we shifted bits out, the fold is not going to work out.
3982 // As a special case, check to see if this means that the
3983 // result is always true or false now.
3984 if (I.getOpcode() == Instruction::SetEQ)
3985 return ReplaceInstUsesWith(I, ConstantBool::False);
3986 if (I.getOpcode() == Instruction::SetNE)
3987 return ReplaceInstUsesWith(I, ConstantBool::True);
3988 } else {
3989 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003990 Constant *NewAndCST;
3991 if (Shift->getOpcode() == Instruction::Shl)
3992 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3993 else
3994 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3995 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003996 if (AndTy == Ty)
3997 LHSI->setOperand(0, Shift->getOperand(0));
3998 else {
3999 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4000 *Shift);
4001 LHSI->setOperand(0, NewCast);
4002 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004003 WorkList.push_back(Shift); // Shift is dead.
4004 AddUsesToWorkList(I);
4005 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004006 }
4007 }
Chris Lattner35167c32004-06-09 07:59:58 +00004008 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004009
4010 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4011 // preferable because it allows the C<<Y expression to be hoisted out
4012 // of a loop if Y is invariant and X is not.
4013 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004014 I.isEquality() && !Shift->isArithmeticShift() &&
4015 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004016 // Compute C << Y.
4017 Value *NS;
4018 if (Shift->getOpcode() == Instruction::Shr) {
4019 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4020 "tmp");
4021 } else {
4022 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004023 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004024 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004025 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004026 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004027 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4028 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004029 }
4030 InsertNewInstBefore(cast<Instruction>(NS), I);
4031
4032 // If C's sign doesn't agree with the and, insert a cast now.
4033 if (NS->getType() != LHSI->getType())
4034 NS = InsertCastBefore(NS, LHSI->getType(), I);
4035
4036 Value *ShiftOp = Shift->getOperand(0);
4037 if (ShiftOp->getType() != LHSI->getType())
4038 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4039
4040 // Compute X & (C << Y).
4041 Instruction *NewAnd =
4042 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4043 InsertNewInstBefore(NewAnd, I);
4044
4045 I.setOperand(0, NewAnd);
4046 return &I;
4047 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004048 }
4049 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004050
Chris Lattner272d5ca2004-09-28 18:22:15 +00004051 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4052 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004053 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004054 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4055
4056 // Check that the shift amount is in range. If not, don't perform
4057 // undefined shifts. When the shift is visited it will be
4058 // simplified.
4059 if (ShAmt->getValue() >= TypeBits)
4060 break;
4061
Chris Lattner272d5ca2004-09-28 18:22:15 +00004062 // If we are comparing against bits always shifted out, the
4063 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004064 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004065 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4066 if (Comp != CI) {// Comparing against a bit that we know is zero.
4067 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4068 Constant *Cst = ConstantBool::get(IsSetNE);
4069 return ReplaceInstUsesWith(I, Cst);
4070 }
4071
4072 if (LHSI->hasOneUse()) {
4073 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004074 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004075 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4076
4077 Constant *Mask;
4078 if (CI->getType()->isUnsigned()) {
4079 Mask = ConstantUInt::get(CI->getType(), Val);
4080 } else if (ShAmtVal != 0) {
4081 Mask = ConstantSInt::get(CI->getType(), Val);
4082 } else {
4083 Mask = ConstantInt::getAllOnesValue(CI->getType());
4084 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004085
Chris Lattner272d5ca2004-09-28 18:22:15 +00004086 Instruction *AndI =
4087 BinaryOperator::createAnd(LHSI->getOperand(0),
4088 Mask, LHSI->getName()+".mask");
4089 Value *And = InsertNewInstBefore(AndI, I);
4090 return new SetCondInst(I.getOpcode(), And,
4091 ConstantExpr::getUShr(CI, ShAmt));
4092 }
4093 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004094 }
4095 break;
4096
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004097 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00004098 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004099 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004100 // Check that the shift amount is in range. If not, don't perform
4101 // undefined shifts. When the shift is visited it will be
4102 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004103 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00004104 if (ShAmt->getValue() >= TypeBits)
4105 break;
4106
Chris Lattner1023b872004-09-27 16:18:50 +00004107 // If we are comparing against bits always shifted out, the
4108 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004109 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004110 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004111
Chris Lattner1023b872004-09-27 16:18:50 +00004112 if (Comp != CI) {// Comparing against a bit that we know is zero.
4113 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4114 Constant *Cst = ConstantBool::get(IsSetNE);
4115 return ReplaceInstUsesWith(I, Cst);
4116 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004117
Chris Lattner1023b872004-09-27 16:18:50 +00004118 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004119 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004120
Chris Lattner1023b872004-09-27 16:18:50 +00004121 // Otherwise strength reduce the shift into an and.
4122 uint64_t Val = ~0ULL; // All ones.
4123 Val <<= ShAmtVal; // Shift over to the right spot.
4124
4125 Constant *Mask;
4126 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004127 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00004128 Mask = ConstantUInt::get(CI->getType(), Val);
4129 } else {
4130 Mask = ConstantSInt::get(CI->getType(), Val);
4131 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004132
Chris Lattner1023b872004-09-27 16:18:50 +00004133 Instruction *AndI =
4134 BinaryOperator::createAnd(LHSI->getOperand(0),
4135 Mask, LHSI->getName()+".mask");
4136 Value *And = InsertNewInstBefore(AndI, I);
4137 return new SetCondInst(I.getOpcode(), And,
4138 ConstantExpr::getShl(CI, ShAmt));
4139 }
Chris Lattner1023b872004-09-27 16:18:50 +00004140 }
4141 }
4142 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004143
Chris Lattner6862fbd2004-09-29 17:40:11 +00004144 case Instruction::Div:
4145 // Fold: (div X, C1) op C2 -> range check
4146 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4147 // Fold this div into the comparison, producing a range check.
4148 // Determine, based on the divide type, what the range is being
4149 // checked. If there is an overflow on the low or high side, remember
4150 // it, otherwise compute the range [low, hi) bounding the new value.
4151 bool LoOverflow = false, HiOverflow = 0;
4152 ConstantInt *LoBound = 0, *HiBound = 0;
4153
4154 ConstantInt *Prod;
4155 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4156
Chris Lattnera92af962004-10-11 19:40:04 +00004157 Instruction::BinaryOps Opcode = I.getOpcode();
4158
Chris Lattner6862fbd2004-09-29 17:40:11 +00004159 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4160 } else if (LHSI->getType()->isUnsigned()) { // udiv
4161 LoBound = Prod;
4162 LoOverflow = ProdOV;
4163 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4164 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4165 if (CI->isNullValue()) { // (X / pos) op 0
4166 // Can't overflow.
4167 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4168 HiBound = DivRHS;
4169 } else if (isPositive(CI)) { // (X / pos) op pos
4170 LoBound = Prod;
4171 LoOverflow = ProdOV;
4172 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4173 } else { // (X / pos) op neg
4174 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4175 LoOverflow = AddWithOverflow(LoBound, Prod,
4176 cast<ConstantInt>(DivRHSH));
4177 HiBound = Prod;
4178 HiOverflow = ProdOV;
4179 }
4180 } else { // Divisor is < 0.
4181 if (CI->isNullValue()) { // (X / neg) op 0
4182 LoBound = AddOne(DivRHS);
4183 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004184 if (HiBound == DivRHS)
4185 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004186 } else if (isPositive(CI)) { // (X / neg) op pos
4187 HiOverflow = LoOverflow = ProdOV;
4188 if (!LoOverflow)
4189 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4190 HiBound = AddOne(Prod);
4191 } else { // (X / neg) op neg
4192 LoBound = Prod;
4193 LoOverflow = HiOverflow = ProdOV;
4194 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4195 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004196
Chris Lattnera92af962004-10-11 19:40:04 +00004197 // Dividing by a negate swaps the condition.
4198 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004199 }
4200
4201 if (LoBound) {
4202 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004203 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004204 default: assert(0 && "Unhandled setcc opcode!");
4205 case Instruction::SetEQ:
4206 if (LoOverflow && HiOverflow)
4207 return ReplaceInstUsesWith(I, ConstantBool::False);
4208 else if (HiOverflow)
4209 return new SetCondInst(Instruction::SetGE, X, LoBound);
4210 else if (LoOverflow)
4211 return new SetCondInst(Instruction::SetLT, X, HiBound);
4212 else
4213 return InsertRangeTest(X, LoBound, HiBound, true, I);
4214 case Instruction::SetNE:
4215 if (LoOverflow && HiOverflow)
4216 return ReplaceInstUsesWith(I, ConstantBool::True);
4217 else if (HiOverflow)
4218 return new SetCondInst(Instruction::SetLT, X, LoBound);
4219 else if (LoOverflow)
4220 return new SetCondInst(Instruction::SetGE, X, HiBound);
4221 else
4222 return InsertRangeTest(X, LoBound, HiBound, false, I);
4223 case Instruction::SetLT:
4224 if (LoOverflow)
4225 return ReplaceInstUsesWith(I, ConstantBool::False);
4226 return new SetCondInst(Instruction::SetLT, X, LoBound);
4227 case Instruction::SetGT:
4228 if (HiOverflow)
4229 return ReplaceInstUsesWith(I, ConstantBool::False);
4230 return new SetCondInst(Instruction::SetGE, X, HiBound);
4231 }
4232 }
4233 }
4234 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004235 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004236
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004237 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004238 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004239 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4240
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004241 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004242 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4244 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004245 case Instruction::Rem:
4246 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4247 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4248 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004249 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4250 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4251 if (isPowerOf2_64(V)) {
4252 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004253 const Type *UTy = BO->getType()->getUnsignedVersion();
4254 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4255 UTy, "tmp"), I);
4256 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4257 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4258 RHSCst, BO->getName()), I);
4259 return BinaryOperator::create(I.getOpcode(), NewRem,
4260 Constant::getNullValue(UTy));
4261 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004262 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004263 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004264
Chris Lattnerc992add2003-08-13 05:33:12 +00004265 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004266 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4267 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004268 if (BO->hasOneUse())
4269 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4270 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004271 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004272 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4273 // efficiently invertible, or if the add has just this one use.
4274 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004275
Chris Lattnerc992add2003-08-13 05:33:12 +00004276 if (Value *NegVal = dyn_castNegVal(BOp1))
4277 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4278 else if (Value *NegVal = dyn_castNegVal(BOp0))
4279 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004280 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004281 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4282 BO->setName("");
4283 InsertNewInstBefore(Neg, I);
4284 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4285 }
4286 }
4287 break;
4288 case Instruction::Xor:
4289 // For the xor case, we can xor two constants together, eliminating
4290 // the explicit xor.
4291 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4292 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004293 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004294
4295 // FALLTHROUGH
4296 case Instruction::Sub:
4297 // Replace (([sub|xor] A, B) != 0) with (A != B)
4298 if (CI->isNullValue())
4299 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4300 BO->getOperand(1));
4301 break;
4302
4303 case Instruction::Or:
4304 // If bits are being or'd in that are not present in the constant we
4305 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004306 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004307 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004308 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004309 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004310 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004311 break;
4312
4313 case Instruction::And:
4314 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004315 // If bits are being compared against that are and'd out, then the
4316 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004317 if (!ConstantExpr::getAnd(CI,
4318 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004319 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004320
Chris Lattner35167c32004-06-09 07:59:58 +00004321 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004322 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004323 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4324 Instruction::SetNE, Op0,
4325 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004326
Chris Lattnerc992add2003-08-13 05:33:12 +00004327 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4328 // to be a signed value as appropriate.
4329 if (isSignBit(BOC)) {
4330 Value *X = BO->getOperand(0);
4331 // If 'X' is not signed, insert a cast now...
4332 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004333 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004334 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004335 }
4336 return new SetCondInst(isSetNE ? Instruction::SetLT :
4337 Instruction::SetGE, X,
4338 Constant::getNullValue(X->getType()));
4339 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004340
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004341 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004342 if (CI->isNullValue() && isHighOnes(BOC)) {
4343 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004344 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004345
4346 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004347 if (NegX->getType()->isSigned()) {
4348 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4349 X = InsertCastBefore(X, DestTy, I);
4350 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004351 }
4352
4353 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004354 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004355 }
4356
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004357 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004358 default: break;
4359 }
4360 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004361 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004362 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004363 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4364 Value *CastOp = Cast->getOperand(0);
4365 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004366 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004367 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004368 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004369 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004370 "Source and destination signednesses should differ!");
4371 if (Cast->getType()->isSigned()) {
4372 // If this is a signed comparison, check for comparisons in the
4373 // vicinity of zero.
4374 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4375 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004376 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004377 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004378 else if (I.getOpcode() == Instruction::SetGT &&
4379 cast<ConstantSInt>(CI)->getValue() == -1)
4380 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004381 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004382 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004383 } else {
4384 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4385 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004386 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004387 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004388 return BinaryOperator::createSetGT(CastOp,
4389 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004390 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004391 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004392 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004393 return BinaryOperator::createSetLT(CastOp,
4394 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004395 }
4396 }
4397 }
Chris Lattnere967b342003-06-04 05:10:11 +00004398 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004399 }
4400
Chris Lattner77c32c32005-04-23 15:31:55 +00004401 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4402 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4403 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4404 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004405 case Instruction::GetElementPtr:
4406 if (RHSC->isNullValue()) {
4407 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4408 bool isAllZeros = true;
4409 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4410 if (!isa<Constant>(LHSI->getOperand(i)) ||
4411 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4412 isAllZeros = false;
4413 break;
4414 }
4415 if (isAllZeros)
4416 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4417 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4418 }
4419 break;
4420
Chris Lattner77c32c32005-04-23 15:31:55 +00004421 case Instruction::PHI:
4422 if (Instruction *NV = FoldOpIntoPhi(I))
4423 return NV;
4424 break;
4425 case Instruction::Select:
4426 // If either operand of the select is a constant, we can fold the
4427 // comparison into the select arms, which will cause one to be
4428 // constant folded and the select turned into a bitwise or.
4429 Value *Op1 = 0, *Op2 = 0;
4430 if (LHSI->hasOneUse()) {
4431 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4432 // Fold the known value into the constant operand.
4433 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4434 // Insert a new SetCC of the other select operand.
4435 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4436 LHSI->getOperand(2), RHSC,
4437 I.getName()), I);
4438 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4439 // Fold the known value into the constant operand.
4440 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4441 // Insert a new SetCC of the other select operand.
4442 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4443 LHSI->getOperand(1), RHSC,
4444 I.getName()), I);
4445 }
4446 }
Jeff Cohen82639852005-04-23 21:38:35 +00004447
Chris Lattner77c32c32005-04-23 15:31:55 +00004448 if (Op1)
4449 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4450 break;
4451 }
4452 }
4453
Chris Lattner0798af32005-01-13 20:14:25 +00004454 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4455 if (User *GEP = dyn_castGetElementPtr(Op0))
4456 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4457 return NI;
4458 if (User *GEP = dyn_castGetElementPtr(Op1))
4459 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4460 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4461 return NI;
4462
Chris Lattner16930792003-11-03 04:25:02 +00004463 // Test to see if the operands of the setcc are casted versions of other
4464 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004465 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4466 Value *CastOp0 = CI->getOperand(0);
4467 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004468 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004469 // We keep moving the cast from the left operand over to the right
4470 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004471 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004472
Chris Lattner16930792003-11-03 04:25:02 +00004473 // If operand #1 is a cast instruction, see if we can eliminate it as
4474 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004475 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4476 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004477 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004478 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004479
Chris Lattner16930792003-11-03 04:25:02 +00004480 // If Op1 is a constant, we can fold the cast into the constant.
4481 if (Op1->getType() != Op0->getType())
4482 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4483 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4484 } else {
4485 // Otherwise, cast the RHS right before the setcc
4486 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4487 InsertNewInstBefore(cast<Instruction>(Op1), I);
4488 }
4489 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4490 }
4491
Chris Lattner6444c372003-11-03 05:17:03 +00004492 // Handle the special case of: setcc (cast bool to X), <cst>
4493 // This comes up when you have code like
4494 // int X = A < B;
4495 // if (X) ...
4496 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004497 // with a constant or another cast from the same type.
4498 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4499 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4500 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004501 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004502
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004503 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004504 Value *A, *B;
4505 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4506 (A == Op1 || B == Op1)) {
4507 // (A^B) == A -> B == 0
4508 Value *OtherVal = A == Op1 ? B : A;
4509 return BinaryOperator::create(I.getOpcode(), OtherVal,
4510 Constant::getNullValue(A->getType()));
4511 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4512 (A == Op0 || B == Op0)) {
4513 // A == (A^B) -> B == 0
4514 Value *OtherVal = A == Op0 ? B : A;
4515 return BinaryOperator::create(I.getOpcode(), OtherVal,
4516 Constant::getNullValue(A->getType()));
4517 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4518 // (A-B) == A -> B == 0
4519 return BinaryOperator::create(I.getOpcode(), B,
4520 Constant::getNullValue(B->getType()));
4521 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4522 // A == (A-B) -> B == 0
4523 return BinaryOperator::create(I.getOpcode(), B,
4524 Constant::getNullValue(B->getType()));
4525 }
4526 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004527 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004528}
4529
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004530// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4531// We only handle extending casts so far.
4532//
4533Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4534 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4535 const Type *SrcTy = LHSCIOp->getType();
4536 const Type *DestTy = SCI.getOperand(0)->getType();
4537 Value *RHSCIOp;
4538
4539 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004540 return 0;
4541
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004542 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4543 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4544 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4545
4546 // Is this a sign or zero extension?
4547 bool isSignSrc = SrcTy->isSigned();
4548 bool isSignDest = DestTy->isSigned();
4549
4550 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4551 // Not an extension from the same type?
4552 RHSCIOp = CI->getOperand(0);
4553 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4554 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4555 // Compute the constant that would happen if we truncated to SrcTy then
4556 // reextended to DestTy.
4557 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4558
4559 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4560 RHSCIOp = Res;
4561 } else {
4562 // If the value cannot be represented in the shorter type, we cannot emit
4563 // a simple comparison.
4564 if (SCI.getOpcode() == Instruction::SetEQ)
4565 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4566 if (SCI.getOpcode() == Instruction::SetNE)
4567 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4568
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004569 // Evaluate the comparison for LT.
4570 Value *Result;
4571 if (DestTy->isSigned()) {
4572 // We're performing a signed comparison.
4573 if (isSignSrc) {
4574 // Signed extend and signed comparison.
4575 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4576 Result = ConstantBool::False;
4577 else
4578 Result = ConstantBool::True; // X < (large) --> true
4579 } else {
4580 // Unsigned extend and signed comparison.
4581 if (cast<ConstantSInt>(CI)->getValue() < 0)
4582 Result = ConstantBool::False;
4583 else
4584 Result = ConstantBool::True;
4585 }
4586 } else {
4587 // We're performing an unsigned comparison.
4588 if (!isSignSrc) {
4589 // Unsigned extend & compare -> always true.
4590 Result = ConstantBool::True;
4591 } else {
4592 // We're performing an unsigned comp with a sign extended value.
4593 // This is true if the input is >= 0. [aka >s -1]
4594 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4595 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4596 NegOne, SCI.getName()), SCI);
4597 }
Reid Spencer279fa252004-11-28 21:31:15 +00004598 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004599
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004600 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004601 if (SCI.getOpcode() == Instruction::SetLT) {
4602 return ReplaceInstUsesWith(SCI, Result);
4603 } else {
4604 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4605 if (Constant *CI = dyn_cast<Constant>(Result))
4606 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4607 else
4608 return BinaryOperator::createNot(Result);
4609 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004610 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004611 } else {
4612 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004613 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004614
Chris Lattner252a8452005-06-16 03:00:08 +00004615 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004616 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4617}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004618
Chris Lattnere8d6c602003-03-10 19:16:08 +00004619Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004620 assert(I.getOperand(1)->getType() == Type::UByteTy);
4621 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004622 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004623
4624 // shl X, 0 == X and shr X, 0 == X
4625 // shl 0, X == 0 and shr 0, X == 0
4626 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004627 Op0 == Constant::getNullValue(Op0->getType()))
4628 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004629
Chris Lattner81a7a232004-10-16 18:11:37 +00004630 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4631 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004632 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004633 else // undef << X -> 0 AND undef >>u X -> 0
4634 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4635 }
4636 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004637 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4639 else
4640 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4641 }
4642
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004643 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4644 if (!isLeftShift)
4645 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4646 if (CSI->isAllOnesValue())
4647 return ReplaceInstUsesWith(I, CSI);
4648
Chris Lattner183b3362004-04-09 19:05:30 +00004649 // Try to fold constant and into select arguments.
4650 if (isa<Constant>(Op0))
4651 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004652 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004653 return R;
4654
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004655 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004656 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004657 if (MaskedValueIsZero(Op0,
4658 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004659 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4660 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4661 I.getName()), I);
4662 return new CastInst(V, I.getType());
4663 }
4664 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004665
Chris Lattner14553932006-01-06 07:12:35 +00004666 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4667 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4668 return Res;
4669 return 0;
4670}
4671
4672Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4673 ShiftInst &I) {
4674 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004675 bool isSignedShift = Op0->getType()->isSigned();
4676 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004677
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004678 // See if we can simplify any instructions used by the instruction whose sole
4679 // purpose is to compute bits we don't care about.
4680 uint64_t KnownZero, KnownOne;
4681 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4682 KnownZero, KnownOne))
4683 return &I;
4684
Chris Lattner14553932006-01-06 07:12:35 +00004685 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4686 // of a signed value.
4687 //
4688 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4689 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004690 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004691 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4692 else {
4693 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4694 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004695 }
Chris Lattner14553932006-01-06 07:12:35 +00004696 }
4697
4698 // ((X*C1) << C2) == (X * (C1 << C2))
4699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4700 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4701 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4702 return BinaryOperator::createMul(BO->getOperand(0),
4703 ConstantExpr::getShl(BOOp, Op1));
4704
4705 // Try to fold constant and into select arguments.
4706 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4707 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4708 return R;
4709 if (isa<PHINode>(Op0))
4710 if (Instruction *NV = FoldOpIntoPhi(I))
4711 return NV;
4712
4713 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004714 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4715 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4716 Value *V1, *V2;
4717 ConstantInt *CC;
4718 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004719 default: break;
4720 case Instruction::Add:
4721 case Instruction::And:
4722 case Instruction::Or:
4723 case Instruction::Xor:
4724 // These operators commute.
4725 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004726 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4727 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004728 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004729 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004730 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004731 Op0BO->getName());
4732 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004733 Instruction *X =
4734 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4735 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004736 InsertNewInstBefore(X, I); // (X + (Y << C))
4737 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004738 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004739 return BinaryOperator::createAnd(X, C2);
4740 }
Chris Lattner14553932006-01-06 07:12:35 +00004741
Chris Lattner797dee72005-09-18 06:30:59 +00004742 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4743 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4744 match(Op0BO->getOperand(1),
4745 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004746 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004747 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004748 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004749 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004750 Op0BO->getName());
4751 InsertNewInstBefore(YS, I); // (Y << C)
4752 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004753 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004754 V1->getName()+".mask");
4755 InsertNewInstBefore(XM, I); // X & (CC << C)
4756
4757 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4758 }
Chris Lattner14553932006-01-06 07:12:35 +00004759
Chris Lattner797dee72005-09-18 06:30:59 +00004760 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004761 case Instruction::Sub:
4762 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004763 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4764 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004765 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004766 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004767 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004768 Op0BO->getName());
4769 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004770 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004771 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004772 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004773 InsertNewInstBefore(X, I); // (X + (Y << C))
4774 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004775 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004776 return BinaryOperator::createAnd(X, C2);
4777 }
Chris Lattner14553932006-01-06 07:12:35 +00004778
Chris Lattner1df0e982006-05-31 21:14:00 +00004779 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004780 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4781 match(Op0BO->getOperand(0),
4782 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004783 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004784 cast<BinaryOperator>(Op0BO->getOperand(0))
4785 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004786 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004787 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004788 Op0BO->getName());
4789 InsertNewInstBefore(YS, I); // (Y << C)
4790 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004791 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004792 V1->getName()+".mask");
4793 InsertNewInstBefore(XM, I); // X & (CC << C)
4794
Chris Lattner1df0e982006-05-31 21:14:00 +00004795 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004796 }
Chris Lattner14553932006-01-06 07:12:35 +00004797
Chris Lattner27cb9db2005-09-18 05:12:10 +00004798 break;
Chris Lattner14553932006-01-06 07:12:35 +00004799 }
4800
4801
4802 // If the operand is an bitwise operator with a constant RHS, and the
4803 // shift is the only use, we can pull it out of the shift.
4804 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4805 bool isValid = true; // Valid only for And, Or, Xor
4806 bool highBitSet = false; // Transform if high bit of constant set?
4807
4808 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004809 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004810 case Instruction::Add:
4811 isValid = isLeftShift;
4812 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004813 case Instruction::Or:
4814 case Instruction::Xor:
4815 highBitSet = false;
4816 break;
4817 case Instruction::And:
4818 highBitSet = true;
4819 break;
Chris Lattner14553932006-01-06 07:12:35 +00004820 }
4821
4822 // If this is a signed shift right, and the high bit is modified
4823 // by the logical operation, do not perform the transformation.
4824 // The highBitSet boolean indicates the value of the high bit of
4825 // the constant which would cause it to be modified for this
4826 // operation.
4827 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004828 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004829 uint64_t Val = Op0C->getRawValue();
4830 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4831 }
4832
4833 if (isValid) {
4834 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4835
4836 Instruction *NewShift =
4837 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4838 Op0BO->getName());
4839 Op0BO->setName("");
4840 InsertNewInstBefore(NewShift, I);
4841
4842 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4843 NewRHS);
4844 }
4845 }
4846 }
4847 }
4848
Chris Lattnereb372a02006-01-06 07:52:12 +00004849 // Find out if this is a shift of a shift by a constant.
4850 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004851 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004852 ShiftOp = Op0SI;
4853 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4854 // If this is a noop-integer case of a shift instruction, use the shift.
4855 if (CI->getOperand(0)->getType()->isInteger() &&
4856 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4857 CI->getType()->getPrimitiveSizeInBits() &&
4858 isa<ShiftInst>(CI->getOperand(0))) {
4859 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4860 }
4861 }
4862
4863 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4864 // Find the operands and properties of the input shift. Note that the
4865 // signedness of the input shift may differ from the current shift if there
4866 // is a noop cast between the two.
4867 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4868 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004869 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004870
4871 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4872
4873 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4874 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4875
4876 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4877 if (isLeftShift == isShiftOfLeftShift) {
4878 // Do not fold these shifts if the first one is signed and the second one
4879 // is unsigned and this is a right shift. Further, don't do any folding
4880 // on them.
4881 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4882 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004883
Chris Lattnereb372a02006-01-06 07:52:12 +00004884 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4885 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4886 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004887
Chris Lattnereb372a02006-01-06 07:52:12 +00004888 Value *Op = ShiftOp->getOperand(0);
4889 if (isShiftOfSignedShift != isSignedShift)
4890 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4891 return new ShiftInst(I.getOpcode(), Op,
4892 ConstantUInt::get(Type::UByteTy, Amt));
4893 }
4894
4895 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4896 // signed types, we can only support the (A >> c1) << c2 configuration,
4897 // because it can not turn an arbitrary bit of A into a sign bit.
4898 if (isUnsignedShift || isLeftShift) {
4899 // Calculate bitmask for what gets shifted off the edge.
4900 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4901 if (isLeftShift)
4902 C = ConstantExpr::getShl(C, ShiftAmt1C);
4903 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004904 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004905
4906 Value *Op = ShiftOp->getOperand(0);
4907 if (isShiftOfSignedShift != isSignedShift)
4908 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4909
4910 Instruction *Mask =
4911 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4912 InsertNewInstBefore(Mask, I);
4913
4914 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004915 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004916 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004917 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004918 return new ShiftInst(I.getOpcode(), Mask,
4919 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004920 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4921 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4922 // Make sure to emit an unsigned shift right, not a signed one.
4923 Mask = InsertNewInstBefore(new CastInst(Mask,
4924 Mask->getType()->getUnsignedVersion(),
4925 Op->getName()), I);
4926 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004927 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004928 InsertNewInstBefore(Mask, I);
4929 return new CastInst(Mask, I.getType());
4930 } else {
4931 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4932 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4933 }
4934 } else {
4935 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4936 Op = InsertNewInstBefore(new CastInst(Mask,
4937 I.getType()->getSignedVersion(),
4938 Mask->getName()), I);
4939 Instruction *Shift =
4940 new ShiftInst(ShiftOp->getOpcode(), Op,
4941 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4942 InsertNewInstBefore(Shift, I);
4943
4944 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4945 C = ConstantExpr::getShl(C, Op1);
4946 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4947 InsertNewInstBefore(Mask, I);
4948 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004949 }
4950 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004951 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004952 // this case, C1 == C2 and C1 is 8, 16, or 32.
4953 if (ShiftAmt1 == ShiftAmt2) {
4954 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004955 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004956 case 8 : SExtType = Type::SByteTy; break;
4957 case 16: SExtType = Type::ShortTy; break;
4958 case 32: SExtType = Type::IntTy; break;
4959 }
4960
4961 if (SExtType) {
4962 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4963 SExtType, "sext");
4964 InsertNewInstBefore(NewTrunc, I);
4965 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004966 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004967 }
Chris Lattner86102b82005-01-01 16:22:27 +00004968 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004969 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004970 return 0;
4971}
4972
Chris Lattner48a44f72002-05-02 17:06:02 +00004973
Chris Lattner8f663e82005-10-29 04:36:15 +00004974/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4975/// expression. If so, decompose it, returning some value X, such that Val is
4976/// X*Scale+Offset.
4977///
4978static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4979 unsigned &Offset) {
4980 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4981 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4982 Offset = CI->getValue();
4983 Scale = 1;
4984 return ConstantUInt::get(Type::UIntTy, 0);
4985 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4986 if (I->getNumOperands() == 2) {
4987 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4988 if (I->getOpcode() == Instruction::Shl) {
4989 // This is a value scaled by '1 << the shift amt'.
4990 Scale = 1U << CUI->getValue();
4991 Offset = 0;
4992 return I->getOperand(0);
4993 } else if (I->getOpcode() == Instruction::Mul) {
4994 // This value is scaled by 'CUI'.
4995 Scale = CUI->getValue();
4996 Offset = 0;
4997 return I->getOperand(0);
4998 } else if (I->getOpcode() == Instruction::Add) {
4999 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
5000 // divisible by C2.
5001 unsigned SubScale;
5002 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
5003 Offset);
5004 Offset += CUI->getValue();
5005 if (SubScale > 1 && (Offset % SubScale == 0)) {
5006 Scale = SubScale;
5007 return SubVal;
5008 }
5009 }
5010 }
5011 }
5012 }
5013
5014 // Otherwise, we can't look past this.
5015 Scale = 1;
5016 Offset = 0;
5017 return Val;
5018}
5019
5020
Chris Lattner216be912005-10-24 06:03:58 +00005021/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5022/// try to eliminate the cast by moving the type information into the alloc.
5023Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5024 AllocationInst &AI) {
5025 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005026 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005027
Chris Lattnerac87beb2005-10-24 06:22:12 +00005028 // Remove any uses of AI that are dead.
5029 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5030 std::vector<Instruction*> DeadUsers;
5031 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5032 Instruction *User = cast<Instruction>(*UI++);
5033 if (isInstructionTriviallyDead(User)) {
5034 while (UI != E && *UI == User)
5035 ++UI; // If this instruction uses AI more than once, don't break UI.
5036
5037 // Add operands to the worklist.
5038 AddUsesToWorkList(*User);
5039 ++NumDeadInst;
5040 DEBUG(std::cerr << "IC: DCE: " << *User);
5041
5042 User->eraseFromParent();
5043 removeFromWorkList(User);
5044 }
5045 }
5046
Chris Lattner216be912005-10-24 06:03:58 +00005047 // Get the type really allocated and the type casted to.
5048 const Type *AllocElTy = AI.getAllocatedType();
5049 const Type *CastElTy = PTy->getElementType();
5050 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005051
5052 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
5053 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
5054 if (CastElTyAlign < AllocElTyAlign) return 0;
5055
Chris Lattner46705b22005-10-24 06:35:18 +00005056 // If the allocation has multiple uses, only promote it if we are strictly
5057 // increasing the alignment of the resultant allocation. If we keep it the
5058 // same, we open the door to infinite loops of various kinds.
5059 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5060
Chris Lattner216be912005-10-24 06:03:58 +00005061 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5062 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005063 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005064
Chris Lattner8270c332005-10-29 03:19:53 +00005065 // See if we can satisfy the modulus by pulling a scale out of the array
5066 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005067 unsigned ArraySizeScale, ArrayOffset;
5068 Value *NumElements = // See if the array size is a decomposable linear expr.
5069 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5070
Chris Lattner8270c332005-10-29 03:19:53 +00005071 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5072 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005073 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5074 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005075
Chris Lattner8270c332005-10-29 03:19:53 +00005076 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5077 Value *Amt = 0;
5078 if (Scale == 1) {
5079 Amt = NumElements;
5080 } else {
5081 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5082 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5083 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5084 else if (Scale != 1) {
5085 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5086 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005087 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005088 }
5089
Chris Lattner8f663e82005-10-29 04:36:15 +00005090 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5091 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5092 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5093 Amt = InsertNewInstBefore(Tmp, AI);
5094 }
5095
Chris Lattner216be912005-10-24 06:03:58 +00005096 std::string Name = AI.getName(); AI.setName("");
5097 AllocationInst *New;
5098 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005099 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005100 else
Nate Begeman848622f2005-11-05 09:21:28 +00005101 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005102 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005103
5104 // If the allocation has multiple uses, insert a cast and change all things
5105 // that used it to use the new cast. This will also hack on CI, but it will
5106 // die soon.
5107 if (!AI.hasOneUse()) {
5108 AddUsesToWorkList(AI);
5109 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5110 InsertNewInstBefore(NewCast, AI);
5111 AI.replaceAllUsesWith(NewCast);
5112 }
Chris Lattner216be912005-10-24 06:03:58 +00005113 return ReplaceInstUsesWith(CI, New);
5114}
5115
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005116/// CanEvaluateInDifferentType - Return true if we can take the specified value
5117/// and return it without inserting any new casts. This is used by code that
5118/// tries to decide whether promoting or shrinking integer operations to wider
5119/// or smaller types will allow us to eliminate a truncate or extend.
5120static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5121 int &NumCastsRemoved) {
5122 if (isa<Constant>(V)) return true;
5123
5124 Instruction *I = dyn_cast<Instruction>(V);
5125 if (!I || !I->hasOneUse()) return false;
5126
5127 switch (I->getOpcode()) {
5128 case Instruction::And:
5129 case Instruction::Or:
5130 case Instruction::Xor:
5131 // These operators can all arbitrarily be extended or truncated.
5132 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5133 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5134 case Instruction::Cast:
5135 // If this is a cast from the destination type, we can trivially eliminate
5136 // it, and this will remove a cast overall.
5137 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005138 // If the first operand is itself a cast, and is eliminable, do not count
5139 // this as an eliminable cast. We would prefer to eliminate those two
5140 // casts first.
5141 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5142 return true;
5143
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005144 ++NumCastsRemoved;
5145 return true;
5146 }
5147 // TODO: Can handle more cases here.
5148 break;
5149 }
5150
5151 return false;
5152}
5153
5154/// EvaluateInDifferentType - Given an expression that
5155/// CanEvaluateInDifferentType returns true for, actually insert the code to
5156/// evaluate the expression.
5157Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5158 if (Constant *C = dyn_cast<Constant>(V))
5159 return ConstantExpr::getCast(C, Ty);
5160
5161 // Otherwise, it must be an instruction.
5162 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005163 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005164 switch (I->getOpcode()) {
5165 case Instruction::And:
5166 case Instruction::Or:
5167 case Instruction::Xor: {
5168 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5169 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5170 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5171 LHS, RHS, I->getName());
5172 break;
5173 }
5174 case Instruction::Cast:
5175 // If this is a cast from the destination type, return the input.
5176 if (I->getOperand(0)->getType() == Ty)
5177 return I->getOperand(0);
5178
5179 // TODO: Can handle more cases here.
5180 assert(0 && "Unreachable!");
5181 break;
5182 }
5183
5184 return InsertNewInstBefore(Res, *I);
5185}
5186
Chris Lattner216be912005-10-24 06:03:58 +00005187
Chris Lattner48a44f72002-05-02 17:06:02 +00005188// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005189//
Chris Lattner113f4f42002-06-25 16:13:24 +00005190Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005191 Value *Src = CI.getOperand(0);
5192
Chris Lattner48a44f72002-05-02 17:06:02 +00005193 // If the user is casting a value to the same type, eliminate this cast
5194 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005195 if (CI.getType() == Src->getType())
5196 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005197
Chris Lattner81a7a232004-10-16 18:11:37 +00005198 if (isa<UndefValue>(Src)) // cast undef -> undef
5199 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5200
Chris Lattner48a44f72002-05-02 17:06:02 +00005201 // If casting the result of another cast instruction, try to eliminate this
5202 // one!
5203 //
Chris Lattner86102b82005-01-01 16:22:27 +00005204 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5205 Value *A = CSrc->getOperand(0);
5206 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5207 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005208 // This instruction now refers directly to the cast's src operand. This
5209 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005210 CI.setOperand(0, CSrc->getOperand(0));
5211 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005212 }
5213
Chris Lattner650b6da2002-08-02 20:00:25 +00005214 // If this is an A->B->A cast, and we are dealing with integral types, try
5215 // to convert this into a logical 'and' instruction.
5216 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005217 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005218 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005219 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005220 CSrc->getType()->getPrimitiveSizeInBits() <
5221 CI.getType()->getPrimitiveSizeInBits()&&
5222 A->getType()->getPrimitiveSizeInBits() ==
5223 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005224 assert(CSrc->getType() != Type::ULongTy &&
5225 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005226 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005227 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5228 AndValue);
5229 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5230 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5231 if (And->getType() != CI.getType()) {
5232 And->setName(CSrc->getName()+".mask");
5233 InsertNewInstBefore(And, CI);
5234 And = new CastInst(And, CI.getType());
5235 }
5236 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005237 }
5238 }
Chris Lattner2590e512006-02-07 06:56:34 +00005239
Chris Lattner03841652004-05-25 04:29:21 +00005240 // If this is a cast to bool, turn it into the appropriate setne instruction.
5241 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005242 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005243 Constant::getNullValue(CI.getOperand(0)->getType()));
5244
Chris Lattner2590e512006-02-07 06:56:34 +00005245 // See if we can simplify any instructions used by the LHS whose sole
5246 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005247 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5248 uint64_t KnownZero, KnownOne;
5249 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5250 KnownZero, KnownOne))
5251 return &CI;
5252 }
Chris Lattner2590e512006-02-07 06:56:34 +00005253
Chris Lattnerd0d51602003-06-21 23:12:02 +00005254 // If casting the result of a getelementptr instruction with no offset, turn
5255 // this into a cast of the original pointer!
5256 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005257 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005258 bool AllZeroOperands = true;
5259 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5260 if (!isa<Constant>(GEP->getOperand(i)) ||
5261 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5262 AllZeroOperands = false;
5263 break;
5264 }
5265 if (AllZeroOperands) {
5266 CI.setOperand(0, GEP->getOperand(0));
5267 return &CI;
5268 }
5269 }
5270
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005271 // If we are casting a malloc or alloca to a pointer to a type of the same
5272 // size, rewrite the allocation instruction to allocate the "right" type.
5273 //
5274 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005275 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5276 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005277
Chris Lattner86102b82005-01-01 16:22:27 +00005278 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5279 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5280 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005281 if (isa<PHINode>(Src))
5282 if (Instruction *NV = FoldOpIntoPhi(CI))
5283 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005284
5285 // If the source and destination are pointers, and this cast is equivalent to
5286 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5287 // This can enhance SROA and other transforms that want type-safe pointers.
5288 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5289 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5290 const Type *DstTy = DstPTy->getElementType();
5291 const Type *SrcTy = SrcPTy->getElementType();
5292
5293 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5294 unsigned NumZeros = 0;
5295 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005296 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5297 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005298 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5299 ++NumZeros;
5300 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005301
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005302 // If we found a path from the src to dest, create the getelementptr now.
5303 if (SrcTy == DstTy) {
5304 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5305 return new GetElementPtrInst(Src, Idxs);
5306 }
5307 }
5308
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005309 // If the source value is an instruction with only this use, we can attempt to
5310 // propagate the cast into the instruction. Also, only handle integral types
5311 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005312 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005313 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005314 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005315
5316 int NumCastsRemoved = 0;
5317 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5318 // If this cast is a truncate, evaluting in a different type always
5319 // eliminates the cast, so it is always a win. If this is a noop-cast
5320 // this just removes a noop cast which isn't pointful, but simplifies
5321 // the code. If this is a zero-extension, we need to do an AND to
5322 // maintain the clear top-part of the computation, so we require that
5323 // the input have eliminated at least one cast. If this is a sign
5324 // extension, we insert two new casts (to do the extension) so we
5325 // require that two casts have been eliminated.
5326 bool DoXForm;
5327 switch (getCastType(Src->getType(), CI.getType())) {
5328 default: assert(0 && "Unknown cast type!");
5329 case Noop:
5330 case Truncate:
5331 DoXForm = true;
5332 break;
5333 case Zeroext:
5334 DoXForm = NumCastsRemoved >= 1;
5335 break;
5336 case Signext:
5337 DoXForm = NumCastsRemoved >= 2;
5338 break;
5339 }
5340
5341 if (DoXForm) {
5342 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5343 assert(Res->getType() == CI.getType());
5344 switch (getCastType(Src->getType(), CI.getType())) {
5345 default: assert(0 && "Unknown cast type!");
5346 case Noop:
5347 case Truncate:
5348 // Just replace this cast with the result.
5349 return ReplaceInstUsesWith(CI, Res);
5350 case Zeroext: {
5351 // We need to emit an AND to clear the high bits.
5352 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5353 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5354 assert(SrcBitSize < DestBitSize && "Not a zext?");
5355 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5356 C = ConstantExpr::getCast(C, CI.getType());
5357 return BinaryOperator::createAnd(Res, C);
5358 }
5359 case Signext:
5360 // We need to emit a cast to truncate, then a cast to sext.
5361 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5362 CI.getType());
5363 }
5364 }
5365 }
5366
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005367 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005368 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5369 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005370
5371 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5372 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5373
5374 switch (SrcI->getOpcode()) {
5375 case Instruction::Add:
5376 case Instruction::Mul:
5377 case Instruction::And:
5378 case Instruction::Or:
5379 case Instruction::Xor:
5380 // If we are discarding information, or just changing the sign, rewrite.
5381 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5382 // Don't insert two casts if they cannot be eliminated. We allow two
5383 // casts to be inserted if the sizes are the same. This could only be
5384 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005385 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5386 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005387 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5388 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5389 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5390 ->getOpcode(), Op0c, Op1c);
5391 }
5392 }
Chris Lattner72086162005-05-06 02:07:39 +00005393
5394 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5395 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5396 Op1 == ConstantBool::True &&
5397 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5398 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5399 return BinaryOperator::createXor(New,
5400 ConstantInt::get(CI.getType(), 1));
5401 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005402 break;
5403 case Instruction::Shl:
5404 // Allow changing the sign of the source operand. Do not allow changing
5405 // the size of the shift, UNLESS the shift amount is a constant. We
5406 // mush not change variable sized shifts to a smaller size, because it
5407 // is undefined to shift more bits out than exist in the value.
5408 if (DestBitSize == SrcBitSize ||
5409 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5410 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5411 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5412 }
5413 break;
Chris Lattner87380412005-05-06 04:18:52 +00005414 case Instruction::Shr:
5415 // If this is a signed shr, and if all bits shifted in are about to be
5416 // truncated off, turn it into an unsigned shr to allow greater
5417 // simplifications.
5418 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5419 isa<ConstantInt>(Op1)) {
5420 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5421 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5422 // Convert to unsigned.
5423 Value *N1 = InsertOperandCastBefore(Op0,
5424 Op0->getType()->getUnsignedVersion(), &CI);
5425 // Insert the new shift, which is now unsigned.
5426 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5427 Op1, Src->getName()), CI);
5428 return new CastInst(N1, CI.getType());
5429 }
5430 }
5431 break;
5432
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005433 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005434 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005435 // We if we are just checking for a seteq of a single bit and casting it
5436 // to an integer. If so, shift the bit to the appropriate place then
5437 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005438 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005439 uint64_t Op1CV = Op1C->getZExtValue();
5440 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5441 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5442 // cast (X == 1) to int --> X iff X has only the low bit set.
5443 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5444 // cast (X != 0) to int --> X iff X has only the low bit set.
5445 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5446 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5447 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5448 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5449 // If Op1C some other power of two, convert:
5450 uint64_t KnownZero, KnownOne;
5451 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5452 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5453
5454 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5455 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5456 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5457 // (X&4) == 2 --> false
5458 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005459 Constant *Res = ConstantBool::get(isSetNE);
5460 Res = ConstantExpr::getCast(Res, CI.getType());
5461 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005462 }
5463
5464 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5465 Value *In = Op0;
5466 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005467 // Perform an unsigned shr by shiftamt. Convert input to
5468 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005469 if (In->getType()->isSigned())
5470 In = InsertNewInstBefore(new CastInst(In,
5471 In->getType()->getUnsignedVersion(), In->getName()),CI);
5472 // Insert the shift to put the result in the low bit.
5473 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005474 ConstantInt::get(Type::UByteTy, ShiftAmt),
5475 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005476 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005477
5478 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5479 Constant *One = ConstantInt::get(In->getType(), 1);
5480 In = BinaryOperator::createXor(In, One, "tmp");
5481 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005482 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005483
5484 if (CI.getType() == In->getType())
5485 return ReplaceInstUsesWith(CI, In);
5486 else
5487 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005488 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005489 }
5490 }
5491 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005492 }
5493 }
Chris Lattner99155be2006-05-25 23:24:33 +00005494
5495 if (SrcI->hasOneUse()) {
5496 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5497 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5498 // because the inputs are known to be a vector. Check to see if this is
5499 // a cast to a vector with the same # elts.
5500 if (isa<PackedType>(CI.getType()) &&
5501 cast<PackedType>(CI.getType())->getNumElements() ==
5502 SVI->getType()->getNumElements()) {
5503 CastInst *Tmp;
5504 // If either of the operands is a cast from CI.getType(), then
5505 // evaluating the shuffle in the casted destination's type will allow
5506 // us to eliminate at least one cast.
5507 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5508 Tmp->getOperand(0)->getType() == CI.getType()) ||
5509 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005510 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005511 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5512 CI.getType(), &CI);
5513 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5514 CI.getType(), &CI);
5515 // Return a new shuffle vector. Use the same element ID's, as we
5516 // know the vector types match #elts.
5517 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5518 }
5519 }
5520 }
5521 }
5522 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005523
Chris Lattner260ab202002-04-18 17:39:14 +00005524 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005525}
5526
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005527/// GetSelectFoldableOperands - We want to turn code that looks like this:
5528/// %C = or %A, %B
5529/// %D = select %cond, %C, %A
5530/// into:
5531/// %C = select %cond, %B, 0
5532/// %D = or %A, %C
5533///
5534/// Assuming that the specified instruction is an operand to the select, return
5535/// a bitmask indicating which operands of this instruction are foldable if they
5536/// equal the other incoming value of the select.
5537///
5538static unsigned GetSelectFoldableOperands(Instruction *I) {
5539 switch (I->getOpcode()) {
5540 case Instruction::Add:
5541 case Instruction::Mul:
5542 case Instruction::And:
5543 case Instruction::Or:
5544 case Instruction::Xor:
5545 return 3; // Can fold through either operand.
5546 case Instruction::Sub: // Can only fold on the amount subtracted.
5547 case Instruction::Shl: // Can only fold on the shift amount.
5548 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005549 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005550 default:
5551 return 0; // Cannot fold
5552 }
5553}
5554
5555/// GetSelectFoldableConstant - For the same transformation as the previous
5556/// function, return the identity constant that goes into the select.
5557static Constant *GetSelectFoldableConstant(Instruction *I) {
5558 switch (I->getOpcode()) {
5559 default: assert(0 && "This cannot happen!"); abort();
5560 case Instruction::Add:
5561 case Instruction::Sub:
5562 case Instruction::Or:
5563 case Instruction::Xor:
5564 return Constant::getNullValue(I->getType());
5565 case Instruction::Shl:
5566 case Instruction::Shr:
5567 return Constant::getNullValue(Type::UByteTy);
5568 case Instruction::And:
5569 return ConstantInt::getAllOnesValue(I->getType());
5570 case Instruction::Mul:
5571 return ConstantInt::get(I->getType(), 1);
5572 }
5573}
5574
Chris Lattner411336f2005-01-19 21:50:18 +00005575/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5576/// have the same opcode and only one use each. Try to simplify this.
5577Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5578 Instruction *FI) {
5579 if (TI->getNumOperands() == 1) {
5580 // If this is a non-volatile load or a cast from the same type,
5581 // merge.
5582 if (TI->getOpcode() == Instruction::Cast) {
5583 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5584 return 0;
5585 } else {
5586 return 0; // unknown unary op.
5587 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005588
Chris Lattner411336f2005-01-19 21:50:18 +00005589 // Fold this by inserting a select from the input values.
5590 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5591 FI->getOperand(0), SI.getName()+".v");
5592 InsertNewInstBefore(NewSI, SI);
5593 return new CastInst(NewSI, TI->getType());
5594 }
5595
5596 // Only handle binary operators here.
5597 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5598 return 0;
5599
5600 // Figure out if the operations have any operands in common.
5601 Value *MatchOp, *OtherOpT, *OtherOpF;
5602 bool MatchIsOpZero;
5603 if (TI->getOperand(0) == FI->getOperand(0)) {
5604 MatchOp = TI->getOperand(0);
5605 OtherOpT = TI->getOperand(1);
5606 OtherOpF = FI->getOperand(1);
5607 MatchIsOpZero = true;
5608 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5609 MatchOp = TI->getOperand(1);
5610 OtherOpT = TI->getOperand(0);
5611 OtherOpF = FI->getOperand(0);
5612 MatchIsOpZero = false;
5613 } else if (!TI->isCommutative()) {
5614 return 0;
5615 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5616 MatchOp = TI->getOperand(0);
5617 OtherOpT = TI->getOperand(1);
5618 OtherOpF = FI->getOperand(0);
5619 MatchIsOpZero = true;
5620 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5621 MatchOp = TI->getOperand(1);
5622 OtherOpT = TI->getOperand(0);
5623 OtherOpF = FI->getOperand(1);
5624 MatchIsOpZero = true;
5625 } else {
5626 return 0;
5627 }
5628
5629 // If we reach here, they do have operations in common.
5630 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5631 OtherOpF, SI.getName()+".v");
5632 InsertNewInstBefore(NewSI, SI);
5633
5634 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5635 if (MatchIsOpZero)
5636 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5637 else
5638 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5639 } else {
5640 if (MatchIsOpZero)
5641 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5642 else
5643 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5644 }
5645}
5646
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005647Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005648 Value *CondVal = SI.getCondition();
5649 Value *TrueVal = SI.getTrueValue();
5650 Value *FalseVal = SI.getFalseValue();
5651
5652 // select true, X, Y -> X
5653 // select false, X, Y -> Y
5654 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005655 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005656 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005657 else {
5658 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005659 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005660 }
Chris Lattner533bc492004-03-30 19:37:13 +00005661
5662 // select C, X, X -> X
5663 if (TrueVal == FalseVal)
5664 return ReplaceInstUsesWith(SI, TrueVal);
5665
Chris Lattner81a7a232004-10-16 18:11:37 +00005666 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5667 return ReplaceInstUsesWith(SI, FalseVal);
5668 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5669 return ReplaceInstUsesWith(SI, TrueVal);
5670 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5671 if (isa<Constant>(TrueVal))
5672 return ReplaceInstUsesWith(SI, TrueVal);
5673 else
5674 return ReplaceInstUsesWith(SI, FalseVal);
5675 }
5676
Chris Lattner1c631e82004-04-08 04:43:23 +00005677 if (SI.getType() == Type::BoolTy)
5678 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5679 if (C == ConstantBool::True) {
5680 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005681 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005682 } else {
5683 // Change: A = select B, false, C --> A = and !B, C
5684 Value *NotCond =
5685 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5686 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005687 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005688 }
5689 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5690 if (C == ConstantBool::False) {
5691 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005692 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005693 } else {
5694 // Change: A = select B, C, true --> A = or !B, C
5695 Value *NotCond =
5696 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5697 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005698 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005699 }
5700 }
5701
Chris Lattner183b3362004-04-09 19:05:30 +00005702 // Selecting between two integer constants?
5703 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5704 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5705 // select C, 1, 0 -> cast C to int
5706 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5707 return new CastInst(CondVal, SI.getType());
5708 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5709 // select C, 0, 1 -> cast !C to int
5710 Value *NotCond =
5711 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005712 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005713 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005714 }
Chris Lattner35167c32004-06-09 07:59:58 +00005715
Chris Lattner380c7e92006-09-20 04:44:59 +00005716 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5717
5718 // (x <s 0) ? -1 : 0 -> sra x, 31
5719 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5720 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5721 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5722 bool CanXForm = false;
5723 if (CmpCst->getType()->isSigned())
5724 CanXForm = CmpCst->isNullValue() &&
5725 IC->getOpcode() == Instruction::SetLT;
5726 else {
5727 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5728 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5729 IC->getOpcode() == Instruction::SetGT;
5730 }
5731
5732 if (CanXForm) {
5733 // The comparison constant and the result are not neccessarily the
5734 // same width. In any case, the first step to do is make sure
5735 // that X is signed.
5736 Value *X = IC->getOperand(0);
5737 if (!X->getType()->isSigned())
5738 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5739
5740 // Now that X is signed, we have to make the all ones value. Do
5741 // this by inserting a new SRA.
5742 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5743 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5744 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
5745 ShAmt, "ones");
5746 InsertNewInstBefore(SRA, SI);
5747
5748 // Finally, convert to the type of the select RHS. If this is
5749 // smaller than the compare value, it will truncate the ones to
5750 // fit. If it is larger, it will sext the ones to fit.
5751 return new CastInst(SRA, SI.getType());
5752 }
5753 }
5754
5755
5756 // If one of the constants is zero (we know they can't both be) and we
5757 // have a setcc instruction with zero, and we have an 'and' with the
5758 // non-constant value, eliminate this whole mess. This corresponds to
5759 // cases like this: ((X & 27) ? 27 : 0)
5760 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005761 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005762 cast<Constant>(IC->getOperand(1))->isNullValue())
5763 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5764 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005765 isa<ConstantInt>(ICA->getOperand(1)) &&
5766 (ICA->getOperand(1) == TrueValC ||
5767 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005768 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5769 // Okay, now we know that everything is set up, we just don't
5770 // know whether we have a setne or seteq and whether the true or
5771 // false val is the zero.
5772 bool ShouldNotVal = !TrueValC->isNullValue();
5773 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5774 Value *V = ICA;
5775 if (ShouldNotVal)
5776 V = InsertNewInstBefore(BinaryOperator::create(
5777 Instruction::Xor, V, ICA->getOperand(1)), SI);
5778 return ReplaceInstUsesWith(SI, V);
5779 }
Chris Lattner380c7e92006-09-20 04:44:59 +00005780 }
Chris Lattner533bc492004-03-30 19:37:13 +00005781 }
Chris Lattner623fba12004-04-10 22:21:27 +00005782
5783 // See if we are selecting two values based on a comparison of the two values.
5784 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5785 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5786 // Transform (X == Y) ? X : Y -> Y
5787 if (SCI->getOpcode() == Instruction::SetEQ)
5788 return ReplaceInstUsesWith(SI, FalseVal);
5789 // Transform (X != Y) ? X : Y -> X
5790 if (SCI->getOpcode() == Instruction::SetNE)
5791 return ReplaceInstUsesWith(SI, TrueVal);
5792 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5793
5794 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5795 // Transform (X == Y) ? Y : X -> X
5796 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005797 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005798 // Transform (X != Y) ? Y : X -> Y
5799 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005800 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005801 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5802 }
5803 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005804
Chris Lattnera04c9042005-01-13 22:52:24 +00005805 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5806 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5807 if (TI->hasOneUse() && FI->hasOneUse()) {
5808 bool isInverse = false;
5809 Instruction *AddOp = 0, *SubOp = 0;
5810
Chris Lattner411336f2005-01-19 21:50:18 +00005811 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5812 if (TI->getOpcode() == FI->getOpcode())
5813 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5814 return IV;
5815
5816 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5817 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005818 if (TI->getOpcode() == Instruction::Sub &&
5819 FI->getOpcode() == Instruction::Add) {
5820 AddOp = FI; SubOp = TI;
5821 } else if (FI->getOpcode() == Instruction::Sub &&
5822 TI->getOpcode() == Instruction::Add) {
5823 AddOp = TI; SubOp = FI;
5824 }
5825
5826 if (AddOp) {
5827 Value *OtherAddOp = 0;
5828 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5829 OtherAddOp = AddOp->getOperand(1);
5830 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5831 OtherAddOp = AddOp->getOperand(0);
5832 }
5833
5834 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005835 // So at this point we know we have (Y -> OtherAddOp):
5836 // select C, (add X, Y), (sub X, Z)
5837 Value *NegVal; // Compute -Z
5838 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5839 NegVal = ConstantExpr::getNeg(C);
5840 } else {
5841 NegVal = InsertNewInstBefore(
5842 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005843 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005844
5845 Value *NewTrueOp = OtherAddOp;
5846 Value *NewFalseOp = NegVal;
5847 if (AddOp != TI)
5848 std::swap(NewTrueOp, NewFalseOp);
5849 Instruction *NewSel =
5850 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5851
5852 NewSel = InsertNewInstBefore(NewSel, SI);
5853 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005854 }
5855 }
5856 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005857
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005858 // See if we can fold the select into one of our operands.
5859 if (SI.getType()->isInteger()) {
5860 // See the comment above GetSelectFoldableOperands for a description of the
5861 // transformation we are doing here.
5862 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5863 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5864 !isa<Constant>(FalseVal))
5865 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5866 unsigned OpToFold = 0;
5867 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5868 OpToFold = 1;
5869 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5870 OpToFold = 2;
5871 }
5872
5873 if (OpToFold) {
5874 Constant *C = GetSelectFoldableConstant(TVI);
5875 std::string Name = TVI->getName(); TVI->setName("");
5876 Instruction *NewSel =
5877 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5878 Name);
5879 InsertNewInstBefore(NewSel, SI);
5880 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5881 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5882 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5883 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5884 else {
5885 assert(0 && "Unknown instruction!!");
5886 }
5887 }
5888 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005889
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005890 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5891 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5892 !isa<Constant>(TrueVal))
5893 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5894 unsigned OpToFold = 0;
5895 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5896 OpToFold = 1;
5897 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5898 OpToFold = 2;
5899 }
5900
5901 if (OpToFold) {
5902 Constant *C = GetSelectFoldableConstant(FVI);
5903 std::string Name = FVI->getName(); FVI->setName("");
5904 Instruction *NewSel =
5905 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5906 Name);
5907 InsertNewInstBefore(NewSel, SI);
5908 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5909 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5910 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5911 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5912 else {
5913 assert(0 && "Unknown instruction!!");
5914 }
5915 }
5916 }
5917 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005918
5919 if (BinaryOperator::isNot(CondVal)) {
5920 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5921 SI.setOperand(1, FalseVal);
5922 SI.setOperand(2, TrueVal);
5923 return &SI;
5924 }
5925
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005926 return 0;
5927}
5928
Chris Lattner82f2ef22006-03-06 20:18:44 +00005929/// GetKnownAlignment - If the specified pointer has an alignment that we can
5930/// determine, return it, otherwise return 0.
5931static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5932 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5933 unsigned Align = GV->getAlignment();
5934 if (Align == 0 && TD)
5935 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5936 return Align;
5937 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5938 unsigned Align = AI->getAlignment();
5939 if (Align == 0 && TD) {
5940 if (isa<AllocaInst>(AI))
5941 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5942 else if (isa<MallocInst>(AI)) {
5943 // Malloc returns maximally aligned memory.
5944 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5945 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5946 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5947 }
5948 }
5949 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005950 } else if (isa<CastInst>(V) ||
5951 (isa<ConstantExpr>(V) &&
5952 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5953 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005954 if (isa<PointerType>(CI->getOperand(0)->getType()))
5955 return GetKnownAlignment(CI->getOperand(0), TD);
5956 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005957 } else if (isa<GetElementPtrInst>(V) ||
5958 (isa<ConstantExpr>(V) &&
5959 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5960 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005961 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5962 if (BaseAlignment == 0) return 0;
5963
5964 // If all indexes are zero, it is just the alignment of the base pointer.
5965 bool AllZeroOperands = true;
5966 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5967 if (!isa<Constant>(GEPI->getOperand(i)) ||
5968 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5969 AllZeroOperands = false;
5970 break;
5971 }
5972 if (AllZeroOperands)
5973 return BaseAlignment;
5974
5975 // Otherwise, if the base alignment is >= the alignment we expect for the
5976 // base pointer type, then we know that the resultant pointer is aligned at
5977 // least as much as its type requires.
5978 if (!TD) return 0;
5979
5980 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5981 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005982 <= BaseAlignment) {
5983 const Type *GEPTy = GEPI->getType();
5984 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5985 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005986 return 0;
5987 }
5988 return 0;
5989}
5990
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005991
Chris Lattnerc66b2232006-01-13 20:11:04 +00005992/// visitCallInst - CallInst simplification. This mostly only handles folding
5993/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5994/// the heavy lifting.
5995///
Chris Lattner970c33a2003-06-19 17:00:31 +00005996Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005997 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5998 if (!II) return visitCallSite(&CI);
5999
Chris Lattner51ea1272004-02-28 05:22:00 +00006000 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6001 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006002 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006003 bool Changed = false;
6004
6005 // memmove/cpy/set of zero bytes is a noop.
6006 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6007 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6008
Chris Lattner00648e12004-10-12 04:52:52 +00006009 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6010 if (CI->getRawValue() == 1) {
6011 // Replace the instruction with just byte operations. We would
6012 // transform other cases to loads/stores, but we don't know if
6013 // alignment is sufficient.
6014 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006015 }
6016
Chris Lattner00648e12004-10-12 04:52:52 +00006017 // If we have a memmove and the source operation is a constant global,
6018 // then the source and dest pointers can't alias, so we can change this
6019 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006020 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006021 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6022 if (GVSrc->isConstant()) {
6023 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006024 const char *Name;
6025 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6026 Type::UIntTy)
6027 Name = "llvm.memcpy.i32";
6028 else
6029 Name = "llvm.memcpy.i64";
6030 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006031 CI.getCalledFunction()->getFunctionType());
6032 CI.setOperand(0, MemCpy);
6033 Changed = true;
6034 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006035 }
Chris Lattner00648e12004-10-12 04:52:52 +00006036
Chris Lattner82f2ef22006-03-06 20:18:44 +00006037 // If we can determine a pointer alignment that is bigger than currently
6038 // set, update the alignment.
6039 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6040 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6041 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6042 unsigned Align = std::min(Alignment1, Alignment2);
6043 if (MI->getAlignment()->getRawValue() < Align) {
6044 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6045 Changed = true;
6046 }
6047 } else if (isa<MemSetInst>(MI)) {
6048 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6049 if (MI->getAlignment()->getRawValue() < Alignment) {
6050 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6051 Changed = true;
6052 }
6053 }
6054
Chris Lattnerc66b2232006-01-13 20:11:04 +00006055 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006056 } else {
6057 switch (II->getIntrinsicID()) {
6058 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006059 case Intrinsic::ppc_altivec_lvx:
6060 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006061 case Intrinsic::x86_sse_loadu_ps:
6062 case Intrinsic::x86_sse2_loadu_pd:
6063 case Intrinsic::x86_sse2_loadu_dq:
6064 // Turn PPC lvx -> load if the pointer is known aligned.
6065 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006066 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006067 Value *Ptr = InsertCastBefore(II->getOperand(1),
6068 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006069 return new LoadInst(Ptr);
6070 }
6071 break;
6072 case Intrinsic::ppc_altivec_stvx:
6073 case Intrinsic::ppc_altivec_stvxl:
6074 // Turn stvx -> store if the pointer is known aligned.
6075 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006076 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6077 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006078 return new StoreInst(II->getOperand(1), Ptr);
6079 }
6080 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006081 case Intrinsic::x86_sse_storeu_ps:
6082 case Intrinsic::x86_sse2_storeu_pd:
6083 case Intrinsic::x86_sse2_storeu_dq:
6084 case Intrinsic::x86_sse2_storel_dq:
6085 // Turn X86 storeu -> store if the pointer is known aligned.
6086 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6087 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6088 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6089 return new StoreInst(II->getOperand(2), Ptr);
6090 }
6091 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00006092 case Intrinsic::ppc_altivec_vperm:
6093 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6094 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6095 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6096
6097 // Check that all of the elements are integer constants or undefs.
6098 bool AllEltsOk = true;
6099 for (unsigned i = 0; i != 16; ++i) {
6100 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6101 !isa<UndefValue>(Mask->getOperand(i))) {
6102 AllEltsOk = false;
6103 break;
6104 }
6105 }
6106
6107 if (AllEltsOk) {
6108 // Cast the input vectors to byte vectors.
6109 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6110 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6111 Value *Result = UndefValue::get(Op0->getType());
6112
6113 // Only extract each element once.
6114 Value *ExtractedElts[32];
6115 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6116
6117 for (unsigned i = 0; i != 16; ++i) {
6118 if (isa<UndefValue>(Mask->getOperand(i)))
6119 continue;
6120 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6121 Idx &= 31; // Match the hardware behavior.
6122
6123 if (ExtractedElts[Idx] == 0) {
6124 Instruction *Elt =
6125 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
6126 ConstantUInt::get(Type::UIntTy, Idx&15),
6127 "tmp");
6128 InsertNewInstBefore(Elt, CI);
6129 ExtractedElts[Idx] = Elt;
6130 }
6131
6132 // Insert this value into the result vector.
6133 Result = new InsertElementInst(Result, ExtractedElts[Idx],
6134 ConstantUInt::get(Type::UIntTy, i),
6135 "tmp");
6136 InsertNewInstBefore(cast<Instruction>(Result), CI);
6137 }
6138 return new CastInst(Result, CI.getType());
6139 }
6140 }
6141 break;
6142
Chris Lattner503221f2006-01-13 21:28:09 +00006143 case Intrinsic::stackrestore: {
6144 // If the save is right next to the restore, remove the restore. This can
6145 // happen when variable allocas are DCE'd.
6146 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6147 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6148 BasicBlock::iterator BI = SS;
6149 if (&*++BI == II)
6150 return EraseInstFromFunction(CI);
6151 }
6152 }
6153
6154 // If the stack restore is in a return/unwind block and if there are no
6155 // allocas or calls between the restore and the return, nuke the restore.
6156 TerminatorInst *TI = II->getParent()->getTerminator();
6157 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6158 BasicBlock::iterator BI = II;
6159 bool CannotRemove = false;
6160 for (++BI; &*BI != TI; ++BI) {
6161 if (isa<AllocaInst>(BI) ||
6162 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6163 CannotRemove = true;
6164 break;
6165 }
6166 }
6167 if (!CannotRemove)
6168 return EraseInstFromFunction(CI);
6169 }
6170 break;
6171 }
6172 }
Chris Lattner00648e12004-10-12 04:52:52 +00006173 }
6174
Chris Lattnerc66b2232006-01-13 20:11:04 +00006175 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006176}
6177
6178// InvokeInst simplification
6179//
6180Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006181 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006182}
6183
Chris Lattneraec3d942003-10-07 22:32:43 +00006184// visitCallSite - Improvements for call and invoke instructions.
6185//
6186Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006187 bool Changed = false;
6188
6189 // If the callee is a constexpr cast of a function, attempt to move the cast
6190 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006191 if (transformConstExprCastCall(CS)) return 0;
6192
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006193 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006194
Chris Lattner61d9d812005-05-13 07:09:09 +00006195 if (Function *CalleeF = dyn_cast<Function>(Callee))
6196 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6197 Instruction *OldCall = CS.getInstruction();
6198 // If the call and callee calling conventions don't match, this call must
6199 // be unreachable, as the call is undefined.
6200 new StoreInst(ConstantBool::True,
6201 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6202 if (!OldCall->use_empty())
6203 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6204 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6205 return EraseInstFromFunction(*OldCall);
6206 return 0;
6207 }
6208
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006209 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6210 // This instruction is not reachable, just remove it. We insert a store to
6211 // undef so that we know that this code is not reachable, despite the fact
6212 // that we can't modify the CFG here.
6213 new StoreInst(ConstantBool::True,
6214 UndefValue::get(PointerType::get(Type::BoolTy)),
6215 CS.getInstruction());
6216
6217 if (!CS.getInstruction()->use_empty())
6218 CS.getInstruction()->
6219 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6220
6221 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6222 // Don't break the CFG, insert a dummy cond branch.
6223 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6224 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006225 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006226 return EraseInstFromFunction(*CS.getInstruction());
6227 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006228
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006229 const PointerType *PTy = cast<PointerType>(Callee->getType());
6230 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6231 if (FTy->isVarArg()) {
6232 // See if we can optimize any arguments passed through the varargs area of
6233 // the call.
6234 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6235 E = CS.arg_end(); I != E; ++I)
6236 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6237 // If this cast does not effect the value passed through the varargs
6238 // area, we can eliminate the use of the cast.
6239 Value *Op = CI->getOperand(0);
6240 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6241 *I = Op;
6242 Changed = true;
6243 }
6244 }
6245 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006246
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006247 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006248}
6249
Chris Lattner970c33a2003-06-19 17:00:31 +00006250// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6251// attempt to move the cast to the arguments of the call/invoke.
6252//
6253bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6254 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6255 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006256 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006257 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006258 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006259 Instruction *Caller = CS.getInstruction();
6260
6261 // Okay, this is a cast from a function to a different type. Unless doing so
6262 // would cause a type conversion of one of our arguments, change this call to
6263 // be a direct call with arguments casted to the appropriate types.
6264 //
6265 const FunctionType *FT = Callee->getFunctionType();
6266 const Type *OldRetTy = Caller->getType();
6267
Chris Lattner1f7942f2004-01-14 06:06:08 +00006268 // Check to see if we are changing the return type...
6269 if (OldRetTy != FT->getReturnType()) {
6270 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006271 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6272 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006273 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006274 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006275 return false; // Cannot transform this return value...
6276
6277 // If the callsite is an invoke instruction, and the return value is used by
6278 // a PHI node in a successor, we cannot change the return type of the call
6279 // because there is no place to put the cast instruction (without breaking
6280 // the critical edge). Bail out in this case.
6281 if (!Caller->use_empty())
6282 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6283 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6284 UI != E; ++UI)
6285 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6286 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006287 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006288 return false;
6289 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006290
6291 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6292 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006293
Chris Lattner970c33a2003-06-19 17:00:31 +00006294 CallSite::arg_iterator AI = CS.arg_begin();
6295 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6296 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006297 const Type *ActTy = (*AI)->getType();
6298 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6299 //Either we can cast directly, or we can upconvert the argument
6300 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6301 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6302 ParamTy->isSigned() == ActTy->isSigned() &&
6303 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6304 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6305 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006306 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006307 }
6308
6309 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6310 Callee->isExternal())
6311 return false; // Do not delete arguments unless we have a function body...
6312
6313 // Okay, we decided that this is a safe thing to do: go ahead and start
6314 // inserting cast instructions as necessary...
6315 std::vector<Value*> Args;
6316 Args.reserve(NumActualArgs);
6317
6318 AI = CS.arg_begin();
6319 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6320 const Type *ParamTy = FT->getParamType(i);
6321 if ((*AI)->getType() == ParamTy) {
6322 Args.push_back(*AI);
6323 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006324 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6325 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006326 }
6327 }
6328
6329 // If the function takes more arguments than the call was taking, add them
6330 // now...
6331 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6332 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6333
6334 // If we are removing arguments to the function, emit an obnoxious warning...
6335 if (FT->getNumParams() < NumActualArgs)
6336 if (!FT->isVarArg()) {
6337 std::cerr << "WARNING: While resolving call to function '"
6338 << Callee->getName() << "' arguments were dropped!\n";
6339 } else {
6340 // Add all of the arguments in their promoted form to the arg list...
6341 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6342 const Type *PTy = getPromotedType((*AI)->getType());
6343 if (PTy != (*AI)->getType()) {
6344 // Must promote to pass through va_arg area!
6345 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6346 InsertNewInstBefore(Cast, *Caller);
6347 Args.push_back(Cast);
6348 } else {
6349 Args.push_back(*AI);
6350 }
6351 }
6352 }
6353
6354 if (FT->getReturnType() == Type::VoidTy)
6355 Caller->setName(""); // Void type should not have a name...
6356
6357 Instruction *NC;
6358 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006359 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006360 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006361 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006362 } else {
6363 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006364 if (cast<CallInst>(Caller)->isTailCall())
6365 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006366 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006367 }
6368
6369 // Insert a cast of the return type as necessary...
6370 Value *NV = NC;
6371 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6372 if (NV->getType() != Type::VoidTy) {
6373 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006374
6375 // If this is an invoke instruction, we should insert it after the first
6376 // non-phi, instruction in the normal successor block.
6377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6378 BasicBlock::iterator I = II->getNormalDest()->begin();
6379 while (isa<PHINode>(I)) ++I;
6380 InsertNewInstBefore(NC, *I);
6381 } else {
6382 // Otherwise, it's a call, just insert cast right after the call instr
6383 InsertNewInstBefore(NC, *Caller);
6384 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006385 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006386 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006387 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006388 }
6389 }
6390
6391 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6392 Caller->replaceAllUsesWith(NV);
6393 Caller->getParent()->getInstList().erase(Caller);
6394 removeFromWorkList(Caller);
6395 return true;
6396}
6397
6398
Chris Lattner7515cab2004-11-14 19:13:23 +00006399// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6400// operator and they all are only used by the PHI, PHI together their
6401// inputs, and do the operation once, to the result of the PHI.
6402Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6403 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6404
6405 // Scan the instruction, looking for input operations that can be folded away.
6406 // If all input operands to the phi are the same instruction (e.g. a cast from
6407 // the same type or "+42") we can pull the operation through the PHI, reducing
6408 // code size and simplifying code.
6409 Constant *ConstantOp = 0;
6410 const Type *CastSrcTy = 0;
6411 if (isa<CastInst>(FirstInst)) {
6412 CastSrcTy = FirstInst->getOperand(0)->getType();
6413 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6414 // Can fold binop or shift if the RHS is a constant.
6415 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6416 if (ConstantOp == 0) return 0;
6417 } else {
6418 return 0; // Cannot fold this operation.
6419 }
6420
6421 // Check to see if all arguments are the same operation.
6422 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6423 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6424 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6425 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6426 return 0;
6427 if (CastSrcTy) {
6428 if (I->getOperand(0)->getType() != CastSrcTy)
6429 return 0; // Cast operation must match.
6430 } else if (I->getOperand(1) != ConstantOp) {
6431 return 0;
6432 }
6433 }
6434
6435 // Okay, they are all the same operation. Create a new PHI node of the
6436 // correct type, and PHI together all of the LHS's of the instructions.
6437 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6438 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006439 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006440
6441 Value *InVal = FirstInst->getOperand(0);
6442 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006443
6444 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006445 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6446 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6447 if (NewInVal != InVal)
6448 InVal = 0;
6449 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6450 }
6451
6452 Value *PhiVal;
6453 if (InVal) {
6454 // The new PHI unions all of the same values together. This is really
6455 // common, so we handle it intelligently here for compile-time speed.
6456 PhiVal = InVal;
6457 delete NewPN;
6458 } else {
6459 InsertNewInstBefore(NewPN, PN);
6460 PhiVal = NewPN;
6461 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006462
Chris Lattner7515cab2004-11-14 19:13:23 +00006463 // Insert and return the new operation.
6464 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006465 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006466 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006467 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006468 else
6469 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006470 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006471}
Chris Lattner48a44f72002-05-02 17:06:02 +00006472
Chris Lattner71536432005-01-17 05:10:15 +00006473/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6474/// that is dead.
6475static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6476 if (PN->use_empty()) return true;
6477 if (!PN->hasOneUse()) return false;
6478
6479 // Remember this node, and if we find the cycle, return.
6480 if (!PotentiallyDeadPHIs.insert(PN).second)
6481 return true;
6482
6483 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6484 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006485
Chris Lattner71536432005-01-17 05:10:15 +00006486 return false;
6487}
6488
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006489// PHINode simplification
6490//
Chris Lattner113f4f42002-06-25 16:13:24 +00006491Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006492 // If LCSSA is around, don't mess with Phi nodes
6493 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006494
Owen Andersonae8aa642006-07-10 22:03:18 +00006495 if (Value *V = PN.hasConstantValue())
6496 return ReplaceInstUsesWith(PN, V);
6497
6498 // If the only user of this instruction is a cast instruction, and all of the
6499 // incoming values are constants, change this PHI to merge together the casted
6500 // constants.
6501 if (PN.hasOneUse())
6502 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6503 if (CI->getType() != PN.getType()) { // noop casts will be folded
6504 bool AllConstant = true;
6505 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6506 if (!isa<Constant>(PN.getIncomingValue(i))) {
6507 AllConstant = false;
6508 break;
6509 }
6510 if (AllConstant) {
6511 // Make a new PHI with all casted values.
6512 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6513 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6514 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6515 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6516 PN.getIncomingBlock(i));
6517 }
6518
6519 // Update the cast instruction.
6520 CI->setOperand(0, New);
6521 WorkList.push_back(CI); // revisit the cast instruction to fold.
6522 WorkList.push_back(New); // Make sure to revisit the new Phi
6523 return &PN; // PN is now dead!
6524 }
6525 }
6526
6527 // If all PHI operands are the same operation, pull them through the PHI,
6528 // reducing code size.
6529 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6530 PN.getIncomingValue(0)->hasOneUse())
6531 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6532 return Result;
6533
6534 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6535 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6536 // PHI)... break the cycle.
6537 if (PN.hasOneUse())
6538 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6539 std::set<PHINode*> PotentiallyDeadPHIs;
6540 PotentiallyDeadPHIs.insert(&PN);
6541 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6542 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6543 }
6544
Chris Lattner91daeb52003-12-19 05:58:40 +00006545 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006546}
6547
Chris Lattner69193f92004-04-05 01:30:19 +00006548static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6549 Instruction *InsertPoint,
6550 InstCombiner *IC) {
6551 unsigned PS = IC->getTargetData().getPointerSize();
6552 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006553 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6554 // We must insert a cast to ensure we sign-extend.
6555 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6556 V->getName()), *InsertPoint);
6557 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6558 *InsertPoint);
6559}
6560
Chris Lattner48a44f72002-05-02 17:06:02 +00006561
Chris Lattner113f4f42002-06-25 16:13:24 +00006562Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006563 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006564 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006565 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006566 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006567 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006568
Chris Lattner81a7a232004-10-16 18:11:37 +00006569 if (isa<UndefValue>(GEP.getOperand(0)))
6570 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6571
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006572 bool HasZeroPointerIndex = false;
6573 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6574 HasZeroPointerIndex = C->isNullValue();
6575
6576 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006577 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006578
Chris Lattner69193f92004-04-05 01:30:19 +00006579 // Eliminate unneeded casts for indices.
6580 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006581 gep_type_iterator GTI = gep_type_begin(GEP);
6582 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6583 if (isa<SequentialType>(*GTI)) {
6584 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6585 Value *Src = CI->getOperand(0);
6586 const Type *SrcTy = Src->getType();
6587 const Type *DestTy = CI->getType();
6588 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006589 if (SrcTy->getPrimitiveSizeInBits() ==
6590 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006591 // We can always eliminate a cast from ulong or long to the other.
6592 // We can always eliminate a cast from uint to int or the other on
6593 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006594 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006595 MadeChange = true;
6596 GEP.setOperand(i, Src);
6597 }
6598 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6599 SrcTy->getPrimitiveSize() == 4) {
6600 // We can always eliminate a cast from int to [u]long. We can
6601 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6602 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006603 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006604 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006605 MadeChange = true;
6606 GEP.setOperand(i, Src);
6607 }
Chris Lattner69193f92004-04-05 01:30:19 +00006608 }
6609 }
6610 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006611 // If we are using a wider index than needed for this platform, shrink it
6612 // to what we need. If the incoming value needs a cast instruction,
6613 // insert it. This explicit cast can make subsequent optimizations more
6614 // obvious.
6615 Value *Op = GEP.getOperand(i);
6616 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006617 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006618 GEP.setOperand(i, ConstantExpr::getCast(C,
6619 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006620 MadeChange = true;
6621 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006622 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6623 Op->getName()), GEP);
6624 GEP.setOperand(i, Op);
6625 MadeChange = true;
6626 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006627
6628 // If this is a constant idx, make sure to canonicalize it to be a signed
6629 // operand, otherwise CSE and other optimizations are pessimized.
6630 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6631 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6632 CUI->getType()->getSignedVersion()));
6633 MadeChange = true;
6634 }
Chris Lattner69193f92004-04-05 01:30:19 +00006635 }
6636 if (MadeChange) return &GEP;
6637
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006638 // Combine Indices - If the source pointer to this getelementptr instruction
6639 // is a getelementptr instruction, combine the indices of the two
6640 // getelementptr instructions into a single instruction.
6641 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006642 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006643 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006644 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006645
6646 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006647 // Note that if our source is a gep chain itself that we wait for that
6648 // chain to be resolved before we perform this transformation. This
6649 // avoids us creating a TON of code in some cases.
6650 //
6651 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6652 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6653 return 0; // Wait until our source is folded to completion.
6654
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006655 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006656
6657 // Find out whether the last index in the source GEP is a sequential idx.
6658 bool EndsWithSequential = false;
6659 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6660 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006661 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006662
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006663 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006664 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006665 // Replace: gep (gep %P, long B), long A, ...
6666 // With: T = long A+B; gep %P, T, ...
6667 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006668 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006669 if (SO1 == Constant::getNullValue(SO1->getType())) {
6670 Sum = GO1;
6671 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6672 Sum = SO1;
6673 } else {
6674 // If they aren't the same type, convert both to an integer of the
6675 // target's pointer size.
6676 if (SO1->getType() != GO1->getType()) {
6677 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6678 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6679 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6680 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6681 } else {
6682 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006683 if (SO1->getType()->getPrimitiveSize() == PS) {
6684 // Convert GO1 to SO1's type.
6685 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6686
6687 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6688 // Convert SO1 to GO1's type.
6689 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6690 } else {
6691 const Type *PT = TD->getIntPtrType();
6692 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6693 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6694 }
6695 }
6696 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006697 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6698 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6699 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006700 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6701 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006702 }
Chris Lattner69193f92004-04-05 01:30:19 +00006703 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006704
6705 // Recycle the GEP we already have if possible.
6706 if (SrcGEPOperands.size() == 2) {
6707 GEP.setOperand(0, SrcGEPOperands[0]);
6708 GEP.setOperand(1, Sum);
6709 return &GEP;
6710 } else {
6711 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6712 SrcGEPOperands.end()-1);
6713 Indices.push_back(Sum);
6714 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6715 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006716 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006717 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006718 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006719 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006720 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6721 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006722 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6723 }
6724
6725 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006726 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006727
Chris Lattner5f667a62004-05-07 22:09:22 +00006728 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006729 // GEP of global variable. If all of the indices for this GEP are
6730 // constants, we can promote this to a constexpr instead of an instruction.
6731
6732 // Scan for nonconstants...
6733 std::vector<Constant*> Indices;
6734 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6735 for (; I != E && isa<Constant>(*I); ++I)
6736 Indices.push_back(cast<Constant>(*I));
6737
6738 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006739 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006740
6741 // Replace all uses of the GEP with the new constexpr...
6742 return ReplaceInstUsesWith(GEP, CE);
6743 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006744 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6745 if (!isa<PointerType>(X->getType())) {
6746 // Not interesting. Source pointer must be a cast from pointer.
6747 } else if (HasZeroPointerIndex) {
6748 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6749 // into : GEP [10 x ubyte]* X, long 0, ...
6750 //
6751 // This occurs when the program declares an array extern like "int X[];"
6752 //
6753 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6754 const PointerType *XTy = cast<PointerType>(X->getType());
6755 if (const ArrayType *XATy =
6756 dyn_cast<ArrayType>(XTy->getElementType()))
6757 if (const ArrayType *CATy =
6758 dyn_cast<ArrayType>(CPTy->getElementType()))
6759 if (CATy->getElementType() == XATy->getElementType()) {
6760 // At this point, we know that the cast source type is a pointer
6761 // to an array of the same type as the destination pointer
6762 // array. Because the array type is never stepped over (there
6763 // is a leading zero) we can fold the cast into this GEP.
6764 GEP.setOperand(0, X);
6765 return &GEP;
6766 }
6767 } else if (GEP.getNumOperands() == 2) {
6768 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006769 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6770 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006771 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6772 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6773 if (isa<ArrayType>(SrcElTy) &&
6774 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6775 TD->getTypeSize(ResElTy)) {
6776 Value *V = InsertNewInstBefore(
6777 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6778 GEP.getOperand(1), GEP.getName()), GEP);
6779 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006780 }
Chris Lattner2a893292005-09-13 18:36:04 +00006781
6782 // Transform things like:
6783 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6784 // (where tmp = 8*tmp2) into:
6785 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6786
6787 if (isa<ArrayType>(SrcElTy) &&
6788 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6789 uint64_t ArrayEltSize =
6790 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6791
6792 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6793 // allow either a mul, shift, or constant here.
6794 Value *NewIdx = 0;
6795 ConstantInt *Scale = 0;
6796 if (ArrayEltSize == 1) {
6797 NewIdx = GEP.getOperand(1);
6798 Scale = ConstantInt::get(NewIdx->getType(), 1);
6799 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006800 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006801 Scale = CI;
6802 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6803 if (Inst->getOpcode() == Instruction::Shl &&
6804 isa<ConstantInt>(Inst->getOperand(1))) {
6805 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6806 if (Inst->getType()->isSigned())
6807 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6808 else
6809 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6810 NewIdx = Inst->getOperand(0);
6811 } else if (Inst->getOpcode() == Instruction::Mul &&
6812 isa<ConstantInt>(Inst->getOperand(1))) {
6813 Scale = cast<ConstantInt>(Inst->getOperand(1));
6814 NewIdx = Inst->getOperand(0);
6815 }
6816 }
6817
6818 // If the index will be to exactly the right offset with the scale taken
6819 // out, perform the transformation.
6820 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6821 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6822 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006823 (int64_t)C->getRawValue() /
6824 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006825 else
6826 Scale = ConstantUInt::get(Scale->getType(),
6827 Scale->getRawValue() / ArrayEltSize);
6828 if (Scale->getRawValue() != 1) {
6829 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6830 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6831 NewIdx = InsertNewInstBefore(Sc, GEP);
6832 }
6833
6834 // Insert the new GEP instruction.
6835 Instruction *Idx =
6836 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6837 NewIdx, GEP.getName());
6838 Idx = InsertNewInstBefore(Idx, GEP);
6839 return new CastInst(Idx, GEP.getType());
6840 }
6841 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006842 }
Chris Lattnerca081252001-12-14 16:52:21 +00006843 }
6844
Chris Lattnerca081252001-12-14 16:52:21 +00006845 return 0;
6846}
6847
Chris Lattner1085bdf2002-11-04 16:18:53 +00006848Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6849 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6850 if (AI.isArrayAllocation()) // Check C != 1
6851 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6852 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006853 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006854
6855 // Create and insert the replacement instruction...
6856 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006857 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006858 else {
6859 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006860 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006861 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006862
6863 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006864
Chris Lattner1085bdf2002-11-04 16:18:53 +00006865 // Scan to the end of the allocation instructions, to skip over a block of
6866 // allocas if possible...
6867 //
6868 BasicBlock::iterator It = New;
6869 while (isa<AllocationInst>(*It)) ++It;
6870
6871 // Now that I is pointing to the first non-allocation-inst in the block,
6872 // insert our getelementptr instruction...
6873 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006874 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6875 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6876 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006877
6878 // Now make everything use the getelementptr instead of the original
6879 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006880 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006881 } else if (isa<UndefValue>(AI.getArraySize())) {
6882 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006883 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006884
6885 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6886 // Note that we only do this for alloca's, because malloc should allocate and
6887 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006888 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006889 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006890 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6891
Chris Lattner1085bdf2002-11-04 16:18:53 +00006892 return 0;
6893}
6894
Chris Lattner8427bff2003-12-07 01:24:23 +00006895Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6896 Value *Op = FI.getOperand(0);
6897
6898 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6899 if (CastInst *CI = dyn_cast<CastInst>(Op))
6900 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6901 FI.setOperand(0, CI->getOperand(0));
6902 return &FI;
6903 }
6904
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006905 // free undef -> unreachable.
6906 if (isa<UndefValue>(Op)) {
6907 // Insert a new store to null because we cannot modify the CFG here.
6908 new StoreInst(ConstantBool::True,
6909 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6910 return EraseInstFromFunction(FI);
6911 }
6912
Chris Lattnerf3a36602004-02-28 04:57:37 +00006913 // If we have 'free null' delete the instruction. This can happen in stl code
6914 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006915 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006916 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006917
Chris Lattner8427bff2003-12-07 01:24:23 +00006918 return 0;
6919}
6920
6921
Chris Lattner72684fe2005-01-31 05:51:45 +00006922/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006923static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6924 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006925 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006926
6927 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006928 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006929 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006930
Chris Lattnerebca4762006-04-02 05:37:12 +00006931 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6932 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006933 // If the source is an array, the code below will not succeed. Check to
6934 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6935 // constants.
6936 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6937 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6938 if (ASrcTy->getNumElements() != 0) {
6939 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6940 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6941 SrcTy = cast<PointerType>(CastOp->getType());
6942 SrcPTy = SrcTy->getElementType();
6943 }
6944
Chris Lattnerebca4762006-04-02 05:37:12 +00006945 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6946 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006947 // Do not allow turning this into a load of an integer, which is then
6948 // casted to a pointer, this pessimizes pointer analysis a lot.
6949 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006950 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006951 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006952
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006953 // Okay, we are casting from one integer or pointer type to another of
6954 // the same size. Instead of casting the pointer before the load, cast
6955 // the result of the loaded value.
6956 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6957 CI->getName(),
6958 LI.isVolatile()),LI);
6959 // Now cast the result of the load.
6960 return new CastInst(NewLoad, LI.getType());
6961 }
Chris Lattner35e24772004-07-13 01:49:43 +00006962 }
6963 }
6964 return 0;
6965}
6966
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006967/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006968/// from this value cannot trap. If it is not obviously safe to load from the
6969/// specified pointer, we do a quick local scan of the basic block containing
6970/// ScanFrom, to determine if the address is already accessed.
6971static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6972 // If it is an alloca or global variable, it is always safe to load from.
6973 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6974
6975 // Otherwise, be a little bit agressive by scanning the local block where we
6976 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006977 // from/to. If so, the previous load or store would have already trapped,
6978 // so there is no harm doing an extra load (also, CSE will later eliminate
6979 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006980 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6981
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006982 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006983 --BBI;
6984
6985 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6986 if (LI->getOperand(0) == V) return true;
6987 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6988 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006989
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006990 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006991 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006992}
6993
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006994Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6995 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006996
Chris Lattnera9d84e32005-05-01 04:24:53 +00006997 // load (cast X) --> cast (load X) iff safe
6998 if (CastInst *CI = dyn_cast<CastInst>(Op))
6999 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7000 return Res;
7001
7002 // None of the following transforms are legal for volatile loads.
7003 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007004
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007005 if (&LI.getParent()->front() != &LI) {
7006 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007007 // If the instruction immediately before this is a store to the same
7008 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007009 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7010 if (SI->getOperand(1) == LI.getOperand(0))
7011 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007012 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7013 if (LIB->getOperand(0) == LI.getOperand(0))
7014 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007015 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007016
7017 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7018 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7019 isa<UndefValue>(GEPI->getOperand(0))) {
7020 // Insert a new store to null instruction before the load to indicate
7021 // that this code is not reachable. We do this instead of inserting
7022 // an unreachable instruction directly because we cannot modify the
7023 // CFG.
7024 new StoreInst(UndefValue::get(LI.getType()),
7025 Constant::getNullValue(Op->getType()), &LI);
7026 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7027 }
7028
Chris Lattner81a7a232004-10-16 18:11:37 +00007029 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007030 // load null/undef -> undef
7031 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007032 // Insert a new store to null instruction before the load to indicate that
7033 // this code is not reachable. We do this instead of inserting an
7034 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007035 new StoreInst(UndefValue::get(LI.getType()),
7036 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007037 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007038 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007039
Chris Lattner81a7a232004-10-16 18:11:37 +00007040 // Instcombine load (constant global) into the value loaded.
7041 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7042 if (GV->isConstant() && !GV->isExternal())
7043 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007044
Chris Lattner81a7a232004-10-16 18:11:37 +00007045 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7046 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7047 if (CE->getOpcode() == Instruction::GetElementPtr) {
7048 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7049 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007050 if (Constant *V =
7051 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007052 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007053 if (CE->getOperand(0)->isNullValue()) {
7054 // Insert a new store to null instruction before the load to indicate
7055 // that this code is not reachable. We do this instead of inserting
7056 // an unreachable instruction directly because we cannot modify the
7057 // CFG.
7058 new StoreInst(UndefValue::get(LI.getType()),
7059 Constant::getNullValue(Op->getType()), &LI);
7060 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7061 }
7062
Chris Lattner81a7a232004-10-16 18:11:37 +00007063 } else if (CE->getOpcode() == Instruction::Cast) {
7064 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7065 return Res;
7066 }
7067 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007068
Chris Lattnera9d84e32005-05-01 04:24:53 +00007069 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007070 // Change select and PHI nodes to select values instead of addresses: this
7071 // helps alias analysis out a lot, allows many others simplifications, and
7072 // exposes redundancy in the code.
7073 //
7074 // Note that we cannot do the transformation unless we know that the
7075 // introduced loads cannot trap! Something like this is valid as long as
7076 // the condition is always false: load (select bool %C, int* null, int* %G),
7077 // but it would not be valid if we transformed it to load from null
7078 // unconditionally.
7079 //
7080 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7081 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007082 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7083 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007084 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007085 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007086 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007087 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007088 return new SelectInst(SI->getCondition(), V1, V2);
7089 }
7090
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007091 // load (select (cond, null, P)) -> load P
7092 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7093 if (C->isNullValue()) {
7094 LI.setOperand(0, SI->getOperand(2));
7095 return &LI;
7096 }
7097
7098 // load (select (cond, P, null)) -> load P
7099 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7100 if (C->isNullValue()) {
7101 LI.setOperand(0, SI->getOperand(1));
7102 return &LI;
7103 }
7104
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007105 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7106 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007107 bool Safe = PN->getParent() == LI.getParent();
7108
7109 // Scan all of the instructions between the PHI and the load to make
7110 // sure there are no instructions that might possibly alter the value
7111 // loaded from the PHI.
7112 if (Safe) {
7113 BasicBlock::iterator I = &LI;
7114 for (--I; !isa<PHINode>(I); --I)
7115 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7116 Safe = false;
7117 break;
7118 }
7119 }
7120
7121 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007122 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007123 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007124 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007125
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007126 if (Safe) {
7127 // Create the PHI.
7128 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7129 InsertNewInstBefore(NewPN, *PN);
7130 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7131
7132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7133 BasicBlock *BB = PN->getIncomingBlock(i);
7134 Value *&TheLoad = LoadMap[BB];
7135 if (TheLoad == 0) {
7136 Value *InVal = PN->getIncomingValue(i);
7137 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7138 InVal->getName()+".val"),
7139 *BB->getTerminator());
7140 }
7141 NewPN->addIncoming(TheLoad, BB);
7142 }
7143 return ReplaceInstUsesWith(LI, NewPN);
7144 }
7145 }
7146 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007147 return 0;
7148}
7149
Chris Lattner72684fe2005-01-31 05:51:45 +00007150/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7151/// when possible.
7152static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7153 User *CI = cast<User>(SI.getOperand(1));
7154 Value *CastOp = CI->getOperand(0);
7155
7156 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7157 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7158 const Type *SrcPTy = SrcTy->getElementType();
7159
7160 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7161 // If the source is an array, the code below will not succeed. Check to
7162 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7163 // constants.
7164 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7165 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7166 if (ASrcTy->getNumElements() != 0) {
7167 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7168 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7169 SrcTy = cast<PointerType>(CastOp->getType());
7170 SrcPTy = SrcTy->getElementType();
7171 }
7172
7173 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007174 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007175 IC.getTargetData().getTypeSize(DestPTy)) {
7176
7177 // Okay, we are casting from one integer or pointer type to another of
7178 // the same size. Instead of casting the pointer before the store, cast
7179 // the value to be stored.
7180 Value *NewCast;
7181 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7182 NewCast = ConstantExpr::getCast(C, SrcPTy);
7183 else
7184 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7185 SrcPTy,
7186 SI.getOperand(0)->getName()+".c"), SI);
7187
7188 return new StoreInst(NewCast, CastOp);
7189 }
7190 }
7191 }
7192 return 0;
7193}
7194
Chris Lattner31f486c2005-01-31 05:36:43 +00007195Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7196 Value *Val = SI.getOperand(0);
7197 Value *Ptr = SI.getOperand(1);
7198
7199 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007200 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007201 ++NumCombined;
7202 return 0;
7203 }
7204
Chris Lattner5997cf92006-02-08 03:25:32 +00007205 // Do really simple DSE, to catch cases where there are several consequtive
7206 // stores to the same location, separated by a few arithmetic operations. This
7207 // situation often occurs with bitfield accesses.
7208 BasicBlock::iterator BBI = &SI;
7209 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7210 --ScanInsts) {
7211 --BBI;
7212
7213 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7214 // Prev store isn't volatile, and stores to the same location?
7215 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7216 ++NumDeadStore;
7217 ++BBI;
7218 EraseInstFromFunction(*PrevSI);
7219 continue;
7220 }
7221 break;
7222 }
7223
Chris Lattnerdab43b22006-05-26 19:19:20 +00007224 // If this is a load, we have to stop. However, if the loaded value is from
7225 // the pointer we're loading and is producing the pointer we're storing,
7226 // then *this* store is dead (X = load P; store X -> P).
7227 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7228 if (LI == Val && LI->getOperand(0) == Ptr) {
7229 EraseInstFromFunction(SI);
7230 ++NumCombined;
7231 return 0;
7232 }
7233 // Otherwise, this is a load from some other location. Stores before it
7234 // may not be dead.
7235 break;
7236 }
7237
Chris Lattner5997cf92006-02-08 03:25:32 +00007238 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007239 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007240 break;
7241 }
7242
7243
7244 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007245
7246 // store X, null -> turns into 'unreachable' in SimplifyCFG
7247 if (isa<ConstantPointerNull>(Ptr)) {
7248 if (!isa<UndefValue>(Val)) {
7249 SI.setOperand(0, UndefValue::get(Val->getType()));
7250 if (Instruction *U = dyn_cast<Instruction>(Val))
7251 WorkList.push_back(U); // Dropped a use.
7252 ++NumCombined;
7253 }
7254 return 0; // Do not modify these!
7255 }
7256
7257 // store undef, Ptr -> noop
7258 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007259 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007260 ++NumCombined;
7261 return 0;
7262 }
7263
Chris Lattner72684fe2005-01-31 05:51:45 +00007264 // If the pointer destination is a cast, see if we can fold the cast into the
7265 // source instead.
7266 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7267 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7268 return Res;
7269 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7270 if (CE->getOpcode() == Instruction::Cast)
7271 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7272 return Res;
7273
Chris Lattner219175c2005-09-12 23:23:25 +00007274
7275 // If this store is the last instruction in the basic block, and if the block
7276 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007277 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007278 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7279 if (BI->isUnconditional()) {
7280 // Check to see if the successor block has exactly two incoming edges. If
7281 // so, see if the other predecessor contains a store to the same location.
7282 // if so, insert a PHI node (if needed) and move the stores down.
7283 BasicBlock *Dest = BI->getSuccessor(0);
7284
7285 pred_iterator PI = pred_begin(Dest);
7286 BasicBlock *Other = 0;
7287 if (*PI != BI->getParent())
7288 Other = *PI;
7289 ++PI;
7290 if (PI != pred_end(Dest)) {
7291 if (*PI != BI->getParent())
7292 if (Other)
7293 Other = 0;
7294 else
7295 Other = *PI;
7296 if (++PI != pred_end(Dest))
7297 Other = 0;
7298 }
7299 if (Other) { // If only one other pred...
7300 BBI = Other->getTerminator();
7301 // Make sure this other block ends in an unconditional branch and that
7302 // there is an instruction before the branch.
7303 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7304 BBI != Other->begin()) {
7305 --BBI;
7306 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7307
7308 // If this instruction is a store to the same location.
7309 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7310 // Okay, we know we can perform this transformation. Insert a PHI
7311 // node now if we need it.
7312 Value *MergedVal = OtherStore->getOperand(0);
7313 if (MergedVal != SI.getOperand(0)) {
7314 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7315 PN->reserveOperandSpace(2);
7316 PN->addIncoming(SI.getOperand(0), SI.getParent());
7317 PN->addIncoming(OtherStore->getOperand(0), Other);
7318 MergedVal = InsertNewInstBefore(PN, Dest->front());
7319 }
7320
7321 // Advance to a place where it is safe to insert the new store and
7322 // insert it.
7323 BBI = Dest->begin();
7324 while (isa<PHINode>(BBI)) ++BBI;
7325 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7326 OtherStore->isVolatile()), *BBI);
7327
7328 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007329 EraseInstFromFunction(SI);
7330 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007331 ++NumCombined;
7332 return 0;
7333 }
7334 }
7335 }
7336 }
7337
Chris Lattner31f486c2005-01-31 05:36:43 +00007338 return 0;
7339}
7340
7341
Chris Lattner9eef8a72003-06-04 04:46:00 +00007342Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7343 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007344 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007345 BasicBlock *TrueDest;
7346 BasicBlock *FalseDest;
7347 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7348 !isa<Constant>(X)) {
7349 // Swap Destinations and condition...
7350 BI.setCondition(X);
7351 BI.setSuccessor(0, FalseDest);
7352 BI.setSuccessor(1, TrueDest);
7353 return &BI;
7354 }
7355
7356 // Cannonicalize setne -> seteq
7357 Instruction::BinaryOps Op; Value *Y;
7358 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7359 TrueDest, FalseDest)))
7360 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7361 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7362 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7363 std::string Name = I->getName(); I->setName("");
7364 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7365 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007366 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007367 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007368 BI.setSuccessor(0, FalseDest);
7369 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007370 removeFromWorkList(I);
7371 I->getParent()->getInstList().erase(I);
7372 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007373 return &BI;
7374 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007375
Chris Lattner9eef8a72003-06-04 04:46:00 +00007376 return 0;
7377}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007378
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007379Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7380 Value *Cond = SI.getCondition();
7381 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7382 if (I->getOpcode() == Instruction::Add)
7383 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7384 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7385 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007386 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007387 AddRHS));
7388 SI.setOperand(0, I->getOperand(0));
7389 WorkList.push_back(I);
7390 return &SI;
7391 }
7392 }
7393 return 0;
7394}
7395
Chris Lattner6bc98652006-03-05 00:22:33 +00007396/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7397/// is to leave as a vector operation.
7398static bool CheapToScalarize(Value *V, bool isConstant) {
7399 if (isa<ConstantAggregateZero>(V))
7400 return true;
7401 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7402 if (isConstant) return true;
7403 // If all elts are the same, we can extract.
7404 Constant *Op0 = C->getOperand(0);
7405 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7406 if (C->getOperand(i) != Op0)
7407 return false;
7408 return true;
7409 }
7410 Instruction *I = dyn_cast<Instruction>(V);
7411 if (!I) return false;
7412
7413 // Insert element gets simplified to the inserted element or is deleted if
7414 // this is constant idx extract element and its a constant idx insertelt.
7415 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7416 isa<ConstantInt>(I->getOperand(2)))
7417 return true;
7418 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7419 return true;
7420 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7421 if (BO->hasOneUse() &&
7422 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7423 CheapToScalarize(BO->getOperand(1), isConstant)))
7424 return true;
7425
7426 return false;
7427}
7428
Chris Lattner12249be2006-05-25 23:48:38 +00007429/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7430/// elements into values that are larger than the #elts in the input.
7431static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7432 unsigned NElts = SVI->getType()->getNumElements();
7433 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7434 return std::vector<unsigned>(NElts, 0);
7435 if (isa<UndefValue>(SVI->getOperand(2)))
7436 return std::vector<unsigned>(NElts, 2*NElts);
7437
7438 std::vector<unsigned> Result;
7439 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7440 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7441 if (isa<UndefValue>(CP->getOperand(i)))
7442 Result.push_back(NElts*2); // undef -> 8
7443 else
7444 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7445 return Result;
7446}
7447
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007448/// FindScalarElement - Given a vector and an element number, see if the scalar
7449/// value is already around as a register, for example if it were inserted then
7450/// extracted from the vector.
7451static Value *FindScalarElement(Value *V, unsigned EltNo) {
7452 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7453 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007454 unsigned Width = PTy->getNumElements();
7455 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007456 return UndefValue::get(PTy->getElementType());
7457
7458 if (isa<UndefValue>(V))
7459 return UndefValue::get(PTy->getElementType());
7460 else if (isa<ConstantAggregateZero>(V))
7461 return Constant::getNullValue(PTy->getElementType());
7462 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7463 return CP->getOperand(EltNo);
7464 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7465 // If this is an insert to a variable element, we don't know what it is.
7466 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7467 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7468
7469 // If this is an insert to the element we are looking for, return the
7470 // inserted value.
7471 if (EltNo == IIElt) return III->getOperand(1);
7472
7473 // Otherwise, the insertelement doesn't modify the value, recurse on its
7474 // vector input.
7475 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007476 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007477 unsigned InEl = getShuffleMask(SVI)[EltNo];
7478 if (InEl < Width)
7479 return FindScalarElement(SVI->getOperand(0), InEl);
7480 else if (InEl < Width*2)
7481 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7482 else
7483 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007484 }
7485
7486 // Otherwise, we don't know.
7487 return 0;
7488}
7489
Robert Bocchinoa8352962006-01-13 22:48:06 +00007490Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007491
Chris Lattner92346c32006-03-31 18:25:14 +00007492 // If packed val is undef, replace extract with scalar undef.
7493 if (isa<UndefValue>(EI.getOperand(0)))
7494 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7495
7496 // If packed val is constant 0, replace extract with scalar 0.
7497 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7498 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7499
Robert Bocchinoa8352962006-01-13 22:48:06 +00007500 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7501 // If packed val is constant with uniform operands, replace EI
7502 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007503 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007504 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007505 if (C->getOperand(i) != op0) {
7506 op0 = 0;
7507 break;
7508 }
7509 if (op0)
7510 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007511 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007512
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007513 // If extracting a specified index from the vector, see if we can recursively
7514 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007515 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007516 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7517 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007518 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007519
Chris Lattner83f65782006-05-25 22:53:38 +00007520 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007521 if (I->hasOneUse()) {
7522 // Push extractelement into predecessor operation if legal and
7523 // profitable to do so
7524 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007525 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7526 if (CheapToScalarize(BO, isConstantElt)) {
7527 ExtractElementInst *newEI0 =
7528 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7529 EI.getName()+".lhs");
7530 ExtractElementInst *newEI1 =
7531 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7532 EI.getName()+".rhs");
7533 InsertNewInstBefore(newEI0, EI);
7534 InsertNewInstBefore(newEI1, EI);
7535 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7536 }
7537 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007538 Value *Ptr = InsertCastBefore(I->getOperand(0),
7539 PointerType::get(EI.getType()), EI);
7540 GetElementPtrInst *GEP =
7541 new GetElementPtrInst(Ptr, EI.getOperand(1),
7542 I->getName() + ".gep");
7543 InsertNewInstBefore(GEP, EI);
7544 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007545 }
7546 }
7547 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7548 // Extracting the inserted element?
7549 if (IE->getOperand(2) == EI.getOperand(1))
7550 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7551 // If the inserted and extracted elements are constants, they must not
7552 // be the same value, extract from the pre-inserted value instead.
7553 if (isa<Constant>(IE->getOperand(2)) &&
7554 isa<Constant>(EI.getOperand(1))) {
7555 AddUsesToWorkList(EI);
7556 EI.setOperand(0, IE->getOperand(0));
7557 return &EI;
7558 }
7559 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7560 // If this is extracting an element from a shufflevector, figure out where
7561 // it came from and extract from the appropriate input element instead.
7562 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007563 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7564 Value *Src;
7565 if (SrcIdx < SVI->getType()->getNumElements())
7566 Src = SVI->getOperand(0);
7567 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7568 SrcIdx -= SVI->getType()->getNumElements();
7569 Src = SVI->getOperand(1);
7570 } else {
7571 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007572 }
Chris Lattner12249be2006-05-25 23:48:38 +00007573 return new ExtractElementInst(Src,
7574 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007575 }
7576 }
Chris Lattner83f65782006-05-25 22:53:38 +00007577 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007578 return 0;
7579}
7580
Chris Lattner90951862006-04-16 00:51:47 +00007581/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7582/// elements from either LHS or RHS, return the shuffle mask and true.
7583/// Otherwise, return false.
7584static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7585 std::vector<Constant*> &Mask) {
7586 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7587 "Invalid CollectSingleShuffleElements");
7588 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7589
7590 if (isa<UndefValue>(V)) {
7591 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7592 return true;
7593 } else if (V == LHS) {
7594 for (unsigned i = 0; i != NumElts; ++i)
7595 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7596 return true;
7597 } else if (V == RHS) {
7598 for (unsigned i = 0; i != NumElts; ++i)
7599 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7600 return true;
7601 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7602 // If this is an insert of an extract from some other vector, include it.
7603 Value *VecOp = IEI->getOperand(0);
7604 Value *ScalarOp = IEI->getOperand(1);
7605 Value *IdxOp = IEI->getOperand(2);
7606
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007607 if (!isa<ConstantInt>(IdxOp))
7608 return false;
7609 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7610
7611 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7612 // Okay, we can handle this if the vector we are insertinting into is
7613 // transitively ok.
7614 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7615 // If so, update the mask to reflect the inserted undef.
7616 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7617 return true;
7618 }
7619 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7620 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007621 EI->getOperand(0)->getType() == V->getType()) {
7622 unsigned ExtractedIdx =
7623 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007624
7625 // This must be extracting from either LHS or RHS.
7626 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7627 // Okay, we can handle this if the vector we are insertinting into is
7628 // transitively ok.
7629 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7630 // If so, update the mask to reflect the inserted value.
7631 if (EI->getOperand(0) == LHS) {
7632 Mask[InsertedIdx & (NumElts-1)] =
7633 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7634 } else {
7635 assert(EI->getOperand(0) == RHS);
7636 Mask[InsertedIdx & (NumElts-1)] =
7637 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7638
7639 }
7640 return true;
7641 }
7642 }
7643 }
7644 }
7645 }
7646 // TODO: Handle shufflevector here!
7647
7648 return false;
7649}
7650
7651/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7652/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7653/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007654static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007655 Value *&RHS) {
7656 assert(isa<PackedType>(V->getType()) &&
7657 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007658 "Invalid shuffle!");
7659 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7660
7661 if (isa<UndefValue>(V)) {
7662 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7663 return V;
7664 } else if (isa<ConstantAggregateZero>(V)) {
7665 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7666 return V;
7667 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7668 // If this is an insert of an extract from some other vector, include it.
7669 Value *VecOp = IEI->getOperand(0);
7670 Value *ScalarOp = IEI->getOperand(1);
7671 Value *IdxOp = IEI->getOperand(2);
7672
7673 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7674 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7675 EI->getOperand(0)->getType() == V->getType()) {
7676 unsigned ExtractedIdx =
7677 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7678 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7679
7680 // Either the extracted from or inserted into vector must be RHSVec,
7681 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007682 if (EI->getOperand(0) == RHS || RHS == 0) {
7683 RHS = EI->getOperand(0);
7684 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007685 Mask[InsertedIdx & (NumElts-1)] =
7686 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7687 return V;
7688 }
7689
Chris Lattner90951862006-04-16 00:51:47 +00007690 if (VecOp == RHS) {
7691 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007692 // Everything but the extracted element is replaced with the RHS.
7693 for (unsigned i = 0; i != NumElts; ++i) {
7694 if (i != InsertedIdx)
7695 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7696 }
7697 return V;
7698 }
Chris Lattner90951862006-04-16 00:51:47 +00007699
7700 // If this insertelement is a chain that comes from exactly these two
7701 // vectors, return the vector and the effective shuffle.
7702 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7703 return EI->getOperand(0);
7704
Chris Lattner39fac442006-04-15 01:39:45 +00007705 }
7706 }
7707 }
Chris Lattner90951862006-04-16 00:51:47 +00007708 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007709
7710 // Otherwise, can't do anything fancy. Return an identity vector.
7711 for (unsigned i = 0; i != NumElts; ++i)
7712 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7713 return V;
7714}
7715
7716Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7717 Value *VecOp = IE.getOperand(0);
7718 Value *ScalarOp = IE.getOperand(1);
7719 Value *IdxOp = IE.getOperand(2);
7720
7721 // If the inserted element was extracted from some other vector, and if the
7722 // indexes are constant, try to turn this into a shufflevector operation.
7723 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7724 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7725 EI->getOperand(0)->getType() == IE.getType()) {
7726 unsigned NumVectorElts = IE.getType()->getNumElements();
7727 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7728 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7729
7730 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7731 return ReplaceInstUsesWith(IE, VecOp);
7732
7733 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7734 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7735
7736 // If we are extracting a value from a vector, then inserting it right
7737 // back into the same place, just use the input vector.
7738 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7739 return ReplaceInstUsesWith(IE, VecOp);
7740
7741 // We could theoretically do this for ANY input. However, doing so could
7742 // turn chains of insertelement instructions into a chain of shufflevector
7743 // instructions, and right now we do not merge shufflevectors. As such,
7744 // only do this in a situation where it is clear that there is benefit.
7745 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7746 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7747 // the values of VecOp, except then one read from EIOp0.
7748 // Build a new shuffle mask.
7749 std::vector<Constant*> Mask;
7750 if (isa<UndefValue>(VecOp))
7751 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7752 else {
7753 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7754 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7755 NumVectorElts));
7756 }
7757 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7758 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7759 ConstantPacked::get(Mask));
7760 }
7761
7762 // If this insertelement isn't used by some other insertelement, turn it
7763 // (and any insertelements it points to), into one big shuffle.
7764 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7765 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007766 Value *RHS = 0;
7767 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7768 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7769 // We now have a shuffle of LHS, RHS, Mask.
7770 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007771 }
7772 }
7773 }
7774
7775 return 0;
7776}
7777
7778
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007779Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7780 Value *LHS = SVI.getOperand(0);
7781 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007782 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007783
7784 bool MadeChange = false;
7785
Chris Lattner12249be2006-05-25 23:48:38 +00007786 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007787 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7788
Chris Lattner39fac442006-04-15 01:39:45 +00007789 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7790 // the undef, change them to undefs.
7791
Chris Lattner12249be2006-05-25 23:48:38 +00007792 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7793 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7794 if (LHS == RHS || isa<UndefValue>(LHS)) {
7795 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007796 // shuffle(undef,undef,mask) -> undef.
7797 return ReplaceInstUsesWith(SVI, LHS);
7798 }
7799
Chris Lattner12249be2006-05-25 23:48:38 +00007800 // Remap any references to RHS to use LHS.
7801 std::vector<Constant*> Elts;
7802 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007803 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007804 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007805 else {
7806 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7807 (Mask[i] < e && isa<UndefValue>(LHS)))
7808 Mask[i] = 2*e; // Turn into undef.
7809 else
7810 Mask[i] &= (e-1); // Force to LHS.
7811 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7812 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007813 }
Chris Lattner12249be2006-05-25 23:48:38 +00007814 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007815 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007816 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007817 LHS = SVI.getOperand(0);
7818 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007819 MadeChange = true;
7820 }
7821
Chris Lattner0e477162006-05-26 00:29:06 +00007822 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007823 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007824
Chris Lattner12249be2006-05-25 23:48:38 +00007825 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7826 if (Mask[i] >= e*2) continue; // Ignore undef values.
7827 // Is this an identity shuffle of the LHS value?
7828 isLHSID &= (Mask[i] == i);
7829
7830 // Is this an identity shuffle of the RHS value?
7831 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007832 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007833
Chris Lattner12249be2006-05-25 23:48:38 +00007834 // Eliminate identity shuffles.
7835 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7836 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007837
Chris Lattner0e477162006-05-26 00:29:06 +00007838 // If the LHS is a shufflevector itself, see if we can combine it with this
7839 // one without producing an unusual shuffle. Here we are really conservative:
7840 // we are absolutely afraid of producing a shuffle mask not in the input
7841 // program, because the code gen may not be smart enough to turn a merged
7842 // shuffle into two specific shuffles: it may produce worse code. As such,
7843 // we only merge two shuffles if the result is one of the two input shuffle
7844 // masks. In this case, merging the shuffles just removes one instruction,
7845 // which we know is safe. This is good for things like turning:
7846 // (splat(splat)) -> splat.
7847 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7848 if (isa<UndefValue>(RHS)) {
7849 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7850
7851 std::vector<unsigned> NewMask;
7852 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7853 if (Mask[i] >= 2*e)
7854 NewMask.push_back(2*e);
7855 else
7856 NewMask.push_back(LHSMask[Mask[i]]);
7857
7858 // If the result mask is equal to the src shuffle or this shuffle mask, do
7859 // the replacement.
7860 if (NewMask == LHSMask || NewMask == Mask) {
7861 std::vector<Constant*> Elts;
7862 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7863 if (NewMask[i] >= e*2) {
7864 Elts.push_back(UndefValue::get(Type::UIntTy));
7865 } else {
7866 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7867 }
7868 }
7869 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7870 LHSSVI->getOperand(1),
7871 ConstantPacked::get(Elts));
7872 }
7873 }
7874 }
7875
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007876 return MadeChange ? &SVI : 0;
7877}
7878
7879
Robert Bocchinoa8352962006-01-13 22:48:06 +00007880
Chris Lattner99f48c62002-09-02 04:59:56 +00007881void InstCombiner::removeFromWorkList(Instruction *I) {
7882 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7883 WorkList.end());
7884}
7885
Chris Lattner39c98bb2004-12-08 23:43:58 +00007886
7887/// TryToSinkInstruction - Try to move the specified instruction from its
7888/// current block into the beginning of DestBlock, which can only happen if it's
7889/// safe to move the instruction past all of the instructions between it and the
7890/// end of its block.
7891static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7892 assert(I->hasOneUse() && "Invariants didn't hold!");
7893
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007894 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7895 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007896
Chris Lattner39c98bb2004-12-08 23:43:58 +00007897 // Do not sink alloca instructions out of the entry block.
7898 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7899 return false;
7900
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007901 // We can only sink load instructions if there is nothing between the load and
7902 // the end of block that could change the value.
7903 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007904 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7905 Scan != E; ++Scan)
7906 if (Scan->mayWriteToMemory())
7907 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007908 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007909
7910 BasicBlock::iterator InsertPos = DestBlock->begin();
7911 while (isa<PHINode>(InsertPos)) ++InsertPos;
7912
Chris Lattner9f269e42005-08-08 19:11:57 +00007913 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007914 ++NumSunkInst;
7915 return true;
7916}
7917
Chris Lattner1443bc52006-05-11 17:11:52 +00007918/// OptimizeConstantExpr - Given a constant expression and target data layout
7919/// information, symbolically evaluation the constant expr to something simpler
7920/// if possible.
7921static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7922 if (!TD) return CE;
7923
7924 Constant *Ptr = CE->getOperand(0);
7925 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7926 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7927 // If this is a constant expr gep that is effectively computing an
7928 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7929 bool isFoldableGEP = true;
7930 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7931 if (!isa<ConstantInt>(CE->getOperand(i)))
7932 isFoldableGEP = false;
7933 if (isFoldableGEP) {
7934 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7935 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7936 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7937 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7938 return ConstantExpr::getCast(C, CE->getType());
7939 }
7940 }
7941
7942 return CE;
7943}
7944
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007945
7946/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7947/// all reachable code to the worklist.
7948///
7949/// This has a couple of tricks to make the code faster and more powerful. In
7950/// particular, we constant fold and DCE instructions as we go, to avoid adding
7951/// them to the worklist (this significantly speeds up instcombine on code where
7952/// many instructions are dead or constant). Additionally, if we find a branch
7953/// whose condition is a known constant, we only visit the reachable successors.
7954///
7955static void AddReachableCodeToWorklist(BasicBlock *BB,
7956 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007957 std::vector<Instruction*> &WorkList,
7958 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007959 // We have now visited this block! If we've already been here, bail out.
7960 if (!Visited.insert(BB).second) return;
7961
7962 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7963 Instruction *Inst = BBI++;
7964
7965 // DCE instruction if trivially dead.
7966 if (isInstructionTriviallyDead(Inst)) {
7967 ++NumDeadInst;
7968 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7969 Inst->eraseFromParent();
7970 continue;
7971 }
7972
7973 // ConstantProp instruction if trivially constant.
7974 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007975 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7976 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007977 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7978 Inst->replaceAllUsesWith(C);
7979 ++NumConstProp;
7980 Inst->eraseFromParent();
7981 continue;
7982 }
7983
7984 WorkList.push_back(Inst);
7985 }
7986
7987 // Recursively visit successors. If this is a branch or switch on a constant,
7988 // only visit the reachable successor.
7989 TerminatorInst *TI = BB->getTerminator();
7990 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7991 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7992 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007993 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7994 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007995 return;
7996 }
7997 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7998 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7999 // See if this is an explicit destination.
8000 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8001 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008002 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008003 return;
8004 }
8005
8006 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008007 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008008 return;
8009 }
8010 }
8011
8012 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008013 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008014}
8015
Chris Lattner113f4f42002-06-25 16:13:24 +00008016bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008017 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008018 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008019
Chris Lattner4ed40f72005-07-07 20:40:38 +00008020 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008021 // Do a depth-first traversal of the function, populate the worklist with
8022 // the reachable instructions. Ignore blocks that are not reachable. Keep
8023 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008024 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008025 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008026
Chris Lattner4ed40f72005-07-07 20:40:38 +00008027 // Do a quick scan over the function. If we find any blocks that are
8028 // unreachable, remove any instructions inside of them. This prevents
8029 // the instcombine code from having to deal with some bad special cases.
8030 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8031 if (!Visited.count(BB)) {
8032 Instruction *Term = BB->getTerminator();
8033 while (Term != BB->begin()) { // Remove instrs bottom-up
8034 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008035
Chris Lattner4ed40f72005-07-07 20:40:38 +00008036 DEBUG(std::cerr << "IC: DCE: " << *I);
8037 ++NumDeadInst;
8038
8039 if (!I->use_empty())
8040 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8041 I->eraseFromParent();
8042 }
8043 }
8044 }
Chris Lattnerca081252001-12-14 16:52:21 +00008045
8046 while (!WorkList.empty()) {
8047 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8048 WorkList.pop_back();
8049
Chris Lattner1443bc52006-05-11 17:11:52 +00008050 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008051 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008052 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008053 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008054 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008055 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008056
Chris Lattnercd517ff2005-01-28 19:32:01 +00008057 DEBUG(std::cerr << "IC: DCE: " << *I);
8058
8059 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008060 removeFromWorkList(I);
8061 continue;
8062 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008063
Chris Lattner1443bc52006-05-11 17:11:52 +00008064 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008065 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8067 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008068 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8069
Chris Lattner1443bc52006-05-11 17:11:52 +00008070 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008071 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008072 ReplaceInstUsesWith(*I, C);
8073
Chris Lattner99f48c62002-09-02 04:59:56 +00008074 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008075 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008076 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008077 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008078 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008079
Chris Lattner39c98bb2004-12-08 23:43:58 +00008080 // See if we can trivially sink this instruction to a successor basic block.
8081 if (I->hasOneUse()) {
8082 BasicBlock *BB = I->getParent();
8083 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8084 if (UserParent != BB) {
8085 bool UserIsSuccessor = false;
8086 // See if the user is one of our successors.
8087 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8088 if (*SI == UserParent) {
8089 UserIsSuccessor = true;
8090 break;
8091 }
8092
8093 // If the user is one of our immediate successors, and if that successor
8094 // only has us as a predecessors (we'd have to split the critical edge
8095 // otherwise), we can keep going.
8096 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8097 next(pred_begin(UserParent)) == pred_end(UserParent))
8098 // Okay, the CFG is simple enough, try to sink this instruction.
8099 Changed |= TryToSinkInstruction(I, UserParent);
8100 }
8101 }
8102
Chris Lattnerca081252001-12-14 16:52:21 +00008103 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008104 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008105 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008106 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008107 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008108 DEBUG(std::cerr << "IC: Old = " << *I
8109 << " New = " << *Result);
8110
Chris Lattner396dbfe2004-06-09 05:08:07 +00008111 // Everything uses the new instruction now.
8112 I->replaceAllUsesWith(Result);
8113
8114 // Push the new instruction and any users onto the worklist.
8115 WorkList.push_back(Result);
8116 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008117
8118 // Move the name to the new instruction first...
8119 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008120 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008121
8122 // Insert the new instruction into the basic block...
8123 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008124 BasicBlock::iterator InsertPos = I;
8125
8126 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8127 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8128 ++InsertPos;
8129
8130 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008131
Chris Lattner63d75af2004-05-01 23:27:23 +00008132 // Make sure that we reprocess all operands now that we reduced their
8133 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008134 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8135 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8136 WorkList.push_back(OpI);
8137
Chris Lattner396dbfe2004-06-09 05:08:07 +00008138 // Instructions can end up on the worklist more than once. Make sure
8139 // we do not process an instruction that has been deleted.
8140 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008141
8142 // Erase the old instruction.
8143 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008144 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008145 DEBUG(std::cerr << "IC: MOD = " << *I);
8146
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008147 // If the instruction was modified, it's possible that it is now dead.
8148 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008149 if (isInstructionTriviallyDead(I)) {
8150 // Make sure we process all operands now that we are reducing their
8151 // use counts.
8152 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8153 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8154 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008155
Chris Lattner63d75af2004-05-01 23:27:23 +00008156 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008157 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008158 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008159 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008160 } else {
8161 WorkList.push_back(Result);
8162 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008163 }
Chris Lattner053c0932002-05-14 15:24:07 +00008164 }
Chris Lattner260ab202002-04-18 17:39:14 +00008165 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008166 }
8167 }
8168
Chris Lattner260ab202002-04-18 17:39:14 +00008169 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008170}
8171
Brian Gaeke38b79e82004-07-27 17:43:21 +00008172FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008173 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008174}
Brian Gaeke960707c2003-11-11 22:41:34 +00008175