blob: 127b15ad9c56fbf06e13dac71a1fa2f36ea024c3 [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 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000110
Chris Lattner99f48c62002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000113 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000115
Chris Lattnerf12cc842002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000120 }
121
Chris Lattner69193f92004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattner260ab202002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000130 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000134 Instruction *commonDivTransforms(BinaryOperator &I);
135 Instruction *commonIDivTransforms(BinaryOperator &I);
136 Instruction *visitUDiv(BinaryOperator &I);
137 Instruction *visitSDiv(BinaryOperator &I);
138 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000139 Instruction *visitRem(BinaryOperator &I);
140 Instruction *visitAnd(BinaryOperator &I);
141 Instruction *visitOr (BinaryOperator &I);
142 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000143 Instruction *visitSetCondInst(SetCondInst &I);
144 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
145
Chris Lattner0798af32005-01-13 20:14:25 +0000146 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
147 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000148 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000149 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000150 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000151 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000152 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
153 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000154 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000155 Instruction *visitCallInst(CallInst &CI);
156 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000157 Instruction *visitPHINode(PHINode &PN);
158 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000159 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000160 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000161 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000162 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000163 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000164 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000165 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000166 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000167 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000168
169 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000170 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000171
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000173 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000174 bool transformConstExprCastCall(CallSite CS);
175
Chris Lattner69193f92004-04-05 01:30:19 +0000176 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // InsertNewInstBefore - insert an instruction New before instruction Old
178 // in the program. Add the new instruction to the worklist.
179 //
Chris Lattner623826c2004-09-28 21:48:02 +0000180 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000181 assert(New && New->getParent() == 0 &&
182 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000183 BasicBlock *BB = Old.getParent();
184 BB->getInstList().insert(&Old, New); // Insert inst
185 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000186 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 }
188
Chris Lattner7e794272004-09-24 15:21:34 +0000189 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
190 /// This also adds the cast to the worklist. Finally, this returns the
191 /// cast.
192 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
193 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000194
Chris Lattnere79d2492006-04-06 19:19:17 +0000195 if (Constant *CV = dyn_cast<Constant>(V))
196 return ConstantExpr::getCast(CV, Ty);
197
Chris Lattner7e794272004-09-24 15:21:34 +0000198 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
199 WorkList.push_back(C);
200 return C;
201 }
202
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000203 // ReplaceInstUsesWith - This method is to be used when an instruction is
204 // found to be dead, replacable with another preexisting expression. Here
205 // we add all uses of I to the worklist, replace all uses of I with the new
206 // value, then return I, so that the inst combiner will know that I was
207 // modified.
208 //
209 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000210 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000211 if (&I != V) {
212 I.replaceAllUsesWith(V);
213 return &I;
214 } else {
215 // If we are replacing the instruction with itself, this must be in a
216 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000217 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000218 return &I;
219 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000220 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000221
Chris Lattner2590e512006-02-07 06:56:34 +0000222 // UpdateValueUsesWith - This method is to be used when an value is
223 // found to be replacable with another preexisting expression or was
224 // updated. Here we add all uses of I to the worklist, replace all uses of
225 // I with the new value (unless the instruction was just updated), then
226 // return true, so that the inst combiner will know that I was modified.
227 //
228 bool UpdateValueUsesWith(Value *Old, Value *New) {
229 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
230 if (Old != New)
231 Old->replaceAllUsesWith(New);
232 if (Instruction *I = dyn_cast<Instruction>(Old))
233 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000234 if (Instruction *I = dyn_cast<Instruction>(New))
235 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000236 return true;
237 }
238
Chris Lattner51ea1272004-02-28 05:22:00 +0000239 // EraseInstFromFunction - When dealing with an instruction that has side
240 // effects or produces a void value, we can't rely on DCE to delete the
241 // instruction. Instead, visit methods should return the value returned by
242 // this function.
243 Instruction *EraseInstFromFunction(Instruction &I) {
244 assert(I.use_empty() && "Cannot erase instruction that is used!");
245 AddUsesToWorkList(I);
246 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000247 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000248 return 0; // Don't do anything with FI
249 }
250
Chris Lattner3ac7c262003-08-13 20:16:26 +0000251 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000252 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
253 /// InsertBefore instruction. This is specialized a bit to avoid inserting
254 /// casts that are known to not do anything...
255 ///
256 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
257 Instruction *InsertBefore);
258
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000260 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000262
Chris Lattner0157e7f2006-02-11 09:31:47 +0000263 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
264 uint64_t &KnownZero, uint64_t &KnownOne,
265 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000266
Chris Lattner2deeaea2006-10-05 06:55:50 +0000267 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
268 uint64_t &UndefElts, unsigned Depth = 0);
269
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
271 // PHI node as operand #0, see if we can fold the instruction into the PHI
272 // (which is only possible if all operands to the PHI are constants).
273 Instruction *FoldOpIntoPhi(Instruction &I);
274
Chris Lattner7515cab2004-11-14 19:13:23 +0000275 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
276 // operator and they all are only used by the PHI, PHI together their
277 // inputs, and do the operation once, to the result of the PHI.
278 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
279
Chris Lattnerba1cb382003-09-19 17:17:26 +0000280 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
281 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000282
283 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
284 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000285 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
286 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000287 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000288 Instruction *MatchBSwap(BinaryOperator &I);
289
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000290 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000291 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000292
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000293 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000294}
295
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000296// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000297// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000298static unsigned getComplexity(Value *V) {
299 if (isa<Instruction>(V)) {
300 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000301 return 3;
302 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000303 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000304 if (isa<Argument>(V)) return 3;
305 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306}
Chris Lattner260ab202002-04-18 17:39:14 +0000307
Chris Lattner7fb29e12003-03-11 00:12:48 +0000308// isOnlyUse - Return true if this instruction will be deleted if we stop using
309// it.
310static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000311 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000312}
313
Chris Lattnere79e8542004-02-23 06:38:22 +0000314// getPromotedType - Return the specified type promoted as it would be to pass
315// though a va_arg area...
316static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000317 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000318 case Type::SByteTyID:
319 case Type::ShortTyID: return Type::IntTy;
320 case Type::UByteTyID:
321 case Type::UShortTyID: return Type::UIntTy;
322 case Type::FloatTyID: return Type::DoubleTy;
323 default: return Ty;
324 }
325}
326
Chris Lattner567b81f2005-09-13 00:40:14 +0000327/// isCast - If the specified operand is a CastInst or a constant expr cast,
328/// return the operand value, otherwise return null.
329static Value *isCast(Value *V) {
330 if (CastInst *I = dyn_cast<CastInst>(V))
331 return I->getOperand(0);
332 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
333 if (CE->getOpcode() == Instruction::Cast)
334 return CE->getOperand(0);
335 return 0;
336}
337
Chris Lattner1d441ad2006-05-06 09:00:16 +0000338enum CastType {
339 Noop = 0,
340 Truncate = 1,
341 Signext = 2,
342 Zeroext = 3
343};
344
345/// getCastType - In the future, we will split the cast instruction into these
346/// various types. Until then, we have to do the analysis here.
347static CastType getCastType(const Type *Src, const Type *Dest) {
348 assert(Src->isIntegral() && Dest->isIntegral() &&
349 "Only works on integral types!");
350 unsigned SrcSize = Src->getPrimitiveSizeInBits();
351 unsigned DestSize = Dest->getPrimitiveSizeInBits();
352
353 if (SrcSize == DestSize) return Noop;
354 if (SrcSize > DestSize) return Truncate;
355 if (Src->isSigned()) return Signext;
356 return Zeroext;
357}
358
359
360// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
361// instruction.
362//
363static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
364 const Type *DstTy, TargetData *TD) {
365
366 // It is legal to eliminate the instruction if casting A->B->A if the sizes
367 // are identical and the bits don't get reinterpreted (for example
368 // int->float->int would not be allowed).
369 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
370 return true;
371
372 // If we are casting between pointer and integer types, treat pointers as
373 // integers of the appropriate size for the code below.
374 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
375 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
376 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
377
378 // Allow free casting and conversion of sizes as long as the sign doesn't
379 // change...
380 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
381 CastType FirstCast = getCastType(SrcTy, MidTy);
382 CastType SecondCast = getCastType(MidTy, DstTy);
383
384 // Capture the effect of these two casts. If the result is a legal cast,
385 // the CastType is stored here, otherwise a special code is used.
386 static const unsigned CastResult[] = {
387 // First cast is noop
388 0, 1, 2, 3,
389 // First cast is a truncate
390 1, 1, 4, 4, // trunc->extend is not safe to eliminate
391 // First cast is a sign ext
392 2, 5, 2, 4, // signext->zeroext never ok
393 // First cast is a zero ext
394 3, 5, 3, 3,
395 };
396
397 unsigned Result = CastResult[FirstCast*4+SecondCast];
398 switch (Result) {
399 default: assert(0 && "Illegal table value!");
400 case 0:
401 case 1:
402 case 2:
403 case 3:
404 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
405 // truncates, we could eliminate more casts.
406 return (unsigned)getCastType(SrcTy, DstTy) == Result;
407 case 4:
408 return false; // Not possible to eliminate this here.
409 case 5:
410 // Sign or zero extend followed by truncate is always ok if the result
411 // is a truncate or noop.
412 CastType ResultCast = getCastType(SrcTy, DstTy);
413 if (ResultCast == Noop || ResultCast == Truncate)
414 return true;
415 // Otherwise we are still growing the value, we are only safe if the
416 // result will match the sign/zeroextendness of the result.
417 return ResultCast == FirstCast;
418 }
419 }
420
421 // If this is a cast from 'float -> double -> integer', cast from
422 // 'float -> integer' directly, as the value isn't changed by the
423 // float->double conversion.
424 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
425 DstTy->isIntegral() &&
426 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
427 return true;
428
429 // Packed type conversions don't modify bits.
430 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
431 return true;
432
433 return false;
434}
435
436/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
437/// in any code being generated. It does not require codegen if V is simple
438/// enough or if the cast can be folded into other casts.
439static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
440 if (V->getType() == Ty || isa<Constant>(V)) return false;
441
442 // If this is a noop cast, it isn't real codegen.
443 if (V->getType()->isLosslesslyConvertibleTo(Ty))
444 return false;
445
Chris Lattner99155be2006-05-25 23:24:33 +0000446 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447 if (const CastInst *CI = dyn_cast<CastInst>(V))
448 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
449 TD))
450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
458Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
459 Instruction *InsertBefore) {
460 if (V->getType() == DestTy) return V;
461 if (Constant *C = dyn_cast<Constant>(V))
462 return ConstantExpr::getCast(C, DestTy);
463
Reid Spencer00c482b2006-10-26 19:19:06 +0000464 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000465}
466
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000467// SimplifyCommutative - This performs a few simplifications for commutative
468// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000469//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000470// 1. Order operands such that they are listed from right (least complex) to
471// left (most complex). This puts constants before unary operators before
472// binary operators.
473//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000474// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
475// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000476//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000478 bool Changed = false;
479 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
480 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000481
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482 if (!I.isAssociative()) return Changed;
483 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000484 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
485 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
486 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000487 Constant *Folded = ConstantExpr::get(I.getOpcode(),
488 cast<Constant>(I.getOperand(1)),
489 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 I.setOperand(0, Op->getOperand(0));
491 I.setOperand(1, Folded);
492 return true;
493 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
494 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
495 isOnlyUse(Op) && isOnlyUse(Op1)) {
496 Constant *C1 = cast<Constant>(Op->getOperand(1));
497 Constant *C2 = cast<Constant>(Op1->getOperand(1));
498
499 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000500 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000501 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
502 Op1->getOperand(0),
503 Op1->getName(), &I);
504 WorkList.push_back(New);
505 I.setOperand(0, New);
506 I.setOperand(1, Folded);
507 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000508 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000509 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000510 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000511}
Chris Lattnerca081252001-12-14 16:52:21 +0000512
Chris Lattnerbb74e222003-03-10 23:06:50 +0000513// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
514// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000515//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516static inline Value *dyn_castNegVal(Value *V) {
517 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000518 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519
Chris Lattner9ad0d552004-12-14 20:08:06 +0000520 // Constants can be considered to be negated values if they can be folded.
521 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
522 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000523 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000524}
525
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526static inline Value *dyn_castNotVal(Value *V) {
527 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000528 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529
530 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000531 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000532 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000533 return 0;
534}
535
Chris Lattner7fb29e12003-03-11 00:12:48 +0000536// dyn_castFoldableMul - If this value is a multiply that can be folded into
537// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538// non-constant operand of the multiply, and set CST to point to the multiplier.
539// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000540//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000541static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000542 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000543 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000545 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000548 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 // The multiplier is really 1 << CST.
550 Constant *One = ConstantInt::get(V->getType(), 1);
551 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
552 return I->getOperand(0);
553 }
554 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000555 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000556}
Chris Lattner31ae8632002-08-14 17:51:49 +0000557
Chris Lattner0798af32005-01-13 20:14:25 +0000558/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
559/// expression, return it.
560static User *dyn_castGetElementPtr(Value *V) {
561 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
562 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
563 if (CE->getOpcode() == Instruction::GetElementPtr)
564 return cast<User>(V);
565 return false;
566}
567
Chris Lattner623826c2004-09-28 21:48:02 +0000568// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000569static ConstantInt *AddOne(ConstantInt *C) {
570 return cast<ConstantInt>(ConstantExpr::getAdd(C,
571 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000572}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000573static ConstantInt *SubOne(ConstantInt *C) {
574 return cast<ConstantInt>(ConstantExpr::getSub(C,
575 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000576}
577
Chris Lattner0157e7f2006-02-11 09:31:47 +0000578/// GetConstantInType - Return a ConstantInt with the specified type and value.
579///
Chris Lattneree0f2802006-02-12 02:07:56 +0000580static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000581 if (Ty->isUnsigned())
582 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000583 else if (Ty->getTypeID() == Type::BoolTyID)
584 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000585 int64_t SVal = Val;
586 SVal <<= 64-Ty->getPrimitiveSizeInBits();
587 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000588 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000589}
590
591
Chris Lattner4534dd592006-02-09 07:38:58 +0000592/// ComputeMaskedBits - Determine which of the bits specified in Mask are
593/// known to be either zero or one and return them in the KnownZero/KnownOne
594/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
595/// processing.
596static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
597 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000598 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
599 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000600 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000601 // optimized based on the contradictory assumption that it is non-zero.
602 // Because instcombine aggressively folds operations with undef args anyway,
603 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000604 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
605 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000606 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000607 KnownZero = ~KnownOne & Mask;
608 return;
609 }
610
611 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000612 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000613 return; // Limit search depth.
614
615 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000616 Instruction *I = dyn_cast<Instruction>(V);
617 if (!I) return;
618
Chris Lattnerfb296922006-05-04 17:33:35 +0000619 Mask &= V->getType()->getIntegralTypeMask();
620
Chris Lattner0157e7f2006-02-11 09:31:47 +0000621 switch (I->getOpcode()) {
622 case Instruction::And:
623 // If either the LHS or the RHS are Zero, the result is zero.
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 Mask &= ~KnownZero;
626 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629
630 // Output known-1 bits are only known if set in both the LHS & RHS.
631 KnownOne &= KnownOne2;
632 // Output known-0 are known to be clear if zero in either the LHS | RHS.
633 KnownZero |= KnownZero2;
634 return;
635 case Instruction::Or:
636 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
637 Mask &= ~KnownOne;
638 ComputeMaskedBits(I->getOperand(0), 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 // Output known-0 bits are only known if clear in both the LHS & RHS.
643 KnownZero &= KnownZero2;
644 // Output known-1 are known to be set if set in either the LHS | RHS.
645 KnownOne |= KnownOne2;
646 return;
647 case Instruction::Xor: {
648 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
652
653 // Output known-0 bits are known if clear or set in both the LHS & RHS.
654 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
655 // Output known-1 are known to be set if set in only one of the LHS, RHS.
656 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
657 KnownZero = KnownZeroOut;
658 return;
659 }
660 case Instruction::Select:
661 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
662 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
665
666 // Only known if known in both the LHS and RHS.
667 KnownOne &= KnownOne2;
668 KnownZero &= KnownZero2;
669 return;
670 case Instruction::Cast: {
671 const Type *SrcTy = I->getOperand(0)->getType();
672 if (!SrcTy->isIntegral()) return;
673
674 // If this is an integer truncate or noop, just look in the input.
675 if (SrcTy->getPrimitiveSizeInBits() >=
676 I->getType()->getPrimitiveSizeInBits()) {
677 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000678 return;
679 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000680
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 // Sign or Zero extension. Compute the bits in the result that are not
682 // present in the input.
683 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
684 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000685
Chris Lattner0157e7f2006-02-11 09:31:47 +0000686 // Handle zero extension.
687 if (!SrcTy->isSigned()) {
688 Mask &= SrcTy->getIntegralTypeMask();
689 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
691 // The top bits are known to be zero.
692 KnownZero |= NewBits;
693 } else {
694 // Sign extension.
695 Mask &= SrcTy->getIntegralTypeMask();
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000698
Chris Lattner0157e7f2006-02-11 09:31:47 +0000699 // If the sign bit of the input is known set or clear, then we know the
700 // top bits of the result.
701 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
702 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000703 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000704 KnownOne &= ~NewBits;
705 } else if (KnownOne & InSignBit) { // Input sign bit known set
706 KnownOne |= NewBits;
707 KnownZero &= ~NewBits;
708 } else { // Input sign bit unknown
709 KnownZero &= ~NewBits;
710 KnownOne &= ~NewBits;
711 }
712 }
713 return;
714 }
715 case Instruction::Shl:
716 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000717 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
718 uint64_t ShiftAmt = SA->getZExtValue();
719 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000722 KnownZero <<= ShiftAmt;
723 KnownOne <<= ShiftAmt;
724 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000725 return;
726 }
727 break;
728 case Instruction::Shr:
729 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000730 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000731 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000732 uint64_t ShiftAmt = SA->getZExtValue();
733 uint64_t HighBits = (1ULL << ShiftAmt)-1;
734 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000735
736 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000737 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000738 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
739 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000740 KnownZero >>= ShiftAmt;
741 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000742 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000743 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000744 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000745 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
746 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000747 KnownZero >>= ShiftAmt;
748 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000749
750 // Handle the sign bits.
751 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000752 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000753
754 if (KnownZero & SignBit) { // New bits are known zero.
755 KnownZero |= HighBits;
756 } else if (KnownOne & SignBit) { // New bits are known one.
757 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000758 }
759 }
760 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000761 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000762 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000763 }
Chris Lattner92a68652006-02-07 08:05:22 +0000764}
765
766/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
767/// this predicate to simplify operations downstream. Mask is known to be zero
768/// for bits that V cannot have.
769static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000770 uint64_t KnownZero, KnownOne;
771 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
772 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
773 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000774}
775
Chris Lattner0157e7f2006-02-11 09:31:47 +0000776/// ShrinkDemandedConstant - Check to see if the specified operand of the
777/// specified instruction is a constant integer. If so, check to see if there
778/// are any bits set in the constant that are not demanded. If so, shrink the
779/// constant and return true.
780static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
781 uint64_t Demanded) {
782 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
783 if (!OpC) return false;
784
785 // If there are no bits set that aren't demanded, nothing to do.
786 if ((~Demanded & OpC->getZExtValue()) == 0)
787 return false;
788
789 // This is producing any bits that are not needed, shrink the RHS.
790 uint64_t Val = Demanded & OpC->getZExtValue();
791 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
792 return true;
793}
794
Chris Lattneree0f2802006-02-12 02:07:56 +0000795// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
796// set of known zero and one bits, compute the maximum and minimum values that
797// could have the specified known zero and known one bits, returning them in
798// min/max.
799static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
800 uint64_t KnownZero,
801 uint64_t KnownOne,
802 int64_t &Min, int64_t &Max) {
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
807
808 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
809 // bit if it is unknown.
810 Min = KnownOne;
811 Max = KnownOne|UnknownBits;
812
813 if (SignBit & UnknownBits) { // Sign bit is unknown
814 Min |= SignBit;
815 Max &= ~SignBit;
816 }
817
818 // Sign extend the min/max values.
819 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
820 Min = (Min << ShAmt) >> ShAmt;
821 Max = (Max << ShAmt) >> ShAmt;
822}
823
824// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
825// a set of known zero and one bits, compute the maximum and minimum values that
826// could have the specified known zero and known one bits, returning them in
827// min/max.
828static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
829 uint64_t KnownZero,
830 uint64_t KnownOne,
831 uint64_t &Min,
832 uint64_t &Max) {
833 uint64_t TypeBits = Ty->getIntegralTypeMask();
834 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
835
836 // The minimum value is when the unknown bits are all zeros.
837 Min = KnownOne;
838 // The maximum value is when the unknown bits are all ones.
839 Max = KnownOne|UnknownBits;
840}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841
842
843/// SimplifyDemandedBits - Look at V. At this point, we know that only the
844/// DemandedMask bits of the result of V are ever used downstream. If we can
845/// use this information to simplify V, do so and return true. Otherwise,
846/// analyze the expression and return a mask of KnownOne and KnownZero bits for
847/// the expression (used to simplify the caller). The KnownZero/One bits may
848/// only be accurate for those bits in the DemandedMask.
849bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
850 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000851 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000852 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
853 // We know all of the bits for a constant!
854 KnownOne = CI->getZExtValue() & DemandedMask;
855 KnownZero = ~KnownOne & DemandedMask;
856 return false;
857 }
858
859 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000860 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000861 if (Depth != 0) { // Not at the root.
862 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
863 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000864 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000865 }
Chris Lattner2590e512006-02-07 06:56:34 +0000866 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 // just set the DemandedMask to all bits.
868 DemandedMask = V->getType()->getIntegralTypeMask();
869 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000870 if (V != UndefValue::get(V->getType()))
871 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
872 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000873 } else if (Depth == 6) { // Limit search depth.
874 return false;
875 }
876
877 Instruction *I = dyn_cast<Instruction>(V);
878 if (!I) return false; // Only analyze instructions.
879
Chris Lattnerfb296922006-05-04 17:33:35 +0000880 DemandedMask &= V->getType()->getIntegralTypeMask();
881
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000883 switch (I->getOpcode()) {
884 default: break;
885 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 // If either the LHS or the RHS are Zero, the result is zero.
887 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
888 KnownZero, KnownOne, Depth+1))
889 return true;
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
891
892 // If something is known zero on the RHS, the bits aren't demanded on the
893 // LHS.
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
895 KnownZero2, KnownOne2, Depth+1))
896 return true;
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
898
899 // If all of the demanded bits are known one on one side, return the other.
900 // These bits cannot contribute to the result of the 'and'.
901 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
902 return UpdateValueUsesWith(I, I->getOperand(0));
903 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
904 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000905
906 // If all of the demanded bits in the inputs are known zeros, return zero.
907 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
908 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
909
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000911 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 return UpdateValueUsesWith(I, I);
913
914 // Output known-1 bits are only known if set in both the LHS & RHS.
915 KnownOne &= KnownOne2;
916 // Output known-0 are known to be clear if zero in either the LHS | RHS.
917 KnownZero |= KnownZero2;
918 break;
919 case Instruction::Or:
920 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
921 KnownZero, KnownOne, Depth+1))
922 return true;
923 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
924 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
925 KnownZero2, KnownOne2, Depth+1))
926 return true;
927 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
928
929 // If all of the demanded bits are known zero on one side, return the other.
930 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000931 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000932 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000933 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000935
936 // If all of the potentially set bits on one side are known to be set on
937 // the other side, just use the 'other' side.
938 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
939 (DemandedMask & (~KnownZero)))
940 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000941 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
942 (DemandedMask & (~KnownZero2)))
943 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000944
945 // If the RHS is a constant, see if we can simplify it.
946 if (ShrinkDemandedConstant(I, 1, DemandedMask))
947 return UpdateValueUsesWith(I, I);
948
949 // Output known-0 bits are only known if clear in both the LHS & RHS.
950 KnownZero &= KnownZero2;
951 // Output known-1 are known to be set if set in either the LHS | RHS.
952 KnownOne |= KnownOne2;
953 break;
954 case Instruction::Xor: {
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 KnownZero, KnownOne, Depth+1))
957 return true;
958 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
959 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
960 KnownZero2, KnownOne2, Depth+1))
961 return true;
962 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
963
964 // If all of the demanded bits are known zero on one side, return the other.
965 // These bits cannot contribute to the result of the 'xor'.
966 if ((DemandedMask & KnownZero) == DemandedMask)
967 return UpdateValueUsesWith(I, I->getOperand(0));
968 if ((DemandedMask & KnownZero2) == DemandedMask)
969 return UpdateValueUsesWith(I, I->getOperand(1));
970
971 // Output known-0 bits are known if clear or set in both the LHS & RHS.
972 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
973 // Output known-1 are known to be set if set in only one of the LHS, RHS.
974 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
975
976 // If all of the unknown bits are known to be zero on one side or the other
977 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000978 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000979 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
980 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
981 Instruction *Or =
982 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
983 I->getName());
984 InsertNewInstBefore(Or, *I);
985 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000986 }
987 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000988
Chris Lattner5b2edb12006-02-12 08:02:11 +0000989 // If all of the demanded bits on one side are known, and all of the set
990 // bits on that side are also known to be set on the other side, turn this
991 // into an AND, as we know the bits will be cleared.
992 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
993 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
994 if ((KnownOne & KnownOne2) == KnownOne) {
995 Constant *AndC = GetConstantInType(I->getType(),
996 ~KnownOne & DemandedMask);
997 Instruction *And =
998 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
999 InsertNewInstBefore(And, *I);
1000 return UpdateValueUsesWith(I, And);
1001 }
1002 }
1003
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004 // If the RHS is a constant, see if we can simplify it.
1005 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1006 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1007 return UpdateValueUsesWith(I, I);
1008
1009 KnownZero = KnownZeroOut;
1010 KnownOne = KnownOneOut;
1011 break;
1012 }
1013 case Instruction::Select:
1014 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1015 KnownZero, KnownOne, Depth+1))
1016 return true;
1017 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1018 KnownZero2, KnownOne2, Depth+1))
1019 return true;
1020 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1021 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1022
1023 // If the operands are constants, see if we can simplify them.
1024 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1025 return UpdateValueUsesWith(I, I);
1026 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1027 return UpdateValueUsesWith(I, I);
1028
1029 // Only known if known in both the LHS and RHS.
1030 KnownOne &= KnownOne2;
1031 KnownZero &= KnownZero2;
1032 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001033 case Instruction::Cast: {
1034 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001035 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001036
Chris Lattner0157e7f2006-02-11 09:31:47 +00001037 // If this is an integer truncate or noop, just look in the input.
1038 if (SrcTy->getPrimitiveSizeInBits() >=
1039 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001040 // Cast to bool is a comparison against 0, which demands all bits. We
1041 // can't propagate anything useful up.
1042 if (I->getType() == Type::BoolTy)
1043 break;
1044
Chris Lattner0157e7f2006-02-11 09:31:47 +00001045 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1046 KnownZero, KnownOne, Depth+1))
1047 return true;
1048 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049 break;
1050 }
1051
1052 // Sign or Zero extension. Compute the bits in the result that are not
1053 // present in the input.
1054 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1055 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1056
1057 // Handle zero extension.
1058 if (!SrcTy->isSigned()) {
1059 DemandedMask &= SrcTy->getIntegralTypeMask();
1060 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1061 KnownZero, KnownOne, Depth+1))
1062 return true;
1063 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1064 // The top bits are known to be zero.
1065 KnownZero |= NewBits;
1066 } else {
1067 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001068 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1069 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1070
1071 // If any of the sign extended bits are demanded, we know that the sign
1072 // bit is demanded.
1073 if (NewBits & DemandedMask)
1074 InputDemandedBits |= InSignBit;
1075
1076 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001077 KnownZero, KnownOne, Depth+1))
1078 return true;
1079 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1080
1081 // If the sign bit of the input is known set or clear, then we know the
1082 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001083
Chris Lattner0157e7f2006-02-11 09:31:47 +00001084 // If the input sign bit is known zero, or if the NewBits are not demanded
1085 // convert this into a zero extension.
1086 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001087 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001088 Value *NewVal =
1089 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001090 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001091 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001092 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001093 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094 } else if (KnownOne & InSignBit) { // Input sign bit known set
1095 KnownOne |= NewBits;
1096 KnownZero &= ~NewBits;
1097 } else { // Input sign bit unknown
1098 KnownZero &= ~NewBits;
1099 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001100 }
Chris Lattner2590e512006-02-07 06:56:34 +00001101 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001102 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001103 }
Chris Lattner2590e512006-02-07 06:56:34 +00001104 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001105 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1106 uint64_t ShiftAmt = SA->getZExtValue();
1107 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001108 KnownZero, KnownOne, Depth+1))
1109 return true;
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001111 KnownZero <<= ShiftAmt;
1112 KnownOne <<= ShiftAmt;
1113 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001114 }
Chris Lattner2590e512006-02-07 06:56:34 +00001115 break;
1116 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001117 // If this is an arithmetic shift right and only the low-bit is set, we can
1118 // always convert this into a logical shr, even if the shift amount is
1119 // variable. The low bit of the shift cannot be an input sign bit unless
1120 // the shift amount is >= the size of the datatype, which is undefined.
1121 if (DemandedMask == 1 && I->getType()->isSigned()) {
1122 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001123 Value *NewVal = InsertCastBefore(I->getOperand(0),
1124 I->getType()->getUnsignedVersion(), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001125 // Perform the unsigned shift right.
1126 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1127 I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001128 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001129 // Then cast that to the destination type.
1130 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001131 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001132 return UpdateValueUsesWith(I, NewVal);
1133 }
1134
Reid Spencere0fc4df2006-10-20 07:07:24 +00001135 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001137
1138 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001139 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1140 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001141 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001142 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001143 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001144 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001145 KnownZero, KnownOne, Depth+1))
1146 return true;
1147 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001148 KnownZero &= TypeMask;
1149 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001150 KnownZero >>= ShiftAmt;
1151 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001152 KnownZero |= HighBits; // high bits known zero.
1153 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001154 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001155 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001156 KnownZero, KnownOne, Depth+1))
1157 return true;
1158 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001159 KnownZero &= TypeMask;
1160 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001161 KnownZero >>= ShiftAmt;
1162 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001163
1164 // Handle the sign bits.
1165 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001166 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001167
1168 // If the input sign bit is known to be zero, or if none of the top bits
1169 // are demanded, turn this into an unsigned shift right.
1170 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1171 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001172 Value *NewVal = InsertCastBefore(I->getOperand(0),
1173 I->getType()->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001174 // Perform the unsigned shift right.
1175 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001176 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001177 // Then cast that to the destination type.
1178 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001179 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001180 return UpdateValueUsesWith(I, NewVal);
1181 } else if (KnownOne & SignBit) { // New bits are known one.
1182 KnownOne |= HighBits;
1183 }
Chris Lattner2590e512006-02-07 06:56:34 +00001184 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001185 }
Chris Lattner2590e512006-02-07 06:56:34 +00001186 break;
1187 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001188
1189 // If the client is only demanding bits that we know, return the known
1190 // constant.
1191 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1192 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001193 return false;
1194}
1195
Chris Lattner2deeaea2006-10-05 06:55:50 +00001196
1197/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1198/// 64 or fewer elements. DemandedElts contains the set of elements that are
1199/// actually used by the caller. This method analyzes which elements of the
1200/// operand are undef and returns that information in UndefElts.
1201///
1202/// If the information about demanded elements can be used to simplify the
1203/// operation, the operation is simplified, then the resultant value is
1204/// returned. This returns null if no change was made.
1205Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1206 uint64_t &UndefElts,
1207 unsigned Depth) {
1208 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1209 assert(VWidth <= 64 && "Vector too wide to analyze!");
1210 uint64_t EltMask = ~0ULL >> (64-VWidth);
1211 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1212 "Invalid DemandedElts!");
1213
1214 if (isa<UndefValue>(V)) {
1215 // If the entire vector is undefined, just return this info.
1216 UndefElts = EltMask;
1217 return 0;
1218 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1219 UndefElts = EltMask;
1220 return UndefValue::get(V->getType());
1221 }
1222
1223 UndefElts = 0;
1224 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1225 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1226 Constant *Undef = UndefValue::get(EltTy);
1227
1228 std::vector<Constant*> Elts;
1229 for (unsigned i = 0; i != VWidth; ++i)
1230 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1231 Elts.push_back(Undef);
1232 UndefElts |= (1ULL << i);
1233 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1234 Elts.push_back(Undef);
1235 UndefElts |= (1ULL << i);
1236 } else { // Otherwise, defined.
1237 Elts.push_back(CP->getOperand(i));
1238 }
1239
1240 // If we changed the constant, return it.
1241 Constant *NewCP = ConstantPacked::get(Elts);
1242 return NewCP != CP ? NewCP : 0;
1243 } else if (isa<ConstantAggregateZero>(V)) {
1244 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1245 // set to undef.
1246 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1247 Constant *Zero = Constant::getNullValue(EltTy);
1248 Constant *Undef = UndefValue::get(EltTy);
1249 std::vector<Constant*> Elts;
1250 for (unsigned i = 0; i != VWidth; ++i)
1251 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1252 UndefElts = DemandedElts ^ EltMask;
1253 return ConstantPacked::get(Elts);
1254 }
1255
1256 if (!V->hasOneUse()) { // Other users may use these bits.
1257 if (Depth != 0) { // Not at the root.
1258 // TODO: Just compute the UndefElts information recursively.
1259 return false;
1260 }
1261 return false;
1262 } else if (Depth == 10) { // Limit search depth.
1263 return false;
1264 }
1265
1266 Instruction *I = dyn_cast<Instruction>(V);
1267 if (!I) return false; // Only analyze instructions.
1268
1269 bool MadeChange = false;
1270 uint64_t UndefElts2;
1271 Value *TmpV;
1272 switch (I->getOpcode()) {
1273 default: break;
1274
1275 case Instruction::InsertElement: {
1276 // If this is a variable index, we don't know which element it overwrites.
1277 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001278 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001279 if (Idx == 0) {
1280 // Note that we can't propagate undef elt info, because we don't know
1281 // which elt is getting updated.
1282 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1283 UndefElts2, Depth+1);
1284 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1285 break;
1286 }
1287
1288 // If this is inserting an element that isn't demanded, remove this
1289 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001290 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001291 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1292 return AddSoonDeadInstToWorklist(*I, 0);
1293
1294 // Otherwise, the element inserted overwrites whatever was there, so the
1295 // input demanded set is simpler than the output set.
1296 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1297 DemandedElts & ~(1ULL << IdxNo),
1298 UndefElts, Depth+1);
1299 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1300
1301 // The inserted element is defined.
1302 UndefElts |= 1ULL << IdxNo;
1303 break;
1304 }
1305
1306 case Instruction::And:
1307 case Instruction::Or:
1308 case Instruction::Xor:
1309 case Instruction::Add:
1310 case Instruction::Sub:
1311 case Instruction::Mul:
1312 // div/rem demand all inputs, because they don't want divide by zero.
1313 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1314 UndefElts, Depth+1);
1315 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1316 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1317 UndefElts2, Depth+1);
1318 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1319
1320 // Output elements are undefined if both are undefined. Consider things
1321 // like undef&0. The result is known zero, not undef.
1322 UndefElts &= UndefElts2;
1323 break;
1324
1325 case Instruction::Call: {
1326 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1327 if (!II) break;
1328 switch (II->getIntrinsicID()) {
1329 default: break;
1330
1331 // Binary vector operations that work column-wise. A dest element is a
1332 // function of the corresponding input elements from the two inputs.
1333 case Intrinsic::x86_sse_sub_ss:
1334 case Intrinsic::x86_sse_mul_ss:
1335 case Intrinsic::x86_sse_min_ss:
1336 case Intrinsic::x86_sse_max_ss:
1337 case Intrinsic::x86_sse2_sub_sd:
1338 case Intrinsic::x86_sse2_mul_sd:
1339 case Intrinsic::x86_sse2_min_sd:
1340 case Intrinsic::x86_sse2_max_sd:
1341 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1342 UndefElts, Depth+1);
1343 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1344 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1345 UndefElts2, Depth+1);
1346 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1347
1348 // If only the low elt is demanded and this is a scalarizable intrinsic,
1349 // scalarize it now.
1350 if (DemandedElts == 1) {
1351 switch (II->getIntrinsicID()) {
1352 default: break;
1353 case Intrinsic::x86_sse_sub_ss:
1354 case Intrinsic::x86_sse_mul_ss:
1355 case Intrinsic::x86_sse2_sub_sd:
1356 case Intrinsic::x86_sse2_mul_sd:
1357 // TODO: Lower MIN/MAX/ABS/etc
1358 Value *LHS = II->getOperand(1);
1359 Value *RHS = II->getOperand(2);
1360 // Extract the element as scalars.
1361 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1362 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1363
1364 switch (II->getIntrinsicID()) {
1365 default: assert(0 && "Case stmts out of sync!");
1366 case Intrinsic::x86_sse_sub_ss:
1367 case Intrinsic::x86_sse2_sub_sd:
1368 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1369 II->getName()), *II);
1370 break;
1371 case Intrinsic::x86_sse_mul_ss:
1372 case Intrinsic::x86_sse2_mul_sd:
1373 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1374 II->getName()), *II);
1375 break;
1376 }
1377
1378 Instruction *New =
1379 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1380 II->getName());
1381 InsertNewInstBefore(New, *II);
1382 AddSoonDeadInstToWorklist(*II, 0);
1383 return New;
1384 }
1385 }
1386
1387 // Output elements are undefined if both are undefined. Consider things
1388 // like undef&0. The result is known zero, not undef.
1389 UndefElts &= UndefElts2;
1390 break;
1391 }
1392 break;
1393 }
1394 }
1395 return MadeChange ? I : 0;
1396}
1397
Chris Lattner623826c2004-09-28 21:48:02 +00001398// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1399// true when both operands are equal...
1400//
1401static bool isTrueWhenEqual(Instruction &I) {
1402 return I.getOpcode() == Instruction::SetEQ ||
1403 I.getOpcode() == Instruction::SetGE ||
1404 I.getOpcode() == Instruction::SetLE;
1405}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001406
1407/// AssociativeOpt - Perform an optimization on an associative operator. This
1408/// function is designed to check a chain of associative operators for a
1409/// potential to apply a certain optimization. Since the optimization may be
1410/// applicable if the expression was reassociated, this checks the chain, then
1411/// reassociates the expression as necessary to expose the optimization
1412/// opportunity. This makes use of a special Functor, which must define
1413/// 'shouldApply' and 'apply' methods.
1414///
1415template<typename Functor>
1416Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1417 unsigned Opcode = Root.getOpcode();
1418 Value *LHS = Root.getOperand(0);
1419
1420 // Quick check, see if the immediate LHS matches...
1421 if (F.shouldApply(LHS))
1422 return F.apply(Root);
1423
1424 // Otherwise, if the LHS is not of the same opcode as the root, return.
1425 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001426 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001427 // Should we apply this transform to the RHS?
1428 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1429
1430 // If not to the RHS, check to see if we should apply to the LHS...
1431 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1432 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1433 ShouldApply = true;
1434 }
1435
1436 // If the functor wants to apply the optimization to the RHS of LHSI,
1437 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1438 if (ShouldApply) {
1439 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001440
Chris Lattnerb8b97502003-08-13 19:01:45 +00001441 // Now all of the instructions are in the current basic block, go ahead
1442 // and perform the reassociation.
1443 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1444
1445 // First move the selected RHS to the LHS of the root...
1446 Root.setOperand(0, LHSI->getOperand(1));
1447
1448 // Make what used to be the LHS of the root be the user of the root...
1449 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001450 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001451 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1452 return 0;
1453 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001454 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001455 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001456 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1457 BasicBlock::iterator ARI = &Root; ++ARI;
1458 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1459 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001460
1461 // Now propagate the ExtraOperand down the chain of instructions until we
1462 // get to LHSI.
1463 while (TmpLHSI != LHSI) {
1464 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001465 // Move the instruction to immediately before the chain we are
1466 // constructing to avoid breaking dominance properties.
1467 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1468 BB->getInstList().insert(ARI, NextLHSI);
1469 ARI = NextLHSI;
1470
Chris Lattnerb8b97502003-08-13 19:01:45 +00001471 Value *NextOp = NextLHSI->getOperand(1);
1472 NextLHSI->setOperand(1, ExtraOperand);
1473 TmpLHSI = NextLHSI;
1474 ExtraOperand = NextOp;
1475 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001476
Chris Lattnerb8b97502003-08-13 19:01:45 +00001477 // Now that the instructions are reassociated, have the functor perform
1478 // the transformation...
1479 return F.apply(Root);
1480 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001481
Chris Lattnerb8b97502003-08-13 19:01:45 +00001482 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1483 }
1484 return 0;
1485}
1486
1487
1488// AddRHS - Implements: X + X --> X << 1
1489struct AddRHS {
1490 Value *RHS;
1491 AddRHS(Value *rhs) : RHS(rhs) {}
1492 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1493 Instruction *apply(BinaryOperator &Add) const {
1494 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1495 ConstantInt::get(Type::UByteTy, 1));
1496 }
1497};
1498
1499// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1500// iff C1&C2 == 0
1501struct AddMaskingAnd {
1502 Constant *C2;
1503 AddMaskingAnd(Constant *c) : C2(c) {}
1504 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001505 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001506 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001507 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001508 }
1509 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001510 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001511 }
1512};
1513
Chris Lattner86102b82005-01-01 16:22:27 +00001514static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001515 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001516 if (isa<CastInst>(I)) {
1517 if (Constant *SOC = dyn_cast<Constant>(SO))
1518 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001519
Chris Lattner86102b82005-01-01 16:22:27 +00001520 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1521 SO->getName() + ".cast"), I);
1522 }
1523
Chris Lattner183b3362004-04-09 19:05:30 +00001524 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001525 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1526 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001527
Chris Lattner183b3362004-04-09 19:05:30 +00001528 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1529 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001530 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1531 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001532 }
1533
1534 Value *Op0 = SO, *Op1 = ConstOperand;
1535 if (!ConstIsRHS)
1536 std::swap(Op0, Op1);
1537 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001538 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1539 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1540 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1541 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001542 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001543 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001544 abort();
1545 }
Chris Lattner86102b82005-01-01 16:22:27 +00001546 return IC->InsertNewInstBefore(New, I);
1547}
1548
1549// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1550// constant as the other operand, try to fold the binary operator into the
1551// select arguments. This also works for Cast instructions, which obviously do
1552// not have a second operand.
1553static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1554 InstCombiner *IC) {
1555 // Don't modify shared select instructions
1556 if (!SI->hasOneUse()) return 0;
1557 Value *TV = SI->getOperand(1);
1558 Value *FV = SI->getOperand(2);
1559
1560 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001561 // Bool selects with constant operands can be folded to logical ops.
1562 if (SI->getType() == Type::BoolTy) return 0;
1563
Chris Lattner86102b82005-01-01 16:22:27 +00001564 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1565 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1566
1567 return new SelectInst(SI->getCondition(), SelectTrueVal,
1568 SelectFalseVal);
1569 }
1570 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001571}
1572
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001573
1574/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1575/// node as operand #0, see if we can fold the instruction into the PHI (which
1576/// is only possible if all operands to the PHI are constants).
1577Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1578 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001579 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001580 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001581
Chris Lattner04689872006-09-09 22:02:56 +00001582 // Check to see if all of the operands of the PHI are constants. If there is
1583 // one non-constant value, remember the BB it is. If there is more than one
1584 // bail out.
1585 BasicBlock *NonConstBB = 0;
1586 for (unsigned i = 0; i != NumPHIValues; ++i)
1587 if (!isa<Constant>(PN->getIncomingValue(i))) {
1588 if (NonConstBB) return 0; // More than one non-const value.
1589 NonConstBB = PN->getIncomingBlock(i);
1590
1591 // If the incoming non-constant value is in I's block, we have an infinite
1592 // loop.
1593 if (NonConstBB == I.getParent())
1594 return 0;
1595 }
1596
1597 // If there is exactly one non-constant value, we can insert a copy of the
1598 // operation in that block. However, if this is a critical edge, we would be
1599 // inserting the computation one some other paths (e.g. inside a loop). Only
1600 // do this if the pred block is unconditionally branching into the phi block.
1601 if (NonConstBB) {
1602 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1603 if (!BI || !BI->isUnconditional()) return 0;
1604 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001605
1606 // Okay, we can do the transformation: create the new PHI node.
1607 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1608 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001609 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001610 InsertNewInstBefore(NewPN, *PN);
1611
1612 // Next, add all of the operands to the PHI.
1613 if (I.getNumOperands() == 2) {
1614 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001615 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001616 Value *InV;
1617 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1618 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1619 } else {
1620 assert(PN->getIncomingBlock(i) == NonConstBB);
1621 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1622 InV = BinaryOperator::create(BO->getOpcode(),
1623 PN->getIncomingValue(i), C, "phitmp",
1624 NonConstBB->getTerminator());
1625 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1626 InV = new ShiftInst(SI->getOpcode(),
1627 PN->getIncomingValue(i), C, "phitmp",
1628 NonConstBB->getTerminator());
1629 else
1630 assert(0 && "Unknown binop!");
1631
1632 WorkList.push_back(cast<Instruction>(InV));
1633 }
1634 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001635 }
1636 } else {
1637 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1638 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001639 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001640 Value *InV;
1641 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1642 InV = ConstantExpr::getCast(InC, RetTy);
1643 } else {
1644 assert(PN->getIncomingBlock(i) == NonConstBB);
1645 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1646 NonConstBB->getTerminator());
1647 WorkList.push_back(cast<Instruction>(InV));
1648 }
1649 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001650 }
1651 }
1652 return ReplaceInstUsesWith(I, NewPN);
1653}
1654
Chris Lattner113f4f42002-06-25 16:13:24 +00001655Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001656 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001657 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001658
Chris Lattnercf4a9962004-04-10 22:01:55 +00001659 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001660 // X + undef -> undef
1661 if (isa<UndefValue>(RHS))
1662 return ReplaceInstUsesWith(I, RHS);
1663
Chris Lattnercf4a9962004-04-10 22:01:55 +00001664 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001665 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1666 if (RHSC->isNullValue())
1667 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001668 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1669 if (CFP->isExactlyValue(-0.0))
1670 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001671 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001672
Chris Lattnercf4a9962004-04-10 22:01:55 +00001673 // X + (signbit) --> X ^ signbit
1674 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001675 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001676 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001677 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001678 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001679
1680 if (isa<PHINode>(LHS))
1681 if (Instruction *NV = FoldOpIntoPhi(I))
1682 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001683
Chris Lattner330628a2006-01-06 17:59:59 +00001684 ConstantInt *XorRHS = 0;
1685 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001686 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1687 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1688 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1689 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1690
1691 uint64_t C0080Val = 1ULL << 31;
1692 int64_t CFF80Val = -C0080Val;
1693 unsigned Size = 32;
1694 do {
1695 if (TySizeBits > Size) {
1696 bool Found = false;
1697 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1698 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1699 if (RHSSExt == CFF80Val) {
1700 if (XorRHS->getZExtValue() == C0080Val)
1701 Found = true;
1702 } else if (RHSZExt == C0080Val) {
1703 if (XorRHS->getSExtValue() == CFF80Val)
1704 Found = true;
1705 }
1706 if (Found) {
1707 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001708 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001709 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001710 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001711 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001712 Size = 0; // Not a sign ext, but can't be any others either.
1713 goto FoundSExt;
1714 }
1715 }
1716 Size >>= 1;
1717 C0080Val >>= Size;
1718 CFF80Val >>= Size;
1719 } while (Size >= 8);
1720
1721FoundSExt:
1722 const Type *MiddleType = 0;
1723 switch (Size) {
1724 default: break;
1725 case 32: MiddleType = Type::IntTy; break;
1726 case 16: MiddleType = Type::ShortTy; break;
1727 case 8: MiddleType = Type::SByteTy; break;
1728 }
1729 if (MiddleType) {
1730 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1731 InsertNewInstBefore(NewTrunc, I);
1732 return new CastInst(NewTrunc, I.getType());
1733 }
1734 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001735 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001736
Chris Lattnerb8b97502003-08-13 19:01:45 +00001737 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001738 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001739 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001740
1741 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1742 if (RHSI->getOpcode() == Instruction::Sub)
1743 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1744 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1745 }
1746 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1747 if (LHSI->getOpcode() == Instruction::Sub)
1748 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1749 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1750 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001751 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001752
Chris Lattner147e9752002-05-08 22:46:53 +00001753 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001754 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001755 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001756
1757 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001758 if (!isa<Constant>(RHS))
1759 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001760 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001761
Misha Brukmanb1c93172005-04-21 23:48:37 +00001762
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001763 ConstantInt *C2;
1764 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1765 if (X == RHS) // X*C + X --> X * (C+1)
1766 return BinaryOperator::createMul(RHS, AddOne(C2));
1767
1768 // X*C1 + X*C2 --> X * (C1+C2)
1769 ConstantInt *C1;
1770 if (X == dyn_castFoldableMul(RHS, C1))
1771 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001772 }
1773
1774 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001775 if (dyn_castFoldableMul(RHS, C2) == LHS)
1776 return BinaryOperator::createMul(LHS, AddOne(C2));
1777
Chris Lattner57c8d992003-02-18 19:57:07 +00001778
Chris Lattnerb8b97502003-08-13 19:01:45 +00001779 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001780 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001781 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001782
Chris Lattnerb9cde762003-10-02 15:11:26 +00001783 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001784 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001785 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1786 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1787 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001788 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001789
Chris Lattnerbff91d92004-10-08 05:07:56 +00001790 // (X & FF00) + xx00 -> (X+xx00) & FF00
1791 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1792 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1793 if (Anded == CRHS) {
1794 // See if all bits from the first bit set in the Add RHS up are included
1795 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001796 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001797
1798 // Form a mask of all bits from the lowest bit added through the top.
1799 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001800 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001801
1802 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001803 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001804
Chris Lattnerbff91d92004-10-08 05:07:56 +00001805 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1806 // Okay, the xform is safe. Insert the new add pronto.
1807 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1808 LHS->getName()), I);
1809 return BinaryOperator::createAnd(NewAdd, C2);
1810 }
1811 }
1812 }
1813
Chris Lattnerd4252a72004-07-30 07:50:03 +00001814 // Try to fold constant add into select arguments.
1815 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001816 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001817 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001818 }
1819
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001820 // add (cast *A to intptrtype) B ->
1821 // cast (GEP (cast *A to sbyte*) B) ->
1822 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001823 {
1824 CastInst* CI = dyn_cast<CastInst>(LHS);
1825 Value* Other = RHS;
1826 if (!CI) {
1827 CI = dyn_cast<CastInst>(RHS);
1828 Other = LHS;
1829 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001830 if (CI && CI->getType()->isSized() &&
1831 (CI->getType()->getPrimitiveSize() ==
1832 TD->getIntPtrType()->getPrimitiveSize())
1833 && isa<PointerType>(CI->getOperand(0)->getType())) {
1834 Value* I2 = InsertCastBefore(CI->getOperand(0),
1835 PointerType::get(Type::SByteTy), I);
1836 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1837 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001838 }
1839 }
1840
Chris Lattner113f4f42002-06-25 16:13:24 +00001841 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001842}
1843
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001844// isSignBit - Return true if the value represented by the constant only has the
1845// highest order bit set.
1846static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001847 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001848 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001849}
1850
Chris Lattner022167f2004-03-13 00:11:49 +00001851/// RemoveNoopCast - Strip off nonconverting casts from the value.
1852///
1853static Value *RemoveNoopCast(Value *V) {
1854 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1855 const Type *CTy = CI->getType();
1856 const Type *OpTy = CI->getOperand(0)->getType();
1857 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001858 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001859 return RemoveNoopCast(CI->getOperand(0));
1860 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1861 return RemoveNoopCast(CI->getOperand(0));
1862 }
1863 return V;
1864}
1865
Chris Lattner113f4f42002-06-25 16:13:24 +00001866Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001868
Chris Lattnere6794492002-08-12 21:17:25 +00001869 if (Op0 == Op1) // sub X, X -> 0
1870 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001871
Chris Lattnere6794492002-08-12 21:17:25 +00001872 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001873 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001874 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001875
Chris Lattner81a7a232004-10-16 18:11:37 +00001876 if (isa<UndefValue>(Op0))
1877 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1878 if (isa<UndefValue>(Op1))
1879 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1880
Chris Lattner8f2f5982003-11-05 01:06:05 +00001881 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1882 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001883 if (C->isAllOnesValue())
1884 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001885
Chris Lattner8f2f5982003-11-05 01:06:05 +00001886 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001887 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001888 if (match(Op1, m_Not(m_Value(X))))
1889 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001890 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001891 // -((uint)X >> 31) -> ((int)X >> 31)
1892 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001893 if (C->isNullValue()) {
1894 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1895 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001896 if (SI->getOpcode() == Instruction::Shr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001897 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001898 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001899 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001900 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001901 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001902 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001903 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001904 if (CU->getZExtValue() ==
1905 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001906 // Ok, the transformation is safe. Insert a cast of the incoming
1907 // value, then the new shift, then the new cast.
Reid Spencer00c482b2006-10-26 19:19:06 +00001908 Value *InV = InsertCastBefore(SI->getOperand(0), NewTy, I);
1909 Instruction *NewShift = new ShiftInst(Instruction::Shr, InV,
Chris Lattner92295c52004-03-12 23:53:13 +00001910 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001911 if (NewShift->getType() == I.getType())
1912 return NewShift;
1913 else {
Reid Spencer00c482b2006-10-26 19:19:06 +00001914 InsertNewInstBefore(NewShift, I);
Chris Lattner022167f2004-03-13 00:11:49 +00001915 return new CastInst(NewShift, I.getType());
1916 }
Chris Lattner92295c52004-03-12 23:53:13 +00001917 }
1918 }
Chris Lattner022167f2004-03-13 00:11:49 +00001919 }
Chris Lattner183b3362004-04-09 19:05:30 +00001920
1921 // Try to fold constant sub into select arguments.
1922 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001923 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001924 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001925
1926 if (isa<PHINode>(Op0))
1927 if (Instruction *NV = FoldOpIntoPhi(I))
1928 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001929 }
1930
Chris Lattnera9be4492005-04-07 16:15:25 +00001931 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1932 if (Op1I->getOpcode() == Instruction::Add &&
1933 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001934 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001935 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001936 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001937 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001938 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1939 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1940 // C1-(X+C2) --> (C1-C2)-X
1941 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1942 Op1I->getOperand(0));
1943 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001944 }
1945
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001946 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001947 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1948 // is not used by anyone else...
1949 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001950 if (Op1I->getOpcode() == Instruction::Sub &&
1951 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001952 // Swap the two operands of the subexpr...
1953 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1954 Op1I->setOperand(0, IIOp1);
1955 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001956
Chris Lattner3082c5a2003-02-18 19:28:33 +00001957 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001958 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001959 }
1960
1961 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1962 //
1963 if (Op1I->getOpcode() == Instruction::And &&
1964 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1965 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1966
Chris Lattner396dbfe2004-06-09 05:08:07 +00001967 Value *NewNot =
1968 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001969 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001970 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001971
Reid Spencer3c514952006-10-16 23:08:08 +00001972 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001973 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001974 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001975 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001976 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001977 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001978 ConstantExpr::getNeg(DivRHS));
1979
Chris Lattner57c8d992003-02-18 19:57:07 +00001980 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001981 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001982 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001983 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001984 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001985 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001986 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001987 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001988 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001989
Chris Lattner47060462005-04-07 17:14:51 +00001990 if (!Op0->getType()->isFloatingPoint())
1991 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1992 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001993 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1994 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1995 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1996 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001997 } else if (Op0I->getOpcode() == Instruction::Sub) {
1998 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1999 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002000 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002001
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002002 ConstantInt *C1;
2003 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2004 if (X == Op1) { // X*C - X --> X * (C-1)
2005 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2006 return BinaryOperator::createMul(Op1, CP1);
2007 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002008
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002009 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2010 if (X == dyn_castFoldableMul(Op1, C2))
2011 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2012 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002013 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002014}
2015
Chris Lattnere79e8542004-02-23 06:38:22 +00002016/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2017/// really just returns true if the most significant (sign) bit is set.
2018static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2019 if (RHS->getType()->isSigned()) {
2020 // True if source is LHS < 0 or LHS <= -1
2021 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2022 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2023 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002024 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002025 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2026 // the size of the integer type.
2027 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002028 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002029 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002030 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002031 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002032 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002033 }
2034 return false;
2035}
2036
Chris Lattner113f4f42002-06-25 16:13:24 +00002037Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002038 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002039 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002040
Chris Lattner81a7a232004-10-16 18:11:37 +00002041 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2042 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2043
Chris Lattnere6794492002-08-12 21:17:25 +00002044 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002045 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2046 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002047
2048 // ((X << C1)*C2) == (X * (C2 << C1))
2049 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2050 if (SI->getOpcode() == Instruction::Shl)
2051 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002052 return BinaryOperator::createMul(SI->getOperand(0),
2053 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002054
Chris Lattnercce81be2003-09-11 22:24:54 +00002055 if (CI->isNullValue())
2056 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2057 if (CI->equalsInt(1)) // X * 1 == X
2058 return ReplaceInstUsesWith(I, Op0);
2059 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002060 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002061
Reid Spencere0fc4df2006-10-20 07:07:24 +00002062 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002063 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2064 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002065 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002066 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002067 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002068 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002069 if (Op1F->isNullValue())
2070 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002071
Chris Lattner3082c5a2003-02-18 19:28:33 +00002072 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2073 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2074 if (Op1F->getValue() == 1.0)
2075 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2076 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002077
2078 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2079 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2080 isa<ConstantInt>(Op0I->getOperand(1))) {
2081 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2082 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2083 Op1, "tmp");
2084 InsertNewInstBefore(Add, I);
2085 Value *C1C2 = ConstantExpr::getMul(Op1,
2086 cast<Constant>(Op0I->getOperand(1)));
2087 return BinaryOperator::createAdd(Add, C1C2);
2088
2089 }
Chris Lattner183b3362004-04-09 19:05:30 +00002090
2091 // Try to fold constant mul into select arguments.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002094 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002095
2096 if (isa<PHINode>(Op0))
2097 if (Instruction *NV = FoldOpIntoPhi(I))
2098 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002099 }
2100
Chris Lattner934a64cf2003-03-10 23:23:04 +00002101 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2102 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002103 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002104
Chris Lattner2635b522004-02-23 05:39:21 +00002105 // If one of the operands of the multiply is a cast from a boolean value, then
2106 // we know the bool is either zero or one, so this is a 'masking' multiply.
2107 // See if we can simplify things based on how the boolean was originally
2108 // formed.
2109 CastInst *BoolCast = 0;
2110 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2111 if (CI->getOperand(0)->getType() == Type::BoolTy)
2112 BoolCast = CI;
2113 if (!BoolCast)
2114 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2115 if (CI->getOperand(0)->getType() == Type::BoolTy)
2116 BoolCast = CI;
2117 if (BoolCast) {
2118 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2119 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2120 const Type *SCOpTy = SCIOp0->getType();
2121
Chris Lattnere79e8542004-02-23 06:38:22 +00002122 // If the setcc is true iff the sign bit of X is set, then convert this
2123 // multiply into a shift/and combination.
2124 if (isa<ConstantInt>(SCIOp1) &&
2125 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002126 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002127 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002128 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002129 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002130 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002131 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002132 }
2133
2134 Value *V =
2135 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2136 BoolCast->getOperand(0)->getName()+
2137 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002138
2139 // If the multiply type is not the same as the source type, sign extend
2140 // or truncate to the multiply type.
2141 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002142 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002143
Chris Lattner2635b522004-02-23 05:39:21 +00002144 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002145 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002146 }
2147 }
2148 }
2149
Chris Lattner113f4f42002-06-25 16:13:24 +00002150 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002151}
2152
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002153/// This function implements the transforms on div instructions that work
2154/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2155/// used by the visitors to those instructions.
2156/// @brief Transforms common to all three div instructions
2157Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002159
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002160 // undef / X -> 0
2161 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002163
2164 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002165 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002166 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002167
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002168 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002169 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2170 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002171 // same basic block, then we replace the select with Y, and the condition
2172 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002173 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002174 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002175 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2176 if (ST->isNullValue()) {
2177 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2178 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002179 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002180 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2181 I.setOperand(1, SI->getOperand(2));
2182 else
2183 UpdateValueUsesWith(SI, SI->getOperand(2));
2184 return &I;
2185 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002186
Chris Lattnerd79dc792006-09-09 20:26:32 +00002187 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2188 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2189 if (ST->isNullValue()) {
2190 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2191 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002192 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002193 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2194 I.setOperand(1, SI->getOperand(1));
2195 else
2196 UpdateValueUsesWith(SI, SI->getOperand(1));
2197 return &I;
2198 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002199 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002200
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002201 return 0;
2202}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002203
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002204/// This function implements the transforms common to both integer division
2205/// instructions (udiv and sdiv). It is called by the visitors to those integer
2206/// division instructions.
2207/// @brief Common integer divide transforms
2208Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2210
2211 if (Instruction *Common = commonDivTransforms(I))
2212 return Common;
2213
2214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2215 // div X, 1 == X
2216 if (RHS->equalsInt(1))
2217 return ReplaceInstUsesWith(I, Op0);
2218
2219 // (X / C1) / C2 -> X / (C1*C2)
2220 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2221 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2222 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2223 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2224 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002225 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002226
2227 if (!RHS->isNullValue()) { // avoid X udiv 0
2228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2230 return R;
2231 if (isa<PHINode>(Op0))
2232 if (Instruction *NV = FoldOpIntoPhi(I))
2233 return NV;
2234 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002235 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002236
Chris Lattner3082c5a2003-02-18 19:28:33 +00002237 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002238 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002239 if (LHS->equalsInt(0))
2240 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2241
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002242 return 0;
2243}
2244
2245Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2247
2248 // Handle the integer div common cases
2249 if (Instruction *Common = commonIDivTransforms(I))
2250 return Common;
2251
2252 // X udiv C^2 -> X >> C
2253 // Check to see if this is an unsigned division with an exact power of 2,
2254 // if so, convert to a right shift.
2255 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2256 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2257 if (isPowerOf2_64(Val)) {
2258 uint64_t ShiftAmt = Log2_64(Val);
2259 Value* X = Op0;
2260 const Type* XTy = X->getType();
2261 bool isSigned = XTy->isSigned();
2262 if (isSigned)
2263 X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2264 Instruction* Result =
2265 new ShiftInst(Instruction::Shr, X,
2266 ConstantInt::get(Type::UByteTy, ShiftAmt));
2267 if (!isSigned)
2268 return Result;
2269 InsertNewInstBefore(Result, I);
2270 return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2271 }
2272 }
2273
2274 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2275 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2276 if (RHSI->getOpcode() == Instruction::Shl &&
2277 isa<ConstantInt>(RHSI->getOperand(0))) {
2278 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2279 if (isPowerOf2_64(C1)) {
2280 Value *N = RHSI->getOperand(1);
2281 const Type* NTy = N->getType();
2282 bool isSigned = NTy->isSigned();
2283 if (uint64_t C2 = Log2_64(C1)) {
2284 if (isSigned) {
2285 NTy = NTy->getUnsignedVersion();
2286 N = InsertCastBefore(N, NTy, I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002287 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002288 Constant *C2V = ConstantInt::get(NTy, C2);
2289 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002290 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002291 Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2292 if (!isSigned)
2293 return Result;
2294 InsertNewInstBefore(Result, I);
2295 return new CastInst(Result, NTy->getSignedVersion(), I.getName());
Chris Lattner2e90b732006-02-05 07:54:04 +00002296 }
2297 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002298 }
2299
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002300 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2301 // where C1&C2 are powers of two.
2302 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2303 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2304 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2305 if (!STO->isNullValue() && !STO->isNullValue()) {
2306 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2307 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2308 // Compute the shift amounts
2309 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2310 // Make sure we get the unsigned version of X
2311 Value* X = Op0;
2312 const Type* origXTy = X->getType();
2313 bool isSigned = origXTy->isSigned();
2314 if (isSigned)
2315 X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2316 // Construct the "on true" case of the select
2317 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2318 Instruction *TSI =
2319 new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2320 TSI = InsertNewInstBefore(TSI, I);
2321
2322 // Construct the "on false" case of the select
2323 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2324 Instruction *FSI =
2325 new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2326 FSI = InsertNewInstBefore(FSI, I);
2327
2328 // construct the select instruction and return it.
2329 SelectInst* NewSI =
2330 new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2331 if (!isSigned)
2332 return NewSI;
2333 InsertNewInstBefore(NewSI, I);
2334 return new CastInst(NewSI, origXTy, NewSI->getName());
2335 }
2336 }
2337 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002338 return 0;
2339}
2340
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002341Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2343
2344 // Handle the integer div common cases
2345 if (Instruction *Common = commonIDivTransforms(I))
2346 return Common;
2347
2348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2349 // sdiv X, -1 == -X
2350 if (RHS->isAllOnesValue())
2351 return BinaryOperator::createNeg(Op0);
2352
2353 // -X/C -> X/-C
2354 if (Value *LHSNeg = dyn_castNegVal(Op0))
2355 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2356 }
2357
2358 // If the sign bits of both operands are zero (i.e. we can prove they are
2359 // unsigned inputs), turn this into a udiv.
2360 if (I.getType()->isInteger()) {
2361 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2362 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2363 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2364 }
2365 }
2366
2367 return 0;
2368}
2369
2370Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2371 return commonDivTransforms(I);
2372}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002373
Chris Lattner85dda9a2006-03-02 06:50:58 +00002374/// GetFactor - If we can prove that the specified value is at least a multiple
2375/// of some factor, return that factor.
2376static Constant *GetFactor(Value *V) {
2377 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2378 return CI;
2379
2380 // Unless we can be tricky, we know this is a multiple of 1.
2381 Constant *Result = ConstantInt::get(V->getType(), 1);
2382
2383 Instruction *I = dyn_cast<Instruction>(V);
2384 if (!I) return Result;
2385
2386 if (I->getOpcode() == Instruction::Mul) {
2387 // Handle multiplies by a constant, etc.
2388 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2389 GetFactor(I->getOperand(1)));
2390 } else if (I->getOpcode() == Instruction::Shl) {
2391 // (X<<C) -> X * (1 << C)
2392 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2393 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2394 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2395 }
2396 } else if (I->getOpcode() == Instruction::And) {
2397 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2398 // X & 0xFFF0 is known to be a multiple of 16.
2399 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2400 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2401 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002402 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002403 }
2404 } else if (I->getOpcode() == Instruction::Cast) {
2405 Value *Op = I->getOperand(0);
2406 // Only handle int->int casts.
2407 if (!Op->getType()->isInteger()) return Result;
2408 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2409 }
2410 return Result;
2411}
2412
Chris Lattner113f4f42002-06-25 16:13:24 +00002413Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002415
2416 // 0 % X == 0, we don't need to preserve faults!
2417 if (Constant *LHS = dyn_cast<Constant>(Op0))
2418 if (LHS->isNullValue())
2419 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2420
2421 if (isa<UndefValue>(Op0)) // undef % X -> 0
2422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2423 if (isa<UndefValue>(Op1))
2424 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2425
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002426 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002427 if (Value *RHSNeg = dyn_castNegVal(Op1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00002428 if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2429 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002430 // X % -Y -> X % Y
2431 AddUsesToWorkList(I);
2432 I.setOperand(1, RHSNeg);
2433 return &I;
2434 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002435
2436 // If the top bits of both operands are zero (i.e. we can prove they are
2437 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002438 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2439 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002440 const Type *NTy = Op0->getType()->getUnsignedVersion();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002441 Value *LHS = InsertCastBefore(Op0, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002442 Value *RHS;
2443 if (Constant *R = dyn_cast<Constant>(Op1))
2444 RHS = ConstantExpr::getCast(R, NTy);
2445 else
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002446 RHS = InsertCastBefore(Op1, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002447 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2448 InsertNewInstBefore(Rem, I);
2449 return new CastInst(Rem, I.getType());
2450 }
2451 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002452
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002454 // X % 0 == undef, we don't need to preserve faults!
2455 if (RHS->equalsInt(0))
2456 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2457
Chris Lattner3082c5a2003-02-18 19:28:33 +00002458 if (RHS->equalsInt(1)) // X % 1 == 0
2459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461 // Check to see if this is an unsigned remainder with an exact power of 2,
2462 // if so, convert to a bitwise and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002463 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2464 if (RHS->getType()->isUnsigned())
2465 if (isPowerOf2_64(C->getZExtValue()))
2466 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002467
Chris Lattnerb70f1412006-02-28 05:49:21 +00002468 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2469 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2470 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2471 return R;
2472 } else if (isa<PHINode>(Op0I)) {
2473 if (Instruction *NV = FoldOpIntoPhi(I))
2474 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002475 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002476
2477 // X*C1%C2 --> 0 iff C1%C2 == 0
2478 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2479 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002480 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002481 }
2482
Chris Lattner2e90b732006-02-05 07:54:04 +00002483 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2484 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2485 if (I.getType()->isUnsigned() &&
2486 RHSI->getOpcode() == Instruction::Shl &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00002487 isa<ConstantInt>(RHSI->getOperand(0)) &&
2488 RHSI->getOperand(0)->getType()->isUnsigned()) {
2489 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002490 if (isPowerOf2_64(C1)) {
2491 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2492 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2493 "tmp"), I);
2494 return BinaryOperator::createAnd(Op0, Add);
2495 }
2496 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002497
2498 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2499 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002500 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2501 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2502 // the same basic block, then we replace the select with Y, and the
2503 // condition of the select with false (if the cond value is in the same
2504 // BB). If the select has uses other than the div, this allows them to be
2505 // simplified also.
2506 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2507 if (ST->isNullValue()) {
2508 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2509 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002510 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002511 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2512 I.setOperand(1, SI->getOperand(2));
2513 else
2514 UpdateValueUsesWith(SI, SI->getOperand(2));
2515 return &I;
2516 }
2517 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2518 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2519 if (ST->isNullValue()) {
2520 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2521 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002522 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002523 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2524 I.setOperand(1, SI->getOperand(1));
2525 else
2526 UpdateValueUsesWith(SI, SI->getOperand(1));
2527 return &I;
2528 }
2529
2530
Reid Spencere0fc4df2006-10-20 07:07:24 +00002531 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2532 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2533 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2534 // STO == 0 and SFO == 0 handled above.
2535 if (isPowerOf2_64(STO->getZExtValue()) &&
2536 isPowerOf2_64(SFO->getZExtValue())) {
2537 Value *TrueAnd = InsertNewInstBefore(
2538 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2539 I);
2540 Value *FalseAnd = InsertNewInstBefore(
2541 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2542 I);
2543 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2544 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002545 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002546 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002547 }
2548
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002549 return 0;
2550}
2551
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002552// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002553static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002554 if (C->getType()->isUnsigned())
2555 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002556
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002557 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002558 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002559 int64_t Val = INT64_MAX; // All ones
2560 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002561 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002562}
2563
2564// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002565static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002566 if (C->getType()->isUnsigned())
2567 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002568
2569 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002570 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002571 int64_t Val = -1; // All ones
2572 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002573 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002574}
2575
Chris Lattner35167c32004-06-09 07:59:58 +00002576// isOneBitSet - Return true if there is exactly one bit set in the specified
2577// constant.
2578static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002579 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002580 return V && (V & (V-1)) == 0;
2581}
2582
Chris Lattner8fc5af42004-09-23 21:46:38 +00002583#if 0 // Currently unused
2584// isLowOnes - Return true if the constant is of the form 0+1+.
2585static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002586 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002587
2588 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002589 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002590
2591 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2592 return U && V && (U & V) == 0;
2593}
2594#endif
2595
2596// isHighOnes - Return true if the constant is of the form 1+0+.
2597// This is the same as lowones(~X).
2598static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002599 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002600 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002601
2602 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002603 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002604
2605 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2606 return U && V && (U & V) == 0;
2607}
2608
2609
Chris Lattner3ac7c262003-08-13 20:16:26 +00002610/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2611/// are carefully arranged to allow folding of expressions such as:
2612///
2613/// (A < B) | (A > B) --> (A != B)
2614///
2615/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2616/// represents that the comparison is true if A == B, and bit value '1' is true
2617/// if A < B.
2618///
2619static unsigned getSetCondCode(const SetCondInst *SCI) {
2620 switch (SCI->getOpcode()) {
2621 // False -> 0
2622 case Instruction::SetGT: return 1;
2623 case Instruction::SetEQ: return 2;
2624 case Instruction::SetGE: return 3;
2625 case Instruction::SetLT: return 4;
2626 case Instruction::SetNE: return 5;
2627 case Instruction::SetLE: return 6;
2628 // True -> 7
2629 default:
2630 assert(0 && "Invalid SetCC opcode!");
2631 return 0;
2632 }
2633}
2634
2635/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2636/// opcode and two operands into either a constant true or false, or a brand new
2637/// SetCC instruction.
2638static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2639 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002640 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002641 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2642 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2643 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2644 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2645 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2646 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002647 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002648 default: assert(0 && "Illegal SetCCCode!"); return 0;
2649 }
2650}
2651
2652// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2653struct FoldSetCCLogical {
2654 InstCombiner &IC;
2655 Value *LHS, *RHS;
2656 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2657 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2658 bool shouldApply(Value *V) const {
2659 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2660 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2661 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2662 return false;
2663 }
2664 Instruction *apply(BinaryOperator &Log) const {
2665 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2666 if (SCI->getOperand(0) != LHS) {
2667 assert(SCI->getOperand(1) == LHS);
2668 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2669 }
2670
2671 unsigned LHSCode = getSetCondCode(SCI);
2672 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2673 unsigned Code;
2674 switch (Log.getOpcode()) {
2675 case Instruction::And: Code = LHSCode & RHSCode; break;
2676 case Instruction::Or: Code = LHSCode | RHSCode; break;
2677 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002678 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002679 }
2680
2681 Value *RV = getSetCCValue(Code, LHS, RHS);
2682 if (Instruction *I = dyn_cast<Instruction>(RV))
2683 return I;
2684 // Otherwise, it's a constant boolean value...
2685 return IC.ReplaceInstUsesWith(Log, RV);
2686 }
2687};
2688
Chris Lattnerba1cb382003-09-19 17:17:26 +00002689// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2690// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2691// guaranteed to be either a shift instruction or a binary operator.
2692Instruction *InstCombiner::OptAndOp(Instruction *Op,
2693 ConstantIntegral *OpRHS,
2694 ConstantIntegral *AndRHS,
2695 BinaryOperator &TheAnd) {
2696 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002697 Constant *Together = 0;
2698 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002699 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002700
Chris Lattnerba1cb382003-09-19 17:17:26 +00002701 switch (Op->getOpcode()) {
2702 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002703 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002704 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2705 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002706 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002707 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002708 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002709 }
2710 break;
2711 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002712 if (Together == AndRHS) // (X | C) & C --> C
2713 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002714
Chris Lattner86102b82005-01-01 16:22:27 +00002715 if (Op->hasOneUse() && Together != OpRHS) {
2716 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2717 std::string Op0Name = Op->getName(); Op->setName("");
2718 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2719 InsertNewInstBefore(Or, TheAnd);
2720 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002721 }
2722 break;
2723 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002724 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002725 // Adding a one to a single bit bit-field should be turned into an XOR
2726 // of the bit. First thing to check is to see if this AND is with a
2727 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002728 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002729
2730 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002731 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002732
2733 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002734 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002735 // Ok, at this point, we know that we are masking the result of the
2736 // ADD down to exactly one bit. If the constant we are adding has
2737 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002738 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002739
Chris Lattnerba1cb382003-09-19 17:17:26 +00002740 // Check to see if any bits below the one bit set in AndRHSV are set.
2741 if ((AddRHS & (AndRHSV-1)) == 0) {
2742 // If not, the only thing that can effect the output of the AND is
2743 // the bit specified by AndRHSV. If that bit is set, the effect of
2744 // the XOR is to toggle the bit. If it is clear, then the ADD has
2745 // no effect.
2746 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2747 TheAnd.setOperand(0, X);
2748 return &TheAnd;
2749 } else {
2750 std::string Name = Op->getName(); Op->setName("");
2751 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002752 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002753 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002754 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002755 }
2756 }
2757 }
2758 }
2759 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002760
2761 case Instruction::Shl: {
2762 // We know that the AND will not produce any of the bits shifted in, so if
2763 // the anded constant includes them, clear them now!
2764 //
2765 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002766 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2767 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002768
Chris Lattner7e794272004-09-24 15:21:34 +00002769 if (CI == ShlMask) { // Masking out bits that the shift already masks
2770 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2771 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002772 TheAnd.setOperand(1, CI);
2773 return &TheAnd;
2774 }
2775 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002776 }
Chris Lattner2da29172003-09-19 19:05:02 +00002777 case Instruction::Shr:
2778 // We know that the AND will not produce any of the bits shifted in, so if
2779 // the anded constant includes them, clear them now! This only applies to
2780 // unsigned shifts, because a signed shr may bring in set bits!
2781 //
2782 if (AndRHS->getType()->isUnsigned()) {
2783 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002784 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2785 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2786
2787 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2788 return ReplaceInstUsesWith(TheAnd, Op);
2789 } else if (CI != AndRHS) {
2790 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002791 return &TheAnd;
2792 }
Chris Lattner7e794272004-09-24 15:21:34 +00002793 } else { // Signed shr.
2794 // See if this is shifting in some sign extension, then masking it out
2795 // with an and.
2796 if (Op->hasOneUse()) {
2797 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2798 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2799 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002800 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002801 // Make the argument unsigned.
2802 Value *ShVal = Op->getOperand(0);
2803 ShVal = InsertCastBefore(ShVal,
2804 ShVal->getType()->getUnsignedVersion(),
2805 TheAnd);
2806 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2807 OpRHS, Op->getName()),
2808 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002809 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2810 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2811 TheAnd.getName()),
2812 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002813 return new CastInst(ShVal, Op->getType());
2814 }
2815 }
Chris Lattner2da29172003-09-19 19:05:02 +00002816 }
2817 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002818 }
2819 return 0;
2820}
2821
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002822
Chris Lattner6862fbd2004-09-29 17:40:11 +00002823/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2824/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2825/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2826/// insert new instructions.
2827Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2828 bool Inside, Instruction &IB) {
2829 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2830 "Lo is not <= Hi in range emission code!");
2831 if (Inside) {
2832 if (Lo == Hi) // Trivially false.
2833 return new SetCondInst(Instruction::SetNE, V, V);
2834 if (cast<ConstantIntegral>(Lo)->isMinValue())
2835 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002836
Chris Lattner6862fbd2004-09-29 17:40:11 +00002837 Constant *AddCST = ConstantExpr::getNeg(Lo);
2838 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2839 InsertNewInstBefore(Add, IB);
2840 // Convert to unsigned for the comparison.
2841 const Type *UnsType = Add->getType()->getUnsignedVersion();
2842 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2843 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2844 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2845 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2846 }
2847
2848 if (Lo == Hi) // Trivially true.
2849 return new SetCondInst(Instruction::SetEQ, V, V);
2850
2851 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002852
2853 // V < 0 || V >= Hi ->'V > Hi-1'
2854 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002855 return new SetCondInst(Instruction::SetGT, V, Hi);
2856
2857 // Emit X-Lo > Hi-Lo-1
2858 Constant *AddCST = ConstantExpr::getNeg(Lo);
2859 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2860 InsertNewInstBefore(Add, IB);
2861 // Convert to unsigned for the comparison.
2862 const Type *UnsType = Add->getType()->getUnsignedVersion();
2863 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2864 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2865 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2866 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2867}
2868
Chris Lattnerb4b25302005-09-18 07:22:02 +00002869// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2870// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2871// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2872// not, since all 1s are not contiguous.
2873static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002874 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002875 if (!isShiftedMask_64(V)) return false;
2876
2877 // look for the first zero bit after the run of ones
2878 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2879 // look for the first non-zero bit
2880 ME = 64-CountLeadingZeros_64(V);
2881 return true;
2882}
2883
2884
2885
2886/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2887/// where isSub determines whether the operator is a sub. If we can fold one of
2888/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002889///
2890/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2891/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2892/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2893///
2894/// return (A +/- B).
2895///
2896Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2897 ConstantIntegral *Mask, bool isSub,
2898 Instruction &I) {
2899 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2900 if (!LHSI || LHSI->getNumOperands() != 2 ||
2901 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2902
2903 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2904
2905 switch (LHSI->getOpcode()) {
2906 default: return 0;
2907 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002908 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2909 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002910 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002911 break;
2912
2913 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2914 // part, we don't need any explicit masks to take them out of A. If that
2915 // is all N is, ignore it.
2916 unsigned MB, ME;
2917 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002918 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2919 Mask >>= 64-MB+1;
2920 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002921 break;
2922 }
2923 }
Chris Lattneraf517572005-09-18 04:24:45 +00002924 return 0;
2925 case Instruction::Or:
2926 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002927 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002928 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002929 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002930 break;
2931 return 0;
2932 }
2933
2934 Instruction *New;
2935 if (isSub)
2936 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2937 else
2938 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2939 return InsertNewInstBefore(New, I);
2940}
2941
Chris Lattner113f4f42002-06-25 16:13:24 +00002942Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002943 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002945
Chris Lattner81a7a232004-10-16 18:11:37 +00002946 if (isa<UndefValue>(Op1)) // X & undef -> 0
2947 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2948
Chris Lattner86102b82005-01-01 16:22:27 +00002949 // and X, X = X
2950 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002951 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002952
Chris Lattner5b2edb12006-02-12 08:02:11 +00002953 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002954 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002955 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002956 if (!isa<PackedType>(I.getType()) &&
2957 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002958 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002959 return &I;
2960
Chris Lattner86102b82005-01-01 16:22:27 +00002961 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002962 uint64_t AndRHSMask = AndRHS->getZExtValue();
2963 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002964 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002965
Chris Lattnerba1cb382003-09-19 17:17:26 +00002966 // Optimize a variety of ((val OP C1) & C2) combinations...
2967 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2968 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002969 Value *Op0LHS = Op0I->getOperand(0);
2970 Value *Op0RHS = Op0I->getOperand(1);
2971 switch (Op0I->getOpcode()) {
2972 case Instruction::Xor:
2973 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002974 // If the mask is only needed on one incoming arm, push it up.
2975 if (Op0I->hasOneUse()) {
2976 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2977 // Not masking anything out for the LHS, move to RHS.
2978 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2979 Op0RHS->getName()+".masked");
2980 InsertNewInstBefore(NewRHS, I);
2981 return BinaryOperator::create(
2982 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002983 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002984 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002985 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2986 // Not masking anything out for the RHS, move to LHS.
2987 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2988 Op0LHS->getName()+".masked");
2989 InsertNewInstBefore(NewLHS, I);
2990 return BinaryOperator::create(
2991 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2992 }
2993 }
2994
Chris Lattner86102b82005-01-01 16:22:27 +00002995 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002996 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002997 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2998 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2999 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3000 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3001 return BinaryOperator::createAnd(V, AndRHS);
3002 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3003 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003004 break;
3005
3006 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003007 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3008 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3009 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3010 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3011 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003012 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003013 }
3014
Chris Lattner16464b32003-07-23 19:25:52 +00003015 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003016 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003017 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003018 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3019 const Type *SrcTy = CI->getOperand(0)->getType();
3020
Chris Lattner2c14cf72005-08-07 07:03:10 +00003021 // If this is an integer truncation or change from signed-to-unsigned, and
3022 // if the source is an and/or with immediate, transform it. This
3023 // frequently occurs for bitfield accesses.
3024 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3025 if (SrcTy->getPrimitiveSizeInBits() >=
3026 I.getType()->getPrimitiveSizeInBits() &&
3027 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003028 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003029 if (CastOp->getOpcode() == Instruction::And) {
3030 // Change: and (cast (and X, C1) to T), C2
3031 // into : and (cast X to T), trunc(C1)&C2
3032 // This will folds the two ands together, which may allow other
3033 // simplifications.
3034 Instruction *NewCast =
3035 new CastInst(CastOp->getOperand(0), I.getType(),
3036 CastOp->getName()+".shrunk");
3037 NewCast = InsertNewInstBefore(NewCast, I);
3038
3039 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3040 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3041 return BinaryOperator::createAnd(NewCast, C3);
3042 } else if (CastOp->getOpcode() == Instruction::Or) {
3043 // Change: and (cast (or X, C1) to T), C2
3044 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3045 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3046 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3047 return ReplaceInstUsesWith(I, AndRHS);
3048 }
3049 }
Chris Lattner33217db2003-07-23 19:36:21 +00003050 }
Chris Lattner183b3362004-04-09 19:05:30 +00003051
3052 // Try to fold constant and into select arguments.
3053 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003054 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003055 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003056 if (isa<PHINode>(Op0))
3057 if (Instruction *NV = FoldOpIntoPhi(I))
3058 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003059 }
3060
Chris Lattnerbb74e222003-03-10 23:06:50 +00003061 Value *Op0NotVal = dyn_castNotVal(Op0);
3062 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003063
Chris Lattner023a4832004-06-18 06:07:51 +00003064 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3065 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3066
Misha Brukman9c003d82004-07-30 12:50:08 +00003067 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003068 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003069 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3070 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003071 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003072 return BinaryOperator::createNot(Or);
3073 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003074
3075 {
3076 Value *A = 0, *B = 0;
3077 ConstantInt *C1 = 0, *C2 = 0;
3078 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3079 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3080 return ReplaceInstUsesWith(I, Op1);
3081 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3082 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3083 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003084
3085 if (Op0->hasOneUse() &&
3086 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3087 if (A == Op1) { // (A^B)&A -> A&(A^B)
3088 I.swapOperands(); // Simplify below
3089 std::swap(Op0, Op1);
3090 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3091 cast<BinaryOperator>(Op0)->swapOperands();
3092 I.swapOperands(); // Simplify below
3093 std::swap(Op0, Op1);
3094 }
3095 }
3096 if (Op1->hasOneUse() &&
3097 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3098 if (B == Op0) { // B&(A^B) -> B&(B^A)
3099 cast<BinaryOperator>(Op1)->swapOperands();
3100 std::swap(A, B);
3101 }
3102 if (A == Op0) { // A&(A^B) -> A & ~B
3103 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3104 InsertNewInstBefore(NotB, I);
3105 return BinaryOperator::createAnd(A, NotB);
3106 }
3107 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003108 }
3109
Chris Lattner3082c5a2003-02-18 19:28:33 +00003110
Chris Lattner623826c2004-09-28 21:48:02 +00003111 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3112 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003113 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3114 return R;
3115
Chris Lattner623826c2004-09-28 21:48:02 +00003116 Value *LHSVal, *RHSVal;
3117 ConstantInt *LHSCst, *RHSCst;
3118 Instruction::BinaryOps LHSCC, RHSCC;
3119 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3120 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3121 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3122 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003123 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003124 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3125 // Ensure that the larger constant is on the RHS.
3126 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3127 SetCondInst *LHS = cast<SetCondInst>(Op0);
3128 if (cast<ConstantBool>(Cmp)->getValue()) {
3129 std::swap(LHS, RHS);
3130 std::swap(LHSCst, RHSCst);
3131 std::swap(LHSCC, RHSCC);
3132 }
3133
3134 // At this point, we know we have have two setcc instructions
3135 // comparing a value against two constants and and'ing the result
3136 // together. Because of the above check, we know that we only have
3137 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3138 // FoldSetCCLogical check above), that the two constants are not
3139 // equal.
3140 assert(LHSCst != RHSCst && "Compares not folded above?");
3141
3142 switch (LHSCC) {
3143 default: assert(0 && "Unknown integer condition code!");
3144 case Instruction::SetEQ:
3145 switch (RHSCC) {
3146 default: assert(0 && "Unknown integer condition code!");
3147 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3148 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003149 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003150 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3151 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3152 return ReplaceInstUsesWith(I, LHS);
3153 }
3154 case Instruction::SetNE:
3155 switch (RHSCC) {
3156 default: assert(0 && "Unknown integer condition code!");
3157 case Instruction::SetLT:
3158 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3159 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3160 break; // (X != 13 & X < 15) -> no change
3161 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3162 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3163 return ReplaceInstUsesWith(I, RHS);
3164 case Instruction::SetNE:
3165 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3166 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3167 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3168 LHSVal->getName()+".off");
3169 InsertNewInstBefore(Add, I);
3170 const Type *UnsType = Add->getType()->getUnsignedVersion();
3171 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3172 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3173 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3174 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3175 }
3176 break; // (X != 13 & X != 15) -> no change
3177 }
3178 break;
3179 case Instruction::SetLT:
3180 switch (RHSCC) {
3181 default: assert(0 && "Unknown integer condition code!");
3182 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3183 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003184 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003185 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3186 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3187 return ReplaceInstUsesWith(I, LHS);
3188 }
3189 case Instruction::SetGT:
3190 switch (RHSCC) {
3191 default: assert(0 && "Unknown integer condition code!");
3192 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3193 return ReplaceInstUsesWith(I, LHS);
3194 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3195 return ReplaceInstUsesWith(I, RHS);
3196 case Instruction::SetNE:
3197 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3198 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3199 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003200 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3201 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003202 }
3203 }
3204 }
3205 }
3206
Chris Lattner3af10532006-05-05 06:39:07 +00003207 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3208 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003209 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003210 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003211 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003212 // Only do this if the casts both really cause code to be generated.
3213 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3214 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003215 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3216 Op1C->getOperand(0),
3217 I.getName());
3218 InsertNewInstBefore(NewOp, I);
3219 return new CastInst(NewOp, I.getType());
3220 }
3221 }
3222
Chris Lattner113f4f42002-06-25 16:13:24 +00003223 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003224}
3225
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003226/// CollectBSwapParts - Look to see if the specified value defines a single byte
3227/// in the result. If it does, and if the specified byte hasn't been filled in
3228/// yet, fill it in and return false.
3229static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3230 Instruction *I = dyn_cast<Instruction>(V);
3231 if (I == 0) return true;
3232
3233 // If this is an or instruction, it is an inner node of the bswap.
3234 if (I->getOpcode() == Instruction::Or)
3235 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3236 CollectBSwapParts(I->getOperand(1), ByteValues);
3237
3238 // If this is a shift by a constant int, and it is "24", then its operand
3239 // defines a byte. We only handle unsigned types here.
3240 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3241 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003242 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003243 8*(ByteValues.size()-1))
3244 return true;
3245
3246 unsigned DestNo;
3247 if (I->getOpcode() == Instruction::Shl) {
3248 // X << 24 defines the top byte with the lowest of the input bytes.
3249 DestNo = ByteValues.size()-1;
3250 } else {
3251 // X >>u 24 defines the low byte with the highest of the input bytes.
3252 DestNo = 0;
3253 }
3254
3255 // If the destination byte value is already defined, the values are or'd
3256 // together, which isn't a bswap (unless it's an or of the same bits).
3257 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3258 return true;
3259 ByteValues[DestNo] = I->getOperand(0);
3260 return false;
3261 }
3262
3263 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3264 // don't have this.
3265 Value *Shift = 0, *ShiftLHS = 0;
3266 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3267 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3268 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3269 return true;
3270 Instruction *SI = cast<Instruction>(Shift);
3271
3272 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003273 if (ShiftAmt->getZExtValue() & 7 ||
3274 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003275 return true;
3276
3277 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3278 unsigned DestByte;
3279 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003280 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003281 break;
3282 // Unknown mask for bswap.
3283 if (DestByte == ByteValues.size()) return true;
3284
Reid Spencere0fc4df2006-10-20 07:07:24 +00003285 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003286 unsigned SrcByte;
3287 if (SI->getOpcode() == Instruction::Shl)
3288 SrcByte = DestByte - ShiftBytes;
3289 else
3290 SrcByte = DestByte + ShiftBytes;
3291
3292 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3293 if (SrcByte != ByteValues.size()-DestByte-1)
3294 return true;
3295
3296 // If the destination byte value is already defined, the values are or'd
3297 // together, which isn't a bswap (unless it's an or of the same bits).
3298 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3299 return true;
3300 ByteValues[DestByte] = SI->getOperand(0);
3301 return false;
3302}
3303
3304/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3305/// If so, insert the new bswap intrinsic and return it.
3306Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3307 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3308 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3309 return 0;
3310
3311 /// ByteValues - For each byte of the result, we keep track of which value
3312 /// defines each byte.
3313 std::vector<Value*> ByteValues;
3314 ByteValues.resize(I.getType()->getPrimitiveSize());
3315
3316 // Try to find all the pieces corresponding to the bswap.
3317 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3318 CollectBSwapParts(I.getOperand(1), ByteValues))
3319 return 0;
3320
3321 // Check to see if all of the bytes come from the same value.
3322 Value *V = ByteValues[0];
3323 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3324
3325 // Check to make sure that all of the bytes come from the same value.
3326 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3327 if (ByteValues[i] != V)
3328 return 0;
3329
3330 // If they do then *success* we can turn this into a bswap. Figure out what
3331 // bswap to make it into.
3332 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003333 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003334 if (I.getType() == Type::UShortTy)
3335 FnName = "llvm.bswap.i16";
3336 else if (I.getType() == Type::UIntTy)
3337 FnName = "llvm.bswap.i32";
3338 else if (I.getType() == Type::ULongTy)
3339 FnName = "llvm.bswap.i64";
3340 else
3341 assert(0 && "Unknown integer type!");
3342 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3343
3344 return new CallInst(F, V);
3345}
3346
3347
Chris Lattner113f4f42002-06-25 16:13:24 +00003348Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003349 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003351
Chris Lattner81a7a232004-10-16 18:11:37 +00003352 if (isa<UndefValue>(Op1))
3353 return ReplaceInstUsesWith(I, // X | undef -> -1
3354 ConstantIntegral::getAllOnesValue(I.getType()));
3355
Chris Lattner5b2edb12006-02-12 08:02:11 +00003356 // or X, X = X
3357 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003358 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003359
Chris Lattner5b2edb12006-02-12 08:02:11 +00003360 // See if we can simplify any instructions used by the instruction whose sole
3361 // purpose is to compute bits we don't care about.
3362 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003363 if (!isa<PackedType>(I.getType()) &&
3364 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003365 KnownZero, KnownOne))
3366 return &I;
3367
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003368 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003369 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003370 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003371 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3372 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003373 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3374 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003375 InsertNewInstBefore(Or, I);
3376 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3377 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003378
Chris Lattnerd4252a72004-07-30 07:50:03 +00003379 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3380 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3381 std::string Op0Name = Op0->getName(); Op0->setName("");
3382 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3383 InsertNewInstBefore(Or, I);
3384 return BinaryOperator::createXor(Or,
3385 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003386 }
Chris Lattner183b3362004-04-09 19:05:30 +00003387
3388 // Try to fold constant and into select arguments.
3389 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003390 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003391 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003392 if (isa<PHINode>(Op0))
3393 if (Instruction *NV = FoldOpIntoPhi(I))
3394 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003395 }
3396
Chris Lattner330628a2006-01-06 17:59:59 +00003397 Value *A = 0, *B = 0;
3398 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003399
3400 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3401 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3402 return ReplaceInstUsesWith(I, Op1);
3403 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3404 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3405 return ReplaceInstUsesWith(I, Op0);
3406
Chris Lattnerb7845d62006-07-10 20:25:24 +00003407 // (A | B) | C and A | (B | C) -> bswap if possible.
3408 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003409 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003410 match(Op1, m_Or(m_Value(), m_Value())) ||
3411 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3412 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003413 if (Instruction *BSwap = MatchBSwap(I))
3414 return BSwap;
3415 }
3416
Chris Lattnerb62f5082005-05-09 04:58:36 +00003417 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3418 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003419 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003420 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3421 Op0->setName("");
3422 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3423 }
3424
3425 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3426 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003427 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003428 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3429 Op0->setName("");
3430 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3431 }
3432
Chris Lattner15212982005-09-18 03:42:07 +00003433 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003434 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003435 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3436
3437 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3438 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3439
3440
Chris Lattner01f56c62005-09-18 06:02:59 +00003441 // If we have: ((V + N) & C1) | (V & C2)
3442 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3443 // replace with V+N.
3444 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003445 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003446 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003447 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3448 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003449 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003450 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003451 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003452 return ReplaceInstUsesWith(I, A);
3453 }
3454 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003455 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003456 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3457 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003458 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003459 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003460 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003461 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003462 }
3463 }
3464 }
Chris Lattner812aab72003-08-12 19:11:07 +00003465
Chris Lattnerd4252a72004-07-30 07:50:03 +00003466 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3467 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003468 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003469 ConstantIntegral::getAllOnesValue(I.getType()));
3470 } else {
3471 A = 0;
3472 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003473 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003474 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3475 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003476 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003477 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003478
Misha Brukman9c003d82004-07-30 12:50:08 +00003479 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003480 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3481 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3482 I.getName()+".demorgan"), I);
3483 return BinaryOperator::createNot(And);
3484 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003485 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003486
Chris Lattner3ac7c262003-08-13 20:16:26 +00003487 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003488 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003489 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3490 return R;
3491
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003492 Value *LHSVal, *RHSVal;
3493 ConstantInt *LHSCst, *RHSCst;
3494 Instruction::BinaryOps LHSCC, RHSCC;
3495 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3496 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3497 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3498 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003499 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003500 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3501 // Ensure that the larger constant is on the RHS.
3502 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3503 SetCondInst *LHS = cast<SetCondInst>(Op0);
3504 if (cast<ConstantBool>(Cmp)->getValue()) {
3505 std::swap(LHS, RHS);
3506 std::swap(LHSCst, RHSCst);
3507 std::swap(LHSCC, RHSCC);
3508 }
3509
3510 // At this point, we know we have have two setcc instructions
3511 // comparing a value against two constants and or'ing the result
3512 // together. Because of the above check, we know that we only have
3513 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3514 // FoldSetCCLogical check above), that the two constants are not
3515 // equal.
3516 assert(LHSCst != RHSCst && "Compares not folded above?");
3517
3518 switch (LHSCC) {
3519 default: assert(0 && "Unknown integer condition code!");
3520 case Instruction::SetEQ:
3521 switch (RHSCC) {
3522 default: assert(0 && "Unknown integer condition code!");
3523 case Instruction::SetEQ:
3524 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3525 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3526 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3527 LHSVal->getName()+".off");
3528 InsertNewInstBefore(Add, I);
3529 const Type *UnsType = Add->getType()->getUnsignedVersion();
3530 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3531 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3532 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3533 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3534 }
3535 break; // (X == 13 | X == 15) -> no change
3536
Chris Lattner5c219462005-04-19 06:04:18 +00003537 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3538 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003539 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3540 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3541 return ReplaceInstUsesWith(I, RHS);
3542 }
3543 break;
3544 case Instruction::SetNE:
3545 switch (RHSCC) {
3546 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003547 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3548 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3549 return ReplaceInstUsesWith(I, LHS);
3550 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003551 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003552 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003553 }
3554 break;
3555 case Instruction::SetLT:
3556 switch (RHSCC) {
3557 default: assert(0 && "Unknown integer condition code!");
3558 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3559 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003560 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3561 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003562 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3563 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3564 return ReplaceInstUsesWith(I, RHS);
3565 }
3566 break;
3567 case Instruction::SetGT:
3568 switch (RHSCC) {
3569 default: assert(0 && "Unknown integer condition code!");
3570 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3571 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3572 return ReplaceInstUsesWith(I, LHS);
3573 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3574 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003575 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003576 }
3577 }
3578 }
3579 }
Chris Lattner3af10532006-05-05 06:39:07 +00003580
3581 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3582 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003583 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003584 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003585 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003586 // Only do this if the casts both really cause code to be generated.
3587 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3588 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003589 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3590 Op1C->getOperand(0),
3591 I.getName());
3592 InsertNewInstBefore(NewOp, I);
3593 return new CastInst(NewOp, I.getType());
3594 }
3595 }
3596
Chris Lattner15212982005-09-18 03:42:07 +00003597
Chris Lattner113f4f42002-06-25 16:13:24 +00003598 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003599}
3600
Chris Lattnerc2076352004-02-16 01:20:27 +00003601// XorSelf - Implements: X ^ X --> 0
3602struct XorSelf {
3603 Value *RHS;
3604 XorSelf(Value *rhs) : RHS(rhs) {}
3605 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3606 Instruction *apply(BinaryOperator &Xor) const {
3607 return &Xor;
3608 }
3609};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003610
3611
Chris Lattner113f4f42002-06-25 16:13:24 +00003612Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003613 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003615
Chris Lattner81a7a232004-10-16 18:11:37 +00003616 if (isa<UndefValue>(Op1))
3617 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3618
Chris Lattnerc2076352004-02-16 01:20:27 +00003619 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3620 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3621 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003622 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003623 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003624
3625 // See if we can simplify any instructions used by the instruction whose sole
3626 // purpose is to compute bits we don't care about.
3627 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003628 if (!isa<PackedType>(I.getType()) &&
3629 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003630 KnownZero, KnownOne))
3631 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003632
Chris Lattner97638592003-07-23 21:37:07 +00003633 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003634 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003635 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003636 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003637 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003638 return new SetCondInst(SCI->getInverseCondition(),
3639 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003640
Chris Lattner8f2f5982003-11-05 01:06:05 +00003641 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003642 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3643 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003644 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3645 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003646 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003647 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003648 }
Chris Lattner023a4832004-06-18 06:07:51 +00003649
3650 // ~(~X & Y) --> (X | ~Y)
3651 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3652 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3653 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3654 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003655 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003656 Op0I->getOperand(1)->getName()+".not");
3657 InsertNewInstBefore(NotY, I);
3658 return BinaryOperator::createOr(Op0NotVal, NotY);
3659 }
3660 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003661
Chris Lattner97638592003-07-23 21:37:07 +00003662 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003663 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003664 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003665 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003666 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3667 return BinaryOperator::createSub(
3668 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003669 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003670 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003671 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003672 } else if (Op0I->getOpcode() == Instruction::Or) {
3673 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3674 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3675 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3676 // Anything in both C1 and C2 is known to be zero, remove it from
3677 // NewRHS.
3678 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3679 NewRHS = ConstantExpr::getAnd(NewRHS,
3680 ConstantExpr::getNot(CommonBits));
3681 WorkList.push_back(Op0I);
3682 I.setOperand(0, Op0I->getOperand(0));
3683 I.setOperand(1, NewRHS);
3684 return &I;
3685 }
Chris Lattner97638592003-07-23 21:37:07 +00003686 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003687 }
Chris Lattner183b3362004-04-09 19:05:30 +00003688
3689 // Try to fold constant and into select arguments.
3690 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003691 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003692 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003693 if (isa<PHINode>(Op0))
3694 if (Instruction *NV = FoldOpIntoPhi(I))
3695 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003696 }
3697
Chris Lattnerbb74e222003-03-10 23:06:50 +00003698 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003699 if (X == Op1)
3700 return ReplaceInstUsesWith(I,
3701 ConstantIntegral::getAllOnesValue(I.getType()));
3702
Chris Lattnerbb74e222003-03-10 23:06:50 +00003703 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003704 if (X == Op0)
3705 return ReplaceInstUsesWith(I,
3706 ConstantIntegral::getAllOnesValue(I.getType()));
3707
Chris Lattnerdcd07922006-04-01 08:03:55 +00003708 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003709 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003710 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003711 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003712 I.swapOperands();
3713 std::swap(Op0, Op1);
3714 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003715 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003716 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003717 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003718 } else if (Op1I->getOpcode() == Instruction::Xor) {
3719 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3720 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3721 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3722 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003723 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3724 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3725 Op1I->swapOperands();
3726 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3727 I.swapOperands(); // Simplified below.
3728 std::swap(Op0, Op1);
3729 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003730 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003731
Chris Lattnerdcd07922006-04-01 08:03:55 +00003732 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003733 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003734 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003735 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003736 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003737 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3738 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003739 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003740 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003741 } else if (Op0I->getOpcode() == Instruction::Xor) {
3742 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3743 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3744 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3745 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003746 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3747 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3748 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003749 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3750 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003751 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3752 InsertNewInstBefore(N, I);
3753 return BinaryOperator::createAnd(N, Op1);
3754 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003755 }
3756
Chris Lattner3ac7c262003-08-13 20:16:26 +00003757 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3758 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3759 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3760 return R;
3761
Chris Lattner3af10532006-05-05 06:39:07 +00003762 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3763 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003764 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003765 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003766 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003767 // Only do this if the casts both really cause code to be generated.
3768 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3769 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003770 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3771 Op1C->getOperand(0),
3772 I.getName());
3773 InsertNewInstBefore(NewOp, I);
3774 return new CastInst(NewOp, I.getType());
3775 }
3776 }
3777
Chris Lattner113f4f42002-06-25 16:13:24 +00003778 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003779}
3780
Chris Lattner6862fbd2004-09-29 17:40:11 +00003781static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003782 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003783}
3784
3785/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3786/// overflowed for this type.
3787static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3788 ConstantInt *In2) {
3789 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3790
3791 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003792 return cast<ConstantInt>(Result)->getZExtValue() <
3793 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003794 if (isPositive(In1) != isPositive(In2))
3795 return false;
3796 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003797 return cast<ConstantInt>(Result)->getSExtValue() <
3798 cast<ConstantInt>(In1)->getSExtValue();
3799 return cast<ConstantInt>(Result)->getSExtValue() >
3800 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003801}
3802
Chris Lattner0798af32005-01-13 20:14:25 +00003803/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3804/// code necessary to compute the offset from the base pointer (without adding
3805/// in the base pointer). Return the result as a signed integer of intptr size.
3806static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3807 TargetData &TD = IC.getTargetData();
3808 gep_type_iterator GTI = gep_type_begin(GEP);
3809 const Type *UIntPtrTy = TD.getIntPtrType();
3810 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3811 Value *Result = Constant::getNullValue(SIntPtrTy);
3812
3813 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003814 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003815
Chris Lattner0798af32005-01-13 20:14:25 +00003816 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3817 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003818 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003819 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003820 SIntPtrTy);
3821 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3822 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003823 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003824 Scale = ConstantExpr::getMul(OpC, Scale);
3825 if (Constant *RC = dyn_cast<Constant>(Result))
3826 Result = ConstantExpr::getAdd(RC, Scale);
3827 else {
3828 // Emit an add instruction.
3829 Result = IC.InsertNewInstBefore(
3830 BinaryOperator::createAdd(Result, Scale,
3831 GEP->getName()+".offs"), I);
3832 }
3833 }
3834 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003835 // Convert to correct type.
3836 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3837 Op->getName()+".c"), I);
3838 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003839 // We'll let instcombine(mul) convert this to a shl if possible.
3840 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3841 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003842
3843 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003844 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003845 GEP->getName()+".offs"), I);
3846 }
3847 }
3848 return Result;
3849}
3850
3851/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3852/// else. At this point we know that the GEP is on the LHS of the comparison.
3853Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3854 Instruction::BinaryOps Cond,
3855 Instruction &I) {
3856 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003857
3858 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3859 if (isa<PointerType>(CI->getOperand(0)->getType()))
3860 RHS = CI->getOperand(0);
3861
Chris Lattner0798af32005-01-13 20:14:25 +00003862 Value *PtrBase = GEPLHS->getOperand(0);
3863 if (PtrBase == RHS) {
3864 // As an optimization, we don't actually have to compute the actual value of
3865 // OFFSET if this is a seteq or setne comparison, just return whether each
3866 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003867 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3868 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003869 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3870 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003871 bool EmitIt = true;
3872 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3873 if (isa<UndefValue>(C)) // undef index -> undef.
3874 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3875 if (C->isNullValue())
3876 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003877 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3878 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003879 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003880 return ReplaceInstUsesWith(I, // No comparison is needed here.
3881 ConstantBool::get(Cond == Instruction::SetNE));
3882 }
3883
3884 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003885 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003886 new SetCondInst(Cond, GEPLHS->getOperand(i),
3887 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3888 if (InVal == 0)
3889 InVal = Comp;
3890 else {
3891 InVal = InsertNewInstBefore(InVal, I);
3892 InsertNewInstBefore(Comp, I);
3893 if (Cond == Instruction::SetNE) // True if any are unequal
3894 InVal = BinaryOperator::createOr(InVal, Comp);
3895 else // True if all are equal
3896 InVal = BinaryOperator::createAnd(InVal, Comp);
3897 }
3898 }
3899 }
3900
3901 if (InVal)
3902 return InVal;
3903 else
3904 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3905 ConstantBool::get(Cond == Instruction::SetEQ));
3906 }
Chris Lattner0798af32005-01-13 20:14:25 +00003907
3908 // Only lower this if the setcc is the only user of the GEP or if we expect
3909 // the result to fold to a constant!
3910 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3911 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3912 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3913 return new SetCondInst(Cond, Offset,
3914 Constant::getNullValue(Offset->getType()));
3915 }
3916 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003917 // If the base pointers are different, but the indices are the same, just
3918 // compare the base pointer.
3919 if (PtrBase != GEPRHS->getOperand(0)) {
3920 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003921 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003922 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003923 if (IndicesTheSame)
3924 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3925 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3926 IndicesTheSame = false;
3927 break;
3928 }
3929
3930 // If all indices are the same, just compare the base pointers.
3931 if (IndicesTheSame)
3932 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3933 GEPRHS->getOperand(0));
3934
3935 // Otherwise, the base pointers are different and the indices are
3936 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003937 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003938 }
Chris Lattner0798af32005-01-13 20:14:25 +00003939
Chris Lattner81e84172005-01-13 22:25:21 +00003940 // If one of the GEPs has all zero indices, recurse.
3941 bool AllZeros = true;
3942 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3943 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3944 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3945 AllZeros = false;
3946 break;
3947 }
3948 if (AllZeros)
3949 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3950 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003951
3952 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003953 AllZeros = true;
3954 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3955 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3956 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3957 AllZeros = false;
3958 break;
3959 }
3960 if (AllZeros)
3961 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3962
Chris Lattner4fa89822005-01-14 00:20:05 +00003963 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3964 // If the GEPs only differ by one index, compare it.
3965 unsigned NumDifferences = 0; // Keep track of # differences.
3966 unsigned DiffOperand = 0; // The operand that differs.
3967 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3968 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003969 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3970 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003971 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003972 NumDifferences = 2;
3973 break;
3974 } else {
3975 if (NumDifferences++) break;
3976 DiffOperand = i;
3977 }
3978 }
3979
3980 if (NumDifferences == 0) // SAME GEP?
3981 return ReplaceInstUsesWith(I, // No comparison is needed here.
3982 ConstantBool::get(Cond == Instruction::SetEQ));
3983 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003984 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3985 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003986
3987 // Convert the operands to signed values to make sure to perform a
3988 // signed comparison.
3989 const Type *NewTy = LHSV->getType()->getSignedVersion();
3990 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003991 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00003992 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003993 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00003994 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003995 }
3996 }
3997
Chris Lattner0798af32005-01-13 20:14:25 +00003998 // Only lower this if the setcc is the only user of the GEP or if we expect
3999 // the result to fold to a constant!
4000 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4001 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4002 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4003 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4004 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4005 return new SetCondInst(Cond, L, R);
4006 }
4007 }
4008 return 0;
4009}
4010
4011
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004012Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004013 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4015 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004016
4017 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004018 if (Op0 == Op1)
4019 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004020
Chris Lattner81a7a232004-10-16 18:11:37 +00004021 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4022 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4023
Chris Lattner15ff1e12004-11-14 07:33:16 +00004024 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4025 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004026 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4027 isa<ConstantPointerNull>(Op0)) &&
4028 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004029 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004030 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4031
4032 // setcc's with boolean values can always be turned into bitwise operations
4033 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004034 switch (I.getOpcode()) {
4035 default: assert(0 && "Invalid setcc instruction!");
4036 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004037 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004038 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004039 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004040 }
Chris Lattner4456da62004-08-11 00:50:51 +00004041 case Instruction::SetNE:
4042 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004043
Chris Lattner4456da62004-08-11 00:50:51 +00004044 case Instruction::SetGT:
4045 std::swap(Op0, Op1); // Change setgt -> setlt
4046 // FALL THROUGH
4047 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4048 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4049 InsertNewInstBefore(Not, I);
4050 return BinaryOperator::createAnd(Not, Op1);
4051 }
4052 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004053 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004054 // FALL THROUGH
4055 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4056 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4057 InsertNewInstBefore(Not, I);
4058 return BinaryOperator::createOr(Not, Op1);
4059 }
4060 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004061 }
4062
Chris Lattner2dd01742004-06-09 04:24:29 +00004063 // See if we are doing a comparison between a constant and an instruction that
4064 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004066 // Check to see if we are comparing against the minimum or maximum value...
4067 if (CI->isMinValue()) {
4068 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004069 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004070 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004071 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004072 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4073 return BinaryOperator::createSetEQ(Op0, Op1);
4074 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4075 return BinaryOperator::createSetNE(Op0, Op1);
4076
4077 } else if (CI->isMaxValue()) {
4078 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004079 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004080 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004081 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004082 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4083 return BinaryOperator::createSetEQ(Op0, Op1);
4084 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4085 return BinaryOperator::createSetNE(Op0, Op1);
4086
4087 // Comparing against a value really close to min or max?
4088 } else if (isMinValuePlusOne(CI)) {
4089 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4090 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4091 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4092 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4093
4094 } else if (isMaxValueMinusOne(CI)) {
4095 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4096 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4097 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4098 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4099 }
4100
4101 // If we still have a setle or setge instruction, turn it into the
4102 // appropriate setlt or setgt instruction. Since the border cases have
4103 // already been handled above, this requires little checking.
4104 //
4105 if (I.getOpcode() == Instruction::SetLE)
4106 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4107 if (I.getOpcode() == Instruction::SetGE)
4108 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4109
Chris Lattneree0f2802006-02-12 02:07:56 +00004110
4111 // See if we can fold the comparison based on bits known to be zero or one
4112 // in the input.
4113 uint64_t KnownZero, KnownOne;
4114 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4115 KnownZero, KnownOne, 0))
4116 return &I;
4117
4118 // Given the known and unknown bits, compute a range that the LHS could be
4119 // in.
4120 if (KnownOne | KnownZero) {
4121 if (Ty->isUnsigned()) { // Unsigned comparison.
4122 uint64_t Min, Max;
4123 uint64_t RHSVal = CI->getZExtValue();
4124 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4125 Min, Max);
4126 switch (I.getOpcode()) { // LE/GE have been folded already.
4127 default: assert(0 && "Unknown setcc opcode!");
4128 case Instruction::SetEQ:
4129 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004130 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004131 break;
4132 case Instruction::SetNE:
4133 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004134 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004135 break;
4136 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004137 if (Max < RHSVal)
4138 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4139 if (Min > RHSVal)
4140 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004141 break;
4142 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004143 if (Min > RHSVal)
4144 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4145 if (Max < RHSVal)
4146 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004147 break;
4148 }
4149 } else { // Signed comparison.
4150 int64_t Min, Max;
4151 int64_t RHSVal = CI->getSExtValue();
4152 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4153 Min, Max);
4154 switch (I.getOpcode()) { // LE/GE have been folded already.
4155 default: assert(0 && "Unknown setcc opcode!");
4156 case Instruction::SetEQ:
4157 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004158 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004159 break;
4160 case Instruction::SetNE:
4161 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004162 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004163 break;
4164 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004165 if (Max < RHSVal)
4166 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4167 if (Min > RHSVal)
4168 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004169 break;
4170 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004171 if (Min > RHSVal)
4172 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4173 if (Max < RHSVal)
4174 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004175 break;
4176 }
4177 }
4178 }
4179
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004180 // Since the RHS is a constantInt (CI), if the left hand side is an
4181 // instruction, see if that instruction also has constants so that the
4182 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004183 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004184 switch (LHSI->getOpcode()) {
4185 case Instruction::And:
4186 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4187 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004188 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4189
4190 // If an operand is an AND of a truncating cast, we can widen the
4191 // and/compare to be the input width without changing the value
4192 // produced, eliminating a cast.
4193 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4194 // We can do this transformation if either the AND constant does not
4195 // have its sign bit set or if it is an equality comparison.
4196 // Extending a relational comparison when we're checking the sign
4197 // bit would not work.
4198 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4199 (I.isEquality() ||
4200 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4201 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4202 ConstantInt *NewCST;
4203 ConstantInt *NewCI;
4204 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004205 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004206 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004207 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004208 CI->getZExtValue());
4209 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004210 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004211 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004212 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004213 CI->getZExtValue());
4214 }
4215 Instruction *NewAnd =
4216 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4217 LHSI->getName());
4218 InsertNewInstBefore(NewAnd, I);
4219 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4220 }
4221 }
4222
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004223 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4224 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4225 // happens a LOT in code produced by the C front-end, for bitfield
4226 // access.
4227 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004228
4229 // Check to see if there is a noop-cast between the shift and the and.
4230 if (!Shift) {
4231 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4232 if (CI->getOperand(0)->getType()->isIntegral() &&
4233 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4234 CI->getType()->getPrimitiveSizeInBits())
4235 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4236 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004237
Reid Spencere0fc4df2006-10-20 07:07:24 +00004238 ConstantInt *ShAmt;
4239 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004240 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4241 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004242
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004243 // We can fold this as long as we can't shift unknown bits
4244 // into the mask. This can only happen with signed shift
4245 // rights, as they sign-extend.
4246 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004247 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004248 if (!CanFold) {
4249 // To test for the bad case of the signed shr, see if any
4250 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004251 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004252 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4253
Reid Spencere0fc4df2006-10-20 07:07:24 +00004254 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004255 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004256 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4257 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004258 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4259 CanFold = true;
4260 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004261
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004262 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004263 Constant *NewCst;
4264 if (Shift->getOpcode() == Instruction::Shl)
4265 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4266 else
4267 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004268
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004269 // Check to see if we are shifting out any of the bits being
4270 // compared.
4271 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4272 // If we shifted bits out, the fold is not going to work out.
4273 // As a special case, check to see if this means that the
4274 // result is always true or false now.
4275 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004276 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004277 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004278 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004279 } else {
4280 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004281 Constant *NewAndCST;
4282 if (Shift->getOpcode() == Instruction::Shl)
4283 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4284 else
4285 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4286 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004287 if (AndTy == Ty)
4288 LHSI->setOperand(0, Shift->getOperand(0));
4289 else {
4290 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4291 *Shift);
4292 LHSI->setOperand(0, NewCast);
4293 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004294 WorkList.push_back(Shift); // Shift is dead.
4295 AddUsesToWorkList(I);
4296 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004297 }
4298 }
Chris Lattner35167c32004-06-09 07:59:58 +00004299 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004300
4301 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4302 // preferable because it allows the C<<Y expression to be hoisted out
4303 // of a loop if Y is invariant and X is not.
4304 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004305 I.isEquality() && !Shift->isArithmeticShift() &&
4306 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004307 // Compute C << Y.
4308 Value *NS;
4309 if (Shift->getOpcode() == Instruction::Shr) {
4310 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4311 "tmp");
4312 } else {
4313 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004314 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004315 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004316 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004317 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004318 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4319 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004320 }
4321 InsertNewInstBefore(cast<Instruction>(NS), I);
4322
4323 // If C's sign doesn't agree with the and, insert a cast now.
4324 if (NS->getType() != LHSI->getType())
4325 NS = InsertCastBefore(NS, LHSI->getType(), I);
4326
4327 Value *ShiftOp = Shift->getOperand(0);
4328 if (ShiftOp->getType() != LHSI->getType())
4329 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4330
4331 // Compute X & (C << Y).
4332 Instruction *NewAnd =
4333 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4334 InsertNewInstBefore(NewAnd, I);
4335
4336 I.setOperand(0, NewAnd);
4337 return &I;
4338 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004339 }
4340 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004341
Chris Lattner272d5ca2004-09-28 18:22:15 +00004342 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004343 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004344 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004345 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4346
4347 // Check that the shift amount is in range. If not, don't perform
4348 // undefined shifts. When the shift is visited it will be
4349 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004350 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004351 break;
4352
Chris Lattner272d5ca2004-09-28 18:22:15 +00004353 // If we are comparing against bits always shifted out, the
4354 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004355 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004356 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4357 if (Comp != CI) {// Comparing against a bit that we know is zero.
4358 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4359 Constant *Cst = ConstantBool::get(IsSetNE);
4360 return ReplaceInstUsesWith(I, Cst);
4361 }
4362
4363 if (LHSI->hasOneUse()) {
4364 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004365 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004366 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4367
4368 Constant *Mask;
4369 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004370 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004371 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004372 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004373 } else {
4374 Mask = ConstantInt::getAllOnesValue(CI->getType());
4375 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004376
Chris Lattner272d5ca2004-09-28 18:22:15 +00004377 Instruction *AndI =
4378 BinaryOperator::createAnd(LHSI->getOperand(0),
4379 Mask, LHSI->getName()+".mask");
4380 Value *And = InsertNewInstBefore(AndI, I);
4381 return new SetCondInst(I.getOpcode(), And,
4382 ConstantExpr::getUShr(CI, ShAmt));
4383 }
4384 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004385 }
4386 break;
4387
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004388 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004389 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004390 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004391 // Check that the shift amount is in range. If not, don't perform
4392 // undefined shifts. When the shift is visited it will be
4393 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004394 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004395 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004396 break;
4397
Chris Lattner1023b872004-09-27 16:18:50 +00004398 // If we are comparing against bits always shifted out, the
4399 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004400 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004401 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004402
Chris Lattner1023b872004-09-27 16:18:50 +00004403 if (Comp != CI) {// Comparing against a bit that we know is zero.
4404 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4405 Constant *Cst = ConstantBool::get(IsSetNE);
4406 return ReplaceInstUsesWith(I, Cst);
4407 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004408
Chris Lattner1023b872004-09-27 16:18:50 +00004409 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004410 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004411
Chris Lattner1023b872004-09-27 16:18:50 +00004412 // Otherwise strength reduce the shift into an and.
4413 uint64_t Val = ~0ULL; // All ones.
4414 Val <<= ShAmtVal; // Shift over to the right spot.
4415
4416 Constant *Mask;
4417 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004418 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004419 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004420 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004421 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004422 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004423
Chris Lattner1023b872004-09-27 16:18:50 +00004424 Instruction *AndI =
4425 BinaryOperator::createAnd(LHSI->getOperand(0),
4426 Mask, LHSI->getName()+".mask");
4427 Value *And = InsertNewInstBefore(AndI, I);
4428 return new SetCondInst(I.getOpcode(), And,
4429 ConstantExpr::getShl(CI, ShAmt));
4430 }
Chris Lattner1023b872004-09-27 16:18:50 +00004431 }
4432 }
4433 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004434
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004435 case Instruction::SDiv:
4436 case Instruction::UDiv:
4437 // Fold: setcc ([us]div X, C1), C2 -> range test
4438 // Fold this div into the comparison, producing a range check.
4439 // Determine, based on the divide type, what the range is being
4440 // checked. If there is an overflow on the low or high side, remember
4441 // it, otherwise compute the range [low, hi) bounding the new value.
4442 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004443 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004444 // FIXME: If the operand types don't match the type of the divide
4445 // then don't attempt this transform. The code below doesn't have the
4446 // logic to deal with a signed divide and an unsigned compare (and
4447 // vice versa). This is because (x /s C1) <s C2 produces different
4448 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4449 // (x /u C1) <u C2. Simply casting the operands and result won't
4450 // work. :( The if statement below tests that condition and bails
4451 // if it finds it.
4452 const Type* DivRHSTy = DivRHS->getType();
4453 unsigned DivOpCode = LHSI->getOpcode();
4454 if (I.isEquality() &&
4455 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4456 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4457 break;
4458
4459 // Initialize the variables that will indicate the nature of the
4460 // range check.
4461 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004462 ConstantInt *LoBound = 0, *HiBound = 0;
4463
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004464 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4465 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4466 // C2 (CI). By solving for X we can turn this into a range check
4467 // instead of computing a divide.
4468 ConstantInt *Prod =
4469 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004470
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004471 // Determine if the product overflows by seeing if the product is
4472 // not equal to the divide. Make sure we do the same kind of divide
4473 // as in the LHS instruction that we're folding.
4474 bool ProdOV = !DivRHS->isNullValue() &&
4475 (DivOpCode == Instruction::SDiv ?
4476 ConstantExpr::getSDiv(Prod, DivRHS) :
4477 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4478
4479 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004480 Instruction::BinaryOps Opcode = I.getOpcode();
4481
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004482 if (DivRHS->isNullValue()) {
4483 // Don't hack on divide by zeros!
4484 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004485 LoBound = Prod;
4486 LoOverflow = ProdOV;
4487 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004488 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004489 if (CI->isNullValue()) { // (X / pos) op 0
4490 // Can't overflow.
4491 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4492 HiBound = DivRHS;
4493 } else if (isPositive(CI)) { // (X / pos) op pos
4494 LoBound = Prod;
4495 LoOverflow = ProdOV;
4496 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4497 } else { // (X / pos) op neg
4498 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4499 LoOverflow = AddWithOverflow(LoBound, Prod,
4500 cast<ConstantInt>(DivRHSH));
4501 HiBound = Prod;
4502 HiOverflow = ProdOV;
4503 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004504 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004505 if (CI->isNullValue()) { // (X / neg) op 0
4506 LoBound = AddOne(DivRHS);
4507 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004508 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004509 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004510 } else if (isPositive(CI)) { // (X / neg) op pos
4511 HiOverflow = LoOverflow = ProdOV;
4512 if (!LoOverflow)
4513 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4514 HiBound = AddOne(Prod);
4515 } else { // (X / neg) op neg
4516 LoBound = Prod;
4517 LoOverflow = HiOverflow = ProdOV;
4518 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4519 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004520
Chris Lattnera92af962004-10-11 19:40:04 +00004521 // Dividing by a negate swaps the condition.
4522 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004523 }
4524
4525 if (LoBound) {
4526 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004527 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004528 default: assert(0 && "Unhandled setcc opcode!");
4529 case Instruction::SetEQ:
4530 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004531 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004532 else if (HiOverflow)
4533 return new SetCondInst(Instruction::SetGE, X, LoBound);
4534 else if (LoOverflow)
4535 return new SetCondInst(Instruction::SetLT, X, HiBound);
4536 else
4537 return InsertRangeTest(X, LoBound, HiBound, true, I);
4538 case Instruction::SetNE:
4539 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004540 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004541 else if (HiOverflow)
4542 return new SetCondInst(Instruction::SetLT, X, LoBound);
4543 else if (LoOverflow)
4544 return new SetCondInst(Instruction::SetGE, X, HiBound);
4545 else
4546 return InsertRangeTest(X, LoBound, HiBound, false, I);
4547 case Instruction::SetLT:
4548 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004549 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004550 return new SetCondInst(Instruction::SetLT, X, LoBound);
4551 case Instruction::SetGT:
4552 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004553 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004554 return new SetCondInst(Instruction::SetGE, X, HiBound);
4555 }
4556 }
4557 }
4558 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004559 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004560
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004561 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004562 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004563 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4564
Reid Spencere0fc4df2006-10-20 07:07:24 +00004565 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4566 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004567 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4568 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004569#if 0
4570 case Instruction::SRem:
4571 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4572 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4573 BO->hasOneUse()) {
4574 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4575 if (V > 1 && isPowerOf2_64(V)) {
4576 Value *NewRem = InsertNewInstBefore(
4577 BinaryOperator::createURem(BO->getOperand(0),
4578 BO->getOperand(1),
4579 BO->getName()), I);
4580 return BinaryOperator::create(
4581 I.getOpcode(), NewRem,
4582 Constant::getNullValue(NewRem->getType()));
4583 }
4584 }
4585 break;
4586#endif
4587
Chris Lattner23b47b62004-07-06 07:38:18 +00004588 case Instruction::Rem:
4589 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004590 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4591 BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4592 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4593 if (V > 1 && isPowerOf2_64(V)) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004594 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004595 const Type *UTy = BO->getType()->getUnsignedVersion();
4596 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4597 UTy, "tmp"), I);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004598 Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
Chris Lattner23b47b62004-07-06 07:38:18 +00004599 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4600 RHSCst, BO->getName()), I);
4601 return BinaryOperator::create(I.getOpcode(), NewRem,
4602 Constant::getNullValue(UTy));
4603 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004604 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004605 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004606 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004607 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4608 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004609 if (BO->hasOneUse())
4610 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4611 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004612 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004613 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4614 // efficiently invertible, or if the add has just this one use.
4615 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004616
Chris Lattnerc992add2003-08-13 05:33:12 +00004617 if (Value *NegVal = dyn_castNegVal(BOp1))
4618 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4619 else if (Value *NegVal = dyn_castNegVal(BOp0))
4620 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004621 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004622 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4623 BO->setName("");
4624 InsertNewInstBefore(Neg, I);
4625 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4626 }
4627 }
4628 break;
4629 case Instruction::Xor:
4630 // For the xor case, we can xor two constants together, eliminating
4631 // the explicit xor.
4632 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4633 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004634 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004635
4636 // FALLTHROUGH
4637 case Instruction::Sub:
4638 // Replace (([sub|xor] A, B) != 0) with (A != B)
4639 if (CI->isNullValue())
4640 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4641 BO->getOperand(1));
4642 break;
4643
4644 case Instruction::Or:
4645 // If bits are being or'd in that are not present in the constant we
4646 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004647 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004648 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004649 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004650 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004651 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004652 break;
4653
4654 case Instruction::And:
4655 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004656 // If bits are being compared against that are and'd out, then the
4657 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004658 if (!ConstantExpr::getAnd(CI,
4659 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004660 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004661
Chris Lattner35167c32004-06-09 07:59:58 +00004662 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004663 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004664 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4665 Instruction::SetNE, Op0,
4666 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004667
Chris Lattnerc992add2003-08-13 05:33:12 +00004668 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4669 // to be a signed value as appropriate.
4670 if (isSignBit(BOC)) {
4671 Value *X = BO->getOperand(0);
4672 // If 'X' is not signed, insert a cast now...
4673 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004674 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004675 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004676 }
4677 return new SetCondInst(isSetNE ? Instruction::SetLT :
4678 Instruction::SetGE, X,
4679 Constant::getNullValue(X->getType()));
4680 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004681
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004682 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004683 if (CI->isNullValue() && isHighOnes(BOC)) {
4684 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004685 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004686
4687 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004688 if (NegX->getType()->isSigned()) {
4689 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4690 X = InsertCastBefore(X, DestTy, I);
4691 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004692 }
4693
4694 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004695 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004696 }
4697
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004698 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004699 default: break;
4700 }
4701 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004702 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004703 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004704 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4705 Value *CastOp = Cast->getOperand(0);
4706 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004707 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004708 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004709 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004710 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004711 "Source and destination signednesses should differ!");
4712 if (Cast->getType()->isSigned()) {
4713 // If this is a signed comparison, check for comparisons in the
4714 // vicinity of zero.
4715 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4716 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004717 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004718 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004719 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004720 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004721 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004722 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004723 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004724 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004725 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004726 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004727 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004728 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004729 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004730 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004731 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004732 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004733 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004734 return BinaryOperator::createSetLT(CastOp,
4735 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004736 }
4737 }
4738 }
Chris Lattnere967b342003-06-04 05:10:11 +00004739 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004740 }
4741
Chris Lattner77c32c32005-04-23 15:31:55 +00004742 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4743 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4744 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4745 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004746 case Instruction::GetElementPtr:
4747 if (RHSC->isNullValue()) {
4748 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4749 bool isAllZeros = true;
4750 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4751 if (!isa<Constant>(LHSI->getOperand(i)) ||
4752 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4753 isAllZeros = false;
4754 break;
4755 }
4756 if (isAllZeros)
4757 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4758 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4759 }
4760 break;
4761
Chris Lattner77c32c32005-04-23 15:31:55 +00004762 case Instruction::PHI:
4763 if (Instruction *NV = FoldOpIntoPhi(I))
4764 return NV;
4765 break;
4766 case Instruction::Select:
4767 // If either operand of the select is a constant, we can fold the
4768 // comparison into the select arms, which will cause one to be
4769 // constant folded and the select turned into a bitwise or.
4770 Value *Op1 = 0, *Op2 = 0;
4771 if (LHSI->hasOneUse()) {
4772 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4773 // Fold the known value into the constant operand.
4774 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4775 // Insert a new SetCC of the other select operand.
4776 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4777 LHSI->getOperand(2), RHSC,
4778 I.getName()), I);
4779 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4780 // Fold the known value into the constant operand.
4781 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4782 // Insert a new SetCC of the other select operand.
4783 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4784 LHSI->getOperand(1), RHSC,
4785 I.getName()), I);
4786 }
4787 }
Jeff Cohen82639852005-04-23 21:38:35 +00004788
Chris Lattner77c32c32005-04-23 15:31:55 +00004789 if (Op1)
4790 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4791 break;
4792 }
4793 }
4794
Chris Lattner0798af32005-01-13 20:14:25 +00004795 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4796 if (User *GEP = dyn_castGetElementPtr(Op0))
4797 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4798 return NI;
4799 if (User *GEP = dyn_castGetElementPtr(Op1))
4800 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4801 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4802 return NI;
4803
Chris Lattner16930792003-11-03 04:25:02 +00004804 // Test to see if the operands of the setcc are casted versions of other
4805 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004806 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4807 Value *CastOp0 = CI->getOperand(0);
4808 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004809 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004810 // We keep moving the cast from the left operand over to the right
4811 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004812 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004813
Chris Lattner16930792003-11-03 04:25:02 +00004814 // If operand #1 is a cast instruction, see if we can eliminate it as
4815 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004816 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4817 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004818 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004819 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004820
Chris Lattner16930792003-11-03 04:25:02 +00004821 // If Op1 is a constant, we can fold the cast into the constant.
4822 if (Op1->getType() != Op0->getType())
4823 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4824 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4825 } else {
4826 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004827 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004828 }
4829 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4830 }
4831
Chris Lattner6444c372003-11-03 05:17:03 +00004832 // Handle the special case of: setcc (cast bool to X), <cst>
4833 // This comes up when you have code like
4834 // int X = A < B;
4835 // if (X) ...
4836 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004837 // with a constant or another cast from the same type.
4838 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4839 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4840 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004841 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004842
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004843 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004844 Value *A, *B;
4845 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4846 (A == Op1 || B == Op1)) {
4847 // (A^B) == A -> B == 0
4848 Value *OtherVal = A == Op1 ? B : A;
4849 return BinaryOperator::create(I.getOpcode(), OtherVal,
4850 Constant::getNullValue(A->getType()));
4851 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4852 (A == Op0 || B == Op0)) {
4853 // A == (A^B) -> B == 0
4854 Value *OtherVal = A == Op0 ? B : A;
4855 return BinaryOperator::create(I.getOpcode(), OtherVal,
4856 Constant::getNullValue(A->getType()));
4857 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4858 // (A-B) == A -> B == 0
4859 return BinaryOperator::create(I.getOpcode(), B,
4860 Constant::getNullValue(B->getType()));
4861 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4862 // A == (A-B) -> B == 0
4863 return BinaryOperator::create(I.getOpcode(), B,
4864 Constant::getNullValue(B->getType()));
4865 }
4866 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004867 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004868}
4869
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004870// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4871// We only handle extending casts so far.
4872//
4873Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4874 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4875 const Type *SrcTy = LHSCIOp->getType();
4876 const Type *DestTy = SCI.getOperand(0)->getType();
4877 Value *RHSCIOp;
4878
4879 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004880 return 0;
4881
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004882 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4883 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4884 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4885
4886 // Is this a sign or zero extension?
4887 bool isSignSrc = SrcTy->isSigned();
4888 bool isSignDest = DestTy->isSigned();
4889
4890 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4891 // Not an extension from the same type?
4892 RHSCIOp = CI->getOperand(0);
4893 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4894 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4895 // Compute the constant that would happen if we truncated to SrcTy then
4896 // reextended to DestTy.
4897 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4898
4899 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004900 // Make sure that src sign and dest sign match. For example,
4901 //
4902 // %A = cast short %X to uint
4903 // %B = setgt uint %A, 1330
4904 //
Devang Patel88afd002006-10-19 19:21:36 +00004905 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004906 //
4907 // %B = setgt short %X, 1330
4908 //
4909 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004910 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4911 // OR operation is EQ/NE.
4912 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00004913 RHSCIOp = Res;
4914 else
4915 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004916 } else {
4917 // If the value cannot be represented in the shorter type, we cannot emit
4918 // a simple comparison.
4919 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004920 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004921 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004922 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004923
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004924 // Evaluate the comparison for LT.
4925 Value *Result;
4926 if (DestTy->isSigned()) {
4927 // We're performing a signed comparison.
4928 if (isSignSrc) {
4929 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004930 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004931 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004932 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00004933 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004934 } else {
4935 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004936 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004937 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004938 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004939 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004940 }
4941 } else {
4942 // We're performing an unsigned comparison.
4943 if (!isSignSrc) {
4944 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004945 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004946 } else {
4947 // We're performing an unsigned comp with a sign extended value.
4948 // This is true if the input is >= 0. [aka >s -1]
4949 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4950 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4951 NegOne, SCI.getName()), SCI);
4952 }
Reid Spencer279fa252004-11-28 21:31:15 +00004953 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004954
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004955 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004956 if (SCI.getOpcode() == Instruction::SetLT) {
4957 return ReplaceInstUsesWith(SCI, Result);
4958 } else {
4959 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4960 if (Constant *CI = dyn_cast<Constant>(Result))
4961 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4962 else
4963 return BinaryOperator::createNot(Result);
4964 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004965 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004966 } else {
4967 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004968 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004969
Chris Lattner252a8452005-06-16 03:00:08 +00004970 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004971 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4972}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004973
Chris Lattnere8d6c602003-03-10 19:16:08 +00004974Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004975 assert(I.getOperand(1)->getType() == Type::UByteTy);
4976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004977 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004978
4979 // shl X, 0 == X and shr X, 0 == X
4980 // shl 0, X == 0 and shr 0, X == 0
4981 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004982 Op0 == Constant::getNullValue(Op0->getType()))
4983 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004984
Chris Lattner81a7a232004-10-16 18:11:37 +00004985 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4986 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004987 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004988 else // undef << X -> 0 AND undef >>u X -> 0
4989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4990 }
4991 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004992 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4994 else
4995 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4996 }
4997
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004998 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4999 if (!isLeftShift)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005000 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner5dee3b22006-10-20 18:20:21 +00005001 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005002 return ReplaceInstUsesWith(I, CSI);
5003
Chris Lattner183b3362004-04-09 19:05:30 +00005004 // Try to fold constant and into select arguments.
5005 if (isa<Constant>(Op0))
5006 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005007 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005008 return R;
5009
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005010 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005011 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005012 if (MaskedValueIsZero(Op0,
5013 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005014 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5015 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5016 I.getName()), I);
5017 return new CastInst(V, I.getType());
5018 }
5019 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005020
Reid Spencere0fc4df2006-10-20 07:07:24 +00005021 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5022 if (CUI->getType()->isUnsigned())
5023 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5024 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005025 return 0;
5026}
5027
Reid Spencere0fc4df2006-10-20 07:07:24 +00005028Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005029 ShiftInst &I) {
5030 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00005031 bool isSignedShift = Op0->getType()->isSigned();
5032 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005033
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005034 // See if we can simplify any instructions used by the instruction whose sole
5035 // purpose is to compute bits we don't care about.
5036 uint64_t KnownZero, KnownOne;
5037 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5038 KnownZero, KnownOne))
5039 return &I;
5040
Chris Lattner14553932006-01-06 07:12:35 +00005041 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5042 // of a signed value.
5043 //
5044 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005045 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005046 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005047 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5048 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005049 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005050 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005051 }
Chris Lattner14553932006-01-06 07:12:35 +00005052 }
5053
5054 // ((X*C1) << C2) == (X * (C1 << C2))
5055 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5056 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5057 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5058 return BinaryOperator::createMul(BO->getOperand(0),
5059 ConstantExpr::getShl(BOOp, Op1));
5060
5061 // Try to fold constant and into select arguments.
5062 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5063 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5064 return R;
5065 if (isa<PHINode>(Op0))
5066 if (Instruction *NV = FoldOpIntoPhi(I))
5067 return NV;
5068
5069 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005070 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5071 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5072 Value *V1, *V2;
5073 ConstantInt *CC;
5074 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005075 default: break;
5076 case Instruction::Add:
5077 case Instruction::And:
5078 case Instruction::Or:
5079 case Instruction::Xor:
5080 // These operators commute.
5081 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005082 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5083 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005084 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005085 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005086 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005087 Op0BO->getName());
5088 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005089 Instruction *X =
5090 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5091 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005092 InsertNewInstBefore(X, I); // (X + (Y << C))
5093 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005094 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005095 return BinaryOperator::createAnd(X, C2);
5096 }
Chris Lattner14553932006-01-06 07:12:35 +00005097
Chris Lattner797dee72005-09-18 06:30:59 +00005098 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5099 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5100 match(Op0BO->getOperand(1),
5101 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005102 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005103 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005104 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005105 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005106 Op0BO->getName());
5107 InsertNewInstBefore(YS, I); // (Y << C)
5108 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005109 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005110 V1->getName()+".mask");
5111 InsertNewInstBefore(XM, I); // X & (CC << C)
5112
5113 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5114 }
Chris Lattner14553932006-01-06 07:12:35 +00005115
Chris Lattner797dee72005-09-18 06:30:59 +00005116 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005117 case Instruction::Sub:
5118 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005119 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5120 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005121 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005122 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005123 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005124 Op0BO->getName());
5125 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005126 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005127 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005128 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005129 InsertNewInstBefore(X, I); // (X + (Y << C))
5130 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005131 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005132 return BinaryOperator::createAnd(X, C2);
5133 }
Chris Lattner14553932006-01-06 07:12:35 +00005134
Chris Lattner1df0e982006-05-31 21:14:00 +00005135 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005136 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5137 match(Op0BO->getOperand(0),
5138 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005139 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005140 cast<BinaryOperator>(Op0BO->getOperand(0))
5141 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005142 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005143 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005144 Op0BO->getName());
5145 InsertNewInstBefore(YS, I); // (Y << C)
5146 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005147 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005148 V1->getName()+".mask");
5149 InsertNewInstBefore(XM, I); // X & (CC << C)
5150
Chris Lattner1df0e982006-05-31 21:14:00 +00005151 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005152 }
Chris Lattner14553932006-01-06 07:12:35 +00005153
Chris Lattner27cb9db2005-09-18 05:12:10 +00005154 break;
Chris Lattner14553932006-01-06 07:12:35 +00005155 }
5156
5157
5158 // If the operand is an bitwise operator with a constant RHS, and the
5159 // shift is the only use, we can pull it out of the shift.
5160 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5161 bool isValid = true; // Valid only for And, Or, Xor
5162 bool highBitSet = false; // Transform if high bit of constant set?
5163
5164 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005165 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005166 case Instruction::Add:
5167 isValid = isLeftShift;
5168 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005169 case Instruction::Or:
5170 case Instruction::Xor:
5171 highBitSet = false;
5172 break;
5173 case Instruction::And:
5174 highBitSet = true;
5175 break;
Chris Lattner14553932006-01-06 07:12:35 +00005176 }
5177
5178 // If this is a signed shift right, and the high bit is modified
5179 // by the logical operation, do not perform the transformation.
5180 // The highBitSet boolean indicates the value of the high bit of
5181 // the constant which would cause it to be modified for this
5182 // operation.
5183 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005184 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005185 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005186 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5187 }
5188
5189 if (isValid) {
5190 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5191
5192 Instruction *NewShift =
5193 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5194 Op0BO->getName());
5195 Op0BO->setName("");
5196 InsertNewInstBefore(NewShift, I);
5197
5198 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5199 NewRHS);
5200 }
5201 }
5202 }
5203 }
5204
Chris Lattnereb372a02006-01-06 07:52:12 +00005205 // Find out if this is a shift of a shift by a constant.
5206 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005207 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005208 ShiftOp = Op0SI;
5209 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5210 // If this is a noop-integer case of a shift instruction, use the shift.
5211 if (CI->getOperand(0)->getType()->isInteger() &&
5212 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5213 CI->getType()->getPrimitiveSizeInBits() &&
5214 isa<ShiftInst>(CI->getOperand(0))) {
5215 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5216 }
5217 }
5218
Reid Spencere0fc4df2006-10-20 07:07:24 +00005219 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005220 // Find the operands and properties of the input shift. Note that the
5221 // signedness of the input shift may differ from the current shift if there
5222 // is a noop cast between the two.
5223 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5224 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005225 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005226
Reid Spencere0fc4df2006-10-20 07:07:24 +00005227 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005228
Reid Spencere0fc4df2006-10-20 07:07:24 +00005229 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5230 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005231
5232 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5233 if (isLeftShift == isShiftOfLeftShift) {
5234 // Do not fold these shifts if the first one is signed and the second one
5235 // is unsigned and this is a right shift. Further, don't do any folding
5236 // on them.
5237 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5238 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005239
Chris Lattnereb372a02006-01-06 07:52:12 +00005240 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5241 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5242 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005243
Chris Lattnereb372a02006-01-06 07:52:12 +00005244 Value *Op = ShiftOp->getOperand(0);
5245 if (isShiftOfSignedShift != isSignedShift)
5246 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5247 return new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005248 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnereb372a02006-01-06 07:52:12 +00005249 }
5250
5251 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5252 // signed types, we can only support the (A >> c1) << c2 configuration,
5253 // because it can not turn an arbitrary bit of A into a sign bit.
5254 if (isUnsignedShift || isLeftShift) {
5255 // Calculate bitmask for what gets shifted off the edge.
5256 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5257 if (isLeftShift)
5258 C = ConstantExpr::getShl(C, ShiftAmt1C);
5259 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005260 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005261
5262 Value *Op = ShiftOp->getOperand(0);
5263 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer00c482b2006-10-26 19:19:06 +00005264 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005265
5266 Instruction *Mask =
5267 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5268 InsertNewInstBefore(Mask, I);
5269
5270 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005271 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005272 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005273 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005274 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005275 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005276 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5277 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5278 // Make sure to emit an unsigned shift right, not a signed one.
5279 Mask = InsertNewInstBefore(new CastInst(Mask,
5280 Mask->getType()->getUnsignedVersion(),
5281 Op->getName()), I);
5282 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005283 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005284 InsertNewInstBefore(Mask, I);
5285 return new CastInst(Mask, I.getType());
5286 } else {
5287 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005288 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005289 }
5290 } else {
5291 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005292 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005293 Instruction *Shift =
5294 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005295 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005296 InsertNewInstBefore(Shift, I);
5297
5298 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5299 C = ConstantExpr::getShl(C, Op1);
5300 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5301 InsertNewInstBefore(Mask, I);
5302 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005303 }
5304 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005305 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005306 // this case, C1 == C2 and C1 is 8, 16, or 32.
5307 if (ShiftAmt1 == ShiftAmt2) {
5308 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005309 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005310 case 8 : SExtType = Type::SByteTy; break;
5311 case 16: SExtType = Type::ShortTy; break;
5312 case 32: SExtType = Type::IntTy; break;
5313 }
5314
5315 if (SExtType) {
5316 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5317 SExtType, "sext");
5318 InsertNewInstBefore(NewTrunc, I);
5319 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005320 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005321 }
Chris Lattner86102b82005-01-01 16:22:27 +00005322 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005323 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005324 return 0;
5325}
5326
Chris Lattner48a44f72002-05-02 17:06:02 +00005327
Chris Lattner8f663e82005-10-29 04:36:15 +00005328/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5329/// expression. If so, decompose it, returning some value X, such that Val is
5330/// X*Scale+Offset.
5331///
5332static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5333 unsigned &Offset) {
5334 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5336 if (CI->getType()->isUnsigned()) {
5337 Offset = CI->getZExtValue();
5338 Scale = 1;
5339 return ConstantInt::get(Type::UIntTy, 0);
5340 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005341 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5342 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005343 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5344 if (CUI->getType()->isUnsigned()) {
5345 if (I->getOpcode() == Instruction::Shl) {
5346 // This is a value scaled by '1 << the shift amt'.
5347 Scale = 1U << CUI->getZExtValue();
5348 Offset = 0;
5349 return I->getOperand(0);
5350 } else if (I->getOpcode() == Instruction::Mul) {
5351 // This value is scaled by 'CUI'.
5352 Scale = CUI->getZExtValue();
5353 Offset = 0;
5354 return I->getOperand(0);
5355 } else if (I->getOpcode() == Instruction::Add) {
5356 // We have X+C. Check to see if we really have (X*C2)+C1,
5357 // where C1 is divisible by C2.
5358 unsigned SubScale;
5359 Value *SubVal =
5360 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5361 Offset += CUI->getZExtValue();
5362 if (SubScale > 1 && (Offset % SubScale == 0)) {
5363 Scale = SubScale;
5364 return SubVal;
5365 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005366 }
5367 }
5368 }
5369 }
5370 }
5371
5372 // Otherwise, we can't look past this.
5373 Scale = 1;
5374 Offset = 0;
5375 return Val;
5376}
5377
5378
Chris Lattner216be912005-10-24 06:03:58 +00005379/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5380/// try to eliminate the cast by moving the type information into the alloc.
5381Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5382 AllocationInst &AI) {
5383 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005384 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005385
Chris Lattnerac87beb2005-10-24 06:22:12 +00005386 // Remove any uses of AI that are dead.
5387 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5388 std::vector<Instruction*> DeadUsers;
5389 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5390 Instruction *User = cast<Instruction>(*UI++);
5391 if (isInstructionTriviallyDead(User)) {
5392 while (UI != E && *UI == User)
5393 ++UI; // If this instruction uses AI more than once, don't break UI.
5394
5395 // Add operands to the worklist.
5396 AddUsesToWorkList(*User);
5397 ++NumDeadInst;
5398 DEBUG(std::cerr << "IC: DCE: " << *User);
5399
5400 User->eraseFromParent();
5401 removeFromWorkList(User);
5402 }
5403 }
5404
Chris Lattner216be912005-10-24 06:03:58 +00005405 // Get the type really allocated and the type casted to.
5406 const Type *AllocElTy = AI.getAllocatedType();
5407 const Type *CastElTy = PTy->getElementType();
5408 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005409
Chris Lattner7d190672006-10-01 19:40:58 +00005410 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5411 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005412 if (CastElTyAlign < AllocElTyAlign) return 0;
5413
Chris Lattner46705b22005-10-24 06:35:18 +00005414 // If the allocation has multiple uses, only promote it if we are strictly
5415 // increasing the alignment of the resultant allocation. If we keep it the
5416 // same, we open the door to infinite loops of various kinds.
5417 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5418
Chris Lattner216be912005-10-24 06:03:58 +00005419 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5420 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005421 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005422
Chris Lattner8270c332005-10-29 03:19:53 +00005423 // See if we can satisfy the modulus by pulling a scale out of the array
5424 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005425 unsigned ArraySizeScale, ArrayOffset;
5426 Value *NumElements = // See if the array size is a decomposable linear expr.
5427 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5428
Chris Lattner8270c332005-10-29 03:19:53 +00005429 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5430 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005431 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5432 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005433
Chris Lattner8270c332005-10-29 03:19:53 +00005434 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5435 Value *Amt = 0;
5436 if (Scale == 1) {
5437 Amt = NumElements;
5438 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005439 // If the allocation size is constant, form a constant mul expression
5440 Amt = ConstantInt::get(Type::UIntTy, Scale);
5441 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5442 Amt = ConstantExpr::getMul(
5443 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5444 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005445 else if (Scale != 1) {
5446 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5447 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005448 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005449 }
5450
Chris Lattner8f663e82005-10-29 04:36:15 +00005451 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005452 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005453 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5454 Amt = InsertNewInstBefore(Tmp, AI);
5455 }
5456
Chris Lattner216be912005-10-24 06:03:58 +00005457 std::string Name = AI.getName(); AI.setName("");
5458 AllocationInst *New;
5459 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005460 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005461 else
Nate Begeman848622f2005-11-05 09:21:28 +00005462 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005463 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005464
5465 // If the allocation has multiple uses, insert a cast and change all things
5466 // that used it to use the new cast. This will also hack on CI, but it will
5467 // die soon.
5468 if (!AI.hasOneUse()) {
5469 AddUsesToWorkList(AI);
5470 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5471 InsertNewInstBefore(NewCast, AI);
5472 AI.replaceAllUsesWith(NewCast);
5473 }
Chris Lattner216be912005-10-24 06:03:58 +00005474 return ReplaceInstUsesWith(CI, New);
5475}
5476
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005477/// CanEvaluateInDifferentType - Return true if we can take the specified value
5478/// and return it without inserting any new casts. This is used by code that
5479/// tries to decide whether promoting or shrinking integer operations to wider
5480/// or smaller types will allow us to eliminate a truncate or extend.
5481static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5482 int &NumCastsRemoved) {
5483 if (isa<Constant>(V)) return true;
5484
5485 Instruction *I = dyn_cast<Instruction>(V);
5486 if (!I || !I->hasOneUse()) return false;
5487
5488 switch (I->getOpcode()) {
5489 case Instruction::And:
5490 case Instruction::Or:
5491 case Instruction::Xor:
5492 // These operators can all arbitrarily be extended or truncated.
5493 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5494 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5495 case Instruction::Cast:
5496 // If this is a cast from the destination type, we can trivially eliminate
5497 // it, and this will remove a cast overall.
5498 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005499 // If the first operand is itself a cast, and is eliminable, do not count
5500 // this as an eliminable cast. We would prefer to eliminate those two
5501 // casts first.
5502 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5503 return true;
5504
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005505 ++NumCastsRemoved;
5506 return true;
5507 }
5508 // TODO: Can handle more cases here.
5509 break;
5510 }
5511
5512 return false;
5513}
5514
5515/// EvaluateInDifferentType - Given an expression that
5516/// CanEvaluateInDifferentType returns true for, actually insert the code to
5517/// evaluate the expression.
5518Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5519 if (Constant *C = dyn_cast<Constant>(V))
5520 return ConstantExpr::getCast(C, Ty);
5521
5522 // Otherwise, it must be an instruction.
5523 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005524 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005525 switch (I->getOpcode()) {
5526 case Instruction::And:
5527 case Instruction::Or:
5528 case Instruction::Xor: {
5529 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5530 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5531 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5532 LHS, RHS, I->getName());
5533 break;
5534 }
5535 case Instruction::Cast:
5536 // If this is a cast from the destination type, return the input.
5537 if (I->getOperand(0)->getType() == Ty)
5538 return I->getOperand(0);
5539
5540 // TODO: Can handle more cases here.
5541 assert(0 && "Unreachable!");
5542 break;
5543 }
5544
5545 return InsertNewInstBefore(Res, *I);
5546}
5547
Chris Lattner216be912005-10-24 06:03:58 +00005548
Chris Lattner48a44f72002-05-02 17:06:02 +00005549// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005550//
Chris Lattner113f4f42002-06-25 16:13:24 +00005551Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005552 Value *Src = CI.getOperand(0);
5553
Chris Lattner48a44f72002-05-02 17:06:02 +00005554 // If the user is casting a value to the same type, eliminate this cast
5555 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005556 if (CI.getType() == Src->getType())
5557 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005558
Chris Lattner81a7a232004-10-16 18:11:37 +00005559 if (isa<UndefValue>(Src)) // cast undef -> undef
5560 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5561
Chris Lattner48a44f72002-05-02 17:06:02 +00005562 // If casting the result of another cast instruction, try to eliminate this
5563 // one!
5564 //
Chris Lattner86102b82005-01-01 16:22:27 +00005565 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5566 Value *A = CSrc->getOperand(0);
5567 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5568 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005569 // This instruction now refers directly to the cast's src operand. This
5570 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005571 CI.setOperand(0, CSrc->getOperand(0));
5572 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005573 }
5574
Chris Lattner650b6da2002-08-02 20:00:25 +00005575 // If this is an A->B->A cast, and we are dealing with integral types, try
5576 // to convert this into a logical 'and' instruction.
5577 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005578 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005579 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005580 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005581 CSrc->getType()->getPrimitiveSizeInBits() <
5582 CI.getType()->getPrimitiveSizeInBits()&&
5583 A->getType()->getPrimitiveSizeInBits() ==
5584 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005585 assert(CSrc->getType() != Type::ULongTy &&
5586 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005587 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005588 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005589 AndValue);
5590 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5591 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5592 if (And->getType() != CI.getType()) {
5593 And->setName(CSrc->getName()+".mask");
5594 InsertNewInstBefore(And, CI);
5595 And = new CastInst(And, CI.getType());
5596 }
5597 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005598 }
5599 }
Chris Lattner2590e512006-02-07 06:56:34 +00005600
Chris Lattner03841652004-05-25 04:29:21 +00005601 // If this is a cast to bool, turn it into the appropriate setne instruction.
5602 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005603 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005604 Constant::getNullValue(CI.getOperand(0)->getType()));
5605
Chris Lattner2590e512006-02-07 06:56:34 +00005606 // See if we can simplify any instructions used by the LHS whose sole
5607 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005608 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5609 uint64_t KnownZero, KnownOne;
5610 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5611 KnownZero, KnownOne))
5612 return &CI;
5613 }
Chris Lattner2590e512006-02-07 06:56:34 +00005614
Chris Lattnerd0d51602003-06-21 23:12:02 +00005615 // If casting the result of a getelementptr instruction with no offset, turn
5616 // this into a cast of the original pointer!
5617 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005618 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005619 bool AllZeroOperands = true;
5620 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5621 if (!isa<Constant>(GEP->getOperand(i)) ||
5622 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5623 AllZeroOperands = false;
5624 break;
5625 }
5626 if (AllZeroOperands) {
5627 CI.setOperand(0, GEP->getOperand(0));
5628 return &CI;
5629 }
5630 }
5631
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005632 // If we are casting a malloc or alloca to a pointer to a type of the same
5633 // size, rewrite the allocation instruction to allocate the "right" type.
5634 //
5635 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005636 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5637 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005638
Chris Lattner86102b82005-01-01 16:22:27 +00005639 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5640 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5641 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005642 if (isa<PHINode>(Src))
5643 if (Instruction *NV = FoldOpIntoPhi(CI))
5644 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005645
5646 // If the source and destination are pointers, and this cast is equivalent to
5647 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5648 // This can enhance SROA and other transforms that want type-safe pointers.
5649 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5650 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5651 const Type *DstTy = DstPTy->getElementType();
5652 const Type *SrcTy = SrcPTy->getElementType();
5653
5654 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5655 unsigned NumZeros = 0;
5656 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005657 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5658 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005659 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5660 ++NumZeros;
5661 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005662
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005663 // If we found a path from the src to dest, create the getelementptr now.
5664 if (SrcTy == DstTy) {
5665 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5666 return new GetElementPtrInst(Src, Idxs);
5667 }
5668 }
5669
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005670 // If the source value is an instruction with only this use, we can attempt to
5671 // propagate the cast into the instruction. Also, only handle integral types
5672 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005673 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005674 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005675 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005676
5677 int NumCastsRemoved = 0;
5678 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5679 // If this cast is a truncate, evaluting in a different type always
5680 // eliminates the cast, so it is always a win. If this is a noop-cast
5681 // this just removes a noop cast which isn't pointful, but simplifies
5682 // the code. If this is a zero-extension, we need to do an AND to
5683 // maintain the clear top-part of the computation, so we require that
5684 // the input have eliminated at least one cast. If this is a sign
5685 // extension, we insert two new casts (to do the extension) so we
5686 // require that two casts have been eliminated.
5687 bool DoXForm;
5688 switch (getCastType(Src->getType(), CI.getType())) {
5689 default: assert(0 && "Unknown cast type!");
5690 case Noop:
5691 case Truncate:
5692 DoXForm = true;
5693 break;
5694 case Zeroext:
5695 DoXForm = NumCastsRemoved >= 1;
5696 break;
5697 case Signext:
5698 DoXForm = NumCastsRemoved >= 2;
5699 break;
5700 }
5701
5702 if (DoXForm) {
5703 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5704 assert(Res->getType() == CI.getType());
5705 switch (getCastType(Src->getType(), CI.getType())) {
5706 default: assert(0 && "Unknown cast type!");
5707 case Noop:
5708 case Truncate:
5709 // Just replace this cast with the result.
5710 return ReplaceInstUsesWith(CI, Res);
5711 case Zeroext: {
5712 // We need to emit an AND to clear the high bits.
5713 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5714 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5715 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005716 Constant *C =
5717 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005718 C = ConstantExpr::getCast(C, CI.getType());
5719 return BinaryOperator::createAnd(Res, C);
5720 }
5721 case Signext:
5722 // We need to emit a cast to truncate, then a cast to sext.
5723 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5724 CI.getType());
5725 }
5726 }
5727 }
5728
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005729 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005730 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5731 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005732
5733 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5734 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5735
5736 switch (SrcI->getOpcode()) {
5737 case Instruction::Add:
5738 case Instruction::Mul:
5739 case Instruction::And:
5740 case Instruction::Or:
5741 case Instruction::Xor:
5742 // If we are discarding information, or just changing the sign, rewrite.
5743 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5744 // Don't insert two casts if they cannot be eliminated. We allow two
5745 // casts to be inserted if the sizes are the same. This could only be
5746 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005747 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5748 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005749 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5750 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5751 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5752 ->getOpcode(), Op0c, Op1c);
5753 }
5754 }
Chris Lattner72086162005-05-06 02:07:39 +00005755
5756 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5757 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005758 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005759 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5760 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5761 return BinaryOperator::createXor(New,
5762 ConstantInt::get(CI.getType(), 1));
5763 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005764 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005765 case Instruction::SDiv:
5766 case Instruction::UDiv:
5767 // If we are just changing the sign, rewrite.
5768 if (DestBitSize == SrcBitSize) {
5769 // Don't insert two casts if they cannot be eliminated. We allow two
5770 // casts to be inserted if the sizes are the same. This could only be
5771 // converting signedness, which is a noop.
5772 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5773 !ValueRequiresCast(Op0, DestTy, TD)) {
5774 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5775 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5776 return BinaryOperator::create(
5777 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5778 }
5779 }
5780 break;
5781
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005782 case Instruction::Shl:
5783 // Allow changing the sign of the source operand. Do not allow changing
5784 // the size of the shift, UNLESS the shift amount is a constant. We
5785 // mush not change variable sized shifts to a smaller size, because it
5786 // is undefined to shift more bits out than exist in the value.
5787 if (DestBitSize == SrcBitSize ||
5788 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5789 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5790 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5791 }
5792 break;
Chris Lattner87380412005-05-06 04:18:52 +00005793 case Instruction::Shr:
5794 // If this is a signed shr, and if all bits shifted in are about to be
5795 // truncated off, turn it into an unsigned shr to allow greater
5796 // simplifications.
5797 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5798 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005799 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005800 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5801 // Convert to unsigned.
5802 Value *N1 = InsertOperandCastBefore(Op0,
5803 Op0->getType()->getUnsignedVersion(), &CI);
5804 // Insert the new shift, which is now unsigned.
5805 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5806 Op1, Src->getName()), CI);
5807 return new CastInst(N1, CI.getType());
5808 }
5809 }
5810 break;
5811
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005812 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005813 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005814 // We if we are just checking for a seteq of a single bit and casting it
5815 // to an integer. If so, shift the bit to the appropriate place then
5816 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005817 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005818 uint64_t Op1CV = Op1C->getZExtValue();
5819 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5820 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5821 // cast (X == 1) to int --> X iff X has only the low bit set.
5822 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5823 // cast (X != 0) to int --> X iff X has only the low bit set.
5824 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5825 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5826 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5827 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5828 // If Op1C some other power of two, convert:
5829 uint64_t KnownZero, KnownOne;
5830 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5831 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5832
5833 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5834 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5835 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5836 // (X&4) == 2 --> false
5837 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005838 Constant *Res = ConstantBool::get(isSetNE);
5839 Res = ConstantExpr::getCast(Res, CI.getType());
5840 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005841 }
5842
5843 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5844 Value *In = Op0;
5845 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005846 // Perform an unsigned shr by shiftamt. Convert input to
5847 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005848 if (In->getType()->isSigned())
Reid Spencer00c482b2006-10-26 19:19:06 +00005849 In = InsertCastBefore(
5850 In, In->getType()->getUnsignedVersion(), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005851 // Insert the shift to put the result in the low bit.
5852 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005853 ConstantInt::get(Type::UByteTy, ShiftAmt),
5854 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005855 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005856
5857 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5858 Constant *One = ConstantInt::get(In->getType(), 1);
5859 In = BinaryOperator::createXor(In, One, "tmp");
5860 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005861 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005862
5863 if (CI.getType() == In->getType())
5864 return ReplaceInstUsesWith(CI, In);
5865 else
5866 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005867 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005868 }
5869 }
5870 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005871 }
5872 }
Chris Lattner99155be2006-05-25 23:24:33 +00005873
5874 if (SrcI->hasOneUse()) {
5875 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5876 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5877 // because the inputs are known to be a vector. Check to see if this is
5878 // a cast to a vector with the same # elts.
5879 if (isa<PackedType>(CI.getType()) &&
5880 cast<PackedType>(CI.getType())->getNumElements() ==
5881 SVI->getType()->getNumElements()) {
5882 CastInst *Tmp;
5883 // If either of the operands is a cast from CI.getType(), then
5884 // evaluating the shuffle in the casted destination's type will allow
5885 // us to eliminate at least one cast.
5886 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5887 Tmp->getOperand(0)->getType() == CI.getType()) ||
5888 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005889 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005890 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5891 CI.getType(), &CI);
5892 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5893 CI.getType(), &CI);
5894 // Return a new shuffle vector. Use the same element ID's, as we
5895 // know the vector types match #elts.
5896 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5897 }
5898 }
5899 }
5900 }
5901 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005902
Chris Lattner260ab202002-04-18 17:39:14 +00005903 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005904}
5905
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005906/// GetSelectFoldableOperands - We want to turn code that looks like this:
5907/// %C = or %A, %B
5908/// %D = select %cond, %C, %A
5909/// into:
5910/// %C = select %cond, %B, 0
5911/// %D = or %A, %C
5912///
5913/// Assuming that the specified instruction is an operand to the select, return
5914/// a bitmask indicating which operands of this instruction are foldable if they
5915/// equal the other incoming value of the select.
5916///
5917static unsigned GetSelectFoldableOperands(Instruction *I) {
5918 switch (I->getOpcode()) {
5919 case Instruction::Add:
5920 case Instruction::Mul:
5921 case Instruction::And:
5922 case Instruction::Or:
5923 case Instruction::Xor:
5924 return 3; // Can fold through either operand.
5925 case Instruction::Sub: // Can only fold on the amount subtracted.
5926 case Instruction::Shl: // Can only fold on the shift amount.
5927 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005928 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005929 default:
5930 return 0; // Cannot fold
5931 }
5932}
5933
5934/// GetSelectFoldableConstant - For the same transformation as the previous
5935/// function, return the identity constant that goes into the select.
5936static Constant *GetSelectFoldableConstant(Instruction *I) {
5937 switch (I->getOpcode()) {
5938 default: assert(0 && "This cannot happen!"); abort();
5939 case Instruction::Add:
5940 case Instruction::Sub:
5941 case Instruction::Or:
5942 case Instruction::Xor:
5943 return Constant::getNullValue(I->getType());
5944 case Instruction::Shl:
5945 case Instruction::Shr:
5946 return Constant::getNullValue(Type::UByteTy);
5947 case Instruction::And:
5948 return ConstantInt::getAllOnesValue(I->getType());
5949 case Instruction::Mul:
5950 return ConstantInt::get(I->getType(), 1);
5951 }
5952}
5953
Chris Lattner411336f2005-01-19 21:50:18 +00005954/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5955/// have the same opcode and only one use each. Try to simplify this.
5956Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5957 Instruction *FI) {
5958 if (TI->getNumOperands() == 1) {
5959 // If this is a non-volatile load or a cast from the same type,
5960 // merge.
5961 if (TI->getOpcode() == Instruction::Cast) {
5962 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5963 return 0;
5964 } else {
5965 return 0; // unknown unary op.
5966 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005967
Chris Lattner411336f2005-01-19 21:50:18 +00005968 // Fold this by inserting a select from the input values.
5969 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5970 FI->getOperand(0), SI.getName()+".v");
5971 InsertNewInstBefore(NewSI, SI);
5972 return new CastInst(NewSI, TI->getType());
5973 }
5974
5975 // Only handle binary operators here.
5976 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5977 return 0;
5978
5979 // Figure out if the operations have any operands in common.
5980 Value *MatchOp, *OtherOpT, *OtherOpF;
5981 bool MatchIsOpZero;
5982 if (TI->getOperand(0) == FI->getOperand(0)) {
5983 MatchOp = TI->getOperand(0);
5984 OtherOpT = TI->getOperand(1);
5985 OtherOpF = FI->getOperand(1);
5986 MatchIsOpZero = true;
5987 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5988 MatchOp = TI->getOperand(1);
5989 OtherOpT = TI->getOperand(0);
5990 OtherOpF = FI->getOperand(0);
5991 MatchIsOpZero = false;
5992 } else if (!TI->isCommutative()) {
5993 return 0;
5994 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5995 MatchOp = TI->getOperand(0);
5996 OtherOpT = TI->getOperand(1);
5997 OtherOpF = FI->getOperand(0);
5998 MatchIsOpZero = true;
5999 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6000 MatchOp = TI->getOperand(1);
6001 OtherOpT = TI->getOperand(0);
6002 OtherOpF = FI->getOperand(1);
6003 MatchIsOpZero = true;
6004 } else {
6005 return 0;
6006 }
6007
6008 // If we reach here, they do have operations in common.
6009 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6010 OtherOpF, SI.getName()+".v");
6011 InsertNewInstBefore(NewSI, SI);
6012
6013 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6014 if (MatchIsOpZero)
6015 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6016 else
6017 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6018 } else {
6019 if (MatchIsOpZero)
6020 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6021 else
6022 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6023 }
6024}
6025
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006026Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006027 Value *CondVal = SI.getCondition();
6028 Value *TrueVal = SI.getTrueValue();
6029 Value *FalseVal = SI.getFalseValue();
6030
6031 // select true, X, Y -> X
6032 // select false, X, Y -> Y
6033 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006034 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006035
6036 // select C, X, X -> X
6037 if (TrueVal == FalseVal)
6038 return ReplaceInstUsesWith(SI, TrueVal);
6039
Chris Lattner81a7a232004-10-16 18:11:37 +00006040 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6041 return ReplaceInstUsesWith(SI, FalseVal);
6042 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6043 return ReplaceInstUsesWith(SI, TrueVal);
6044 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6045 if (isa<Constant>(TrueVal))
6046 return ReplaceInstUsesWith(SI, TrueVal);
6047 else
6048 return ReplaceInstUsesWith(SI, FalseVal);
6049 }
6050
Chris Lattner1c631e82004-04-08 04:43:23 +00006051 if (SI.getType() == Type::BoolTy)
6052 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006053 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006054 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006055 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006056 } else {
6057 // Change: A = select B, false, C --> A = and !B, C
6058 Value *NotCond =
6059 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6060 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006061 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006062 }
6063 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006064 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006065 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006066 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006067 } else {
6068 // Change: A = select B, C, true --> A = or !B, C
6069 Value *NotCond =
6070 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6071 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006072 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006073 }
6074 }
6075
Chris Lattner183b3362004-04-09 19:05:30 +00006076 // Selecting between two integer constants?
6077 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6078 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6079 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006080 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006081 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006082 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006083 // select C, 0, 1 -> cast !C to int
6084 Value *NotCond =
6085 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006086 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006087 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006088 }
Chris Lattner35167c32004-06-09 07:59:58 +00006089
Chris Lattner380c7e92006-09-20 04:44:59 +00006090 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6091
6092 // (x <s 0) ? -1 : 0 -> sra x, 31
6093 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6094 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6095 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6096 bool CanXForm = false;
6097 if (CmpCst->getType()->isSigned())
6098 CanXForm = CmpCst->isNullValue() &&
6099 IC->getOpcode() == Instruction::SetLT;
6100 else {
6101 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006102 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006103 IC->getOpcode() == Instruction::SetGT;
6104 }
6105
6106 if (CanXForm) {
6107 // The comparison constant and the result are not neccessarily the
6108 // same width. In any case, the first step to do is make sure
6109 // that X is signed.
6110 Value *X = IC->getOperand(0);
6111 if (!X->getType()->isSigned())
6112 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6113
6114 // Now that X is signed, we have to make the all ones value. Do
6115 // this by inserting a new SRA.
6116 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006117 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattner380c7e92006-09-20 04:44:59 +00006118 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6119 ShAmt, "ones");
6120 InsertNewInstBefore(SRA, SI);
6121
6122 // Finally, convert to the type of the select RHS. If this is
6123 // smaller than the compare value, it will truncate the ones to
6124 // fit. If it is larger, it will sext the ones to fit.
6125 return new CastInst(SRA, SI.getType());
6126 }
6127 }
6128
6129
6130 // If one of the constants is zero (we know they can't both be) and we
6131 // have a setcc instruction with zero, and we have an 'and' with the
6132 // non-constant value, eliminate this whole mess. This corresponds to
6133 // cases like this: ((X & 27) ? 27 : 0)
6134 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006135 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006136 cast<Constant>(IC->getOperand(1))->isNullValue())
6137 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6138 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006139 isa<ConstantInt>(ICA->getOperand(1)) &&
6140 (ICA->getOperand(1) == TrueValC ||
6141 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006142 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6143 // Okay, now we know that everything is set up, we just don't
6144 // know whether we have a setne or seteq and whether the true or
6145 // false val is the zero.
6146 bool ShouldNotVal = !TrueValC->isNullValue();
6147 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6148 Value *V = ICA;
6149 if (ShouldNotVal)
6150 V = InsertNewInstBefore(BinaryOperator::create(
6151 Instruction::Xor, V, ICA->getOperand(1)), SI);
6152 return ReplaceInstUsesWith(SI, V);
6153 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006154 }
Chris Lattner533bc492004-03-30 19:37:13 +00006155 }
Chris Lattner623fba12004-04-10 22:21:27 +00006156
6157 // See if we are selecting two values based on a comparison of the two values.
6158 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6159 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6160 // Transform (X == Y) ? X : Y -> Y
6161 if (SCI->getOpcode() == Instruction::SetEQ)
6162 return ReplaceInstUsesWith(SI, FalseVal);
6163 // Transform (X != Y) ? X : Y -> X
6164 if (SCI->getOpcode() == Instruction::SetNE)
6165 return ReplaceInstUsesWith(SI, TrueVal);
6166 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6167
6168 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6169 // Transform (X == Y) ? Y : X -> X
6170 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006171 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006172 // Transform (X != Y) ? Y : X -> Y
6173 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006174 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006175 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6176 }
6177 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006178
Chris Lattnera04c9042005-01-13 22:52:24 +00006179 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6180 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6181 if (TI->hasOneUse() && FI->hasOneUse()) {
6182 bool isInverse = false;
6183 Instruction *AddOp = 0, *SubOp = 0;
6184
Chris Lattner411336f2005-01-19 21:50:18 +00006185 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6186 if (TI->getOpcode() == FI->getOpcode())
6187 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6188 return IV;
6189
6190 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6191 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006192 if (TI->getOpcode() == Instruction::Sub &&
6193 FI->getOpcode() == Instruction::Add) {
6194 AddOp = FI; SubOp = TI;
6195 } else if (FI->getOpcode() == Instruction::Sub &&
6196 TI->getOpcode() == Instruction::Add) {
6197 AddOp = TI; SubOp = FI;
6198 }
6199
6200 if (AddOp) {
6201 Value *OtherAddOp = 0;
6202 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6203 OtherAddOp = AddOp->getOperand(1);
6204 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6205 OtherAddOp = AddOp->getOperand(0);
6206 }
6207
6208 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006209 // So at this point we know we have (Y -> OtherAddOp):
6210 // select C, (add X, Y), (sub X, Z)
6211 Value *NegVal; // Compute -Z
6212 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6213 NegVal = ConstantExpr::getNeg(C);
6214 } else {
6215 NegVal = InsertNewInstBefore(
6216 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006217 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006218
6219 Value *NewTrueOp = OtherAddOp;
6220 Value *NewFalseOp = NegVal;
6221 if (AddOp != TI)
6222 std::swap(NewTrueOp, NewFalseOp);
6223 Instruction *NewSel =
6224 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6225
6226 NewSel = InsertNewInstBefore(NewSel, SI);
6227 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006228 }
6229 }
6230 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006231
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006232 // See if we can fold the select into one of our operands.
6233 if (SI.getType()->isInteger()) {
6234 // See the comment above GetSelectFoldableOperands for a description of the
6235 // transformation we are doing here.
6236 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6237 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6238 !isa<Constant>(FalseVal))
6239 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6240 unsigned OpToFold = 0;
6241 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6242 OpToFold = 1;
6243 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6244 OpToFold = 2;
6245 }
6246
6247 if (OpToFold) {
6248 Constant *C = GetSelectFoldableConstant(TVI);
6249 std::string Name = TVI->getName(); TVI->setName("");
6250 Instruction *NewSel =
6251 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6252 Name);
6253 InsertNewInstBefore(NewSel, SI);
6254 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6255 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6256 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6257 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6258 else {
6259 assert(0 && "Unknown instruction!!");
6260 }
6261 }
6262 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006263
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006264 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6265 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6266 !isa<Constant>(TrueVal))
6267 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6268 unsigned OpToFold = 0;
6269 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6270 OpToFold = 1;
6271 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6272 OpToFold = 2;
6273 }
6274
6275 if (OpToFold) {
6276 Constant *C = GetSelectFoldableConstant(FVI);
6277 std::string Name = FVI->getName(); FVI->setName("");
6278 Instruction *NewSel =
6279 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6280 Name);
6281 InsertNewInstBefore(NewSel, SI);
6282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6283 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6284 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6285 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6286 else {
6287 assert(0 && "Unknown instruction!!");
6288 }
6289 }
6290 }
6291 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006292
6293 if (BinaryOperator::isNot(CondVal)) {
6294 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6295 SI.setOperand(1, FalseVal);
6296 SI.setOperand(2, TrueVal);
6297 return &SI;
6298 }
6299
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006300 return 0;
6301}
6302
Chris Lattner82f2ef22006-03-06 20:18:44 +00006303/// GetKnownAlignment - If the specified pointer has an alignment that we can
6304/// determine, return it, otherwise return 0.
6305static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6306 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6307 unsigned Align = GV->getAlignment();
6308 if (Align == 0 && TD)
6309 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6310 return Align;
6311 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6312 unsigned Align = AI->getAlignment();
6313 if (Align == 0 && TD) {
6314 if (isa<AllocaInst>(AI))
6315 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6316 else if (isa<MallocInst>(AI)) {
6317 // Malloc returns maximally aligned memory.
6318 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6319 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6320 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6321 }
6322 }
6323 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006324 } else if (isa<CastInst>(V) ||
6325 (isa<ConstantExpr>(V) &&
6326 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6327 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006328 if (isa<PointerType>(CI->getOperand(0)->getType()))
6329 return GetKnownAlignment(CI->getOperand(0), TD);
6330 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006331 } else if (isa<GetElementPtrInst>(V) ||
6332 (isa<ConstantExpr>(V) &&
6333 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6334 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006335 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6336 if (BaseAlignment == 0) return 0;
6337
6338 // If all indexes are zero, it is just the alignment of the base pointer.
6339 bool AllZeroOperands = true;
6340 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6341 if (!isa<Constant>(GEPI->getOperand(i)) ||
6342 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6343 AllZeroOperands = false;
6344 break;
6345 }
6346 if (AllZeroOperands)
6347 return BaseAlignment;
6348
6349 // Otherwise, if the base alignment is >= the alignment we expect for the
6350 // base pointer type, then we know that the resultant pointer is aligned at
6351 // least as much as its type requires.
6352 if (!TD) return 0;
6353
6354 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6355 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006356 <= BaseAlignment) {
6357 const Type *GEPTy = GEPI->getType();
6358 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6359 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006360 return 0;
6361 }
6362 return 0;
6363}
6364
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006365
Chris Lattnerc66b2232006-01-13 20:11:04 +00006366/// visitCallInst - CallInst simplification. This mostly only handles folding
6367/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6368/// the heavy lifting.
6369///
Chris Lattner970c33a2003-06-19 17:00:31 +00006370Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006371 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6372 if (!II) return visitCallSite(&CI);
6373
Chris Lattner51ea1272004-02-28 05:22:00 +00006374 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6375 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006376 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006377 bool Changed = false;
6378
6379 // memmove/cpy/set of zero bytes is a noop.
6380 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6381 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6382
Chris Lattner00648e12004-10-12 04:52:52 +00006383 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006384 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006385 // Replace the instruction with just byte operations. We would
6386 // transform other cases to loads/stores, but we don't know if
6387 // alignment is sufficient.
6388 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006389 }
6390
Chris Lattner00648e12004-10-12 04:52:52 +00006391 // If we have a memmove and the source operation is a constant global,
6392 // then the source and dest pointers can't alias, so we can change this
6393 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006394 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006395 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6396 if (GVSrc->isConstant()) {
6397 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006398 const char *Name;
6399 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6400 Type::UIntTy)
6401 Name = "llvm.memcpy.i32";
6402 else
6403 Name = "llvm.memcpy.i64";
6404 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006405 CI.getCalledFunction()->getFunctionType());
6406 CI.setOperand(0, MemCpy);
6407 Changed = true;
6408 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006409 }
Chris Lattner00648e12004-10-12 04:52:52 +00006410
Chris Lattner82f2ef22006-03-06 20:18:44 +00006411 // If we can determine a pointer alignment that is bigger than currently
6412 // set, update the alignment.
6413 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6414 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6415 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6416 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006417 if (MI->getAlignment()->getZExtValue() < Align) {
6418 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006419 Changed = true;
6420 }
6421 } else if (isa<MemSetInst>(MI)) {
6422 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006423 if (MI->getAlignment()->getZExtValue() < Alignment) {
6424 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006425 Changed = true;
6426 }
6427 }
6428
Chris Lattnerc66b2232006-01-13 20:11:04 +00006429 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006430 } else {
6431 switch (II->getIntrinsicID()) {
6432 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006433 case Intrinsic::ppc_altivec_lvx:
6434 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006435 case Intrinsic::x86_sse_loadu_ps:
6436 case Intrinsic::x86_sse2_loadu_pd:
6437 case Intrinsic::x86_sse2_loadu_dq:
6438 // Turn PPC lvx -> load if the pointer is known aligned.
6439 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006440 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006441 Value *Ptr = InsertCastBefore(II->getOperand(1),
6442 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006443 return new LoadInst(Ptr);
6444 }
6445 break;
6446 case Intrinsic::ppc_altivec_stvx:
6447 case Intrinsic::ppc_altivec_stvxl:
6448 // Turn stvx -> store if the pointer is known aligned.
6449 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006450 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6451 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006452 return new StoreInst(II->getOperand(1), Ptr);
6453 }
6454 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006455 case Intrinsic::x86_sse_storeu_ps:
6456 case Intrinsic::x86_sse2_storeu_pd:
6457 case Intrinsic::x86_sse2_storeu_dq:
6458 case Intrinsic::x86_sse2_storel_dq:
6459 // Turn X86 storeu -> store if the pointer is known aligned.
6460 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6461 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6462 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6463 return new StoreInst(II->getOperand(2), Ptr);
6464 }
6465 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006466
6467 case Intrinsic::x86_sse_cvttss2si: {
6468 // These intrinsics only demands the 0th element of its input vector. If
6469 // we can simplify the input based on that, do so now.
6470 uint64_t UndefElts;
6471 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6472 UndefElts)) {
6473 II->setOperand(1, V);
6474 return II;
6475 }
6476 break;
6477 }
6478
Chris Lattnere79d2492006-04-06 19:19:17 +00006479 case Intrinsic::ppc_altivec_vperm:
6480 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6481 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6482 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6483
6484 // Check that all of the elements are integer constants or undefs.
6485 bool AllEltsOk = true;
6486 for (unsigned i = 0; i != 16; ++i) {
6487 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6488 !isa<UndefValue>(Mask->getOperand(i))) {
6489 AllEltsOk = false;
6490 break;
6491 }
6492 }
6493
6494 if (AllEltsOk) {
6495 // Cast the input vectors to byte vectors.
6496 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6497 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6498 Value *Result = UndefValue::get(Op0->getType());
6499
6500 // Only extract each element once.
6501 Value *ExtractedElts[32];
6502 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6503
6504 for (unsigned i = 0; i != 16; ++i) {
6505 if (isa<UndefValue>(Mask->getOperand(i)))
6506 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006507 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006508 Idx &= 31; // Match the hardware behavior.
6509
6510 if (ExtractedElts[Idx] == 0) {
6511 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006512 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006513 InsertNewInstBefore(Elt, CI);
6514 ExtractedElts[Idx] = Elt;
6515 }
6516
6517 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006518 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006519 InsertNewInstBefore(cast<Instruction>(Result), CI);
6520 }
6521 return new CastInst(Result, CI.getType());
6522 }
6523 }
6524 break;
6525
Chris Lattner503221f2006-01-13 21:28:09 +00006526 case Intrinsic::stackrestore: {
6527 // If the save is right next to the restore, remove the restore. This can
6528 // happen when variable allocas are DCE'd.
6529 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6530 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6531 BasicBlock::iterator BI = SS;
6532 if (&*++BI == II)
6533 return EraseInstFromFunction(CI);
6534 }
6535 }
6536
6537 // If the stack restore is in a return/unwind block and if there are no
6538 // allocas or calls between the restore and the return, nuke the restore.
6539 TerminatorInst *TI = II->getParent()->getTerminator();
6540 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6541 BasicBlock::iterator BI = II;
6542 bool CannotRemove = false;
6543 for (++BI; &*BI != TI; ++BI) {
6544 if (isa<AllocaInst>(BI) ||
6545 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6546 CannotRemove = true;
6547 break;
6548 }
6549 }
6550 if (!CannotRemove)
6551 return EraseInstFromFunction(CI);
6552 }
6553 break;
6554 }
6555 }
Chris Lattner00648e12004-10-12 04:52:52 +00006556 }
6557
Chris Lattnerc66b2232006-01-13 20:11:04 +00006558 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006559}
6560
6561// InvokeInst simplification
6562//
6563Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006564 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006565}
6566
Chris Lattneraec3d942003-10-07 22:32:43 +00006567// visitCallSite - Improvements for call and invoke instructions.
6568//
6569Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006570 bool Changed = false;
6571
6572 // If the callee is a constexpr cast of a function, attempt to move the cast
6573 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006574 if (transformConstExprCastCall(CS)) return 0;
6575
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006576 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006577
Chris Lattner61d9d812005-05-13 07:09:09 +00006578 if (Function *CalleeF = dyn_cast<Function>(Callee))
6579 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6580 Instruction *OldCall = CS.getInstruction();
6581 // If the call and callee calling conventions don't match, this call must
6582 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006583 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006584 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6585 if (!OldCall->use_empty())
6586 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6587 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6588 return EraseInstFromFunction(*OldCall);
6589 return 0;
6590 }
6591
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006592 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6593 // This instruction is not reachable, just remove it. We insert a store to
6594 // undef so that we know that this code is not reachable, despite the fact
6595 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006596 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006597 UndefValue::get(PointerType::get(Type::BoolTy)),
6598 CS.getInstruction());
6599
6600 if (!CS.getInstruction()->use_empty())
6601 CS.getInstruction()->
6602 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6603
6604 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6605 // Don't break the CFG, insert a dummy cond branch.
6606 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006607 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006608 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006609 return EraseInstFromFunction(*CS.getInstruction());
6610 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006611
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006612 const PointerType *PTy = cast<PointerType>(Callee->getType());
6613 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6614 if (FTy->isVarArg()) {
6615 // See if we can optimize any arguments passed through the varargs area of
6616 // the call.
6617 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6618 E = CS.arg_end(); I != E; ++I)
6619 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6620 // If this cast does not effect the value passed through the varargs
6621 // area, we can eliminate the use of the cast.
6622 Value *Op = CI->getOperand(0);
6623 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6624 *I = Op;
6625 Changed = true;
6626 }
6627 }
6628 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006629
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006630 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006631}
6632
Chris Lattner970c33a2003-06-19 17:00:31 +00006633// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6634// attempt to move the cast to the arguments of the call/invoke.
6635//
6636bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6637 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6638 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006639 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006640 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006641 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006642 Instruction *Caller = CS.getInstruction();
6643
6644 // Okay, this is a cast from a function to a different type. Unless doing so
6645 // would cause a type conversion of one of our arguments, change this call to
6646 // be a direct call with arguments casted to the appropriate types.
6647 //
6648 const FunctionType *FT = Callee->getFunctionType();
6649 const Type *OldRetTy = Caller->getType();
6650
Chris Lattner1f7942f2004-01-14 06:06:08 +00006651 // Check to see if we are changing the return type...
6652 if (OldRetTy != FT->getReturnType()) {
6653 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006654 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6655 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006656 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006657 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006658 return false; // Cannot transform this return value...
6659
6660 // If the callsite is an invoke instruction, and the return value is used by
6661 // a PHI node in a successor, we cannot change the return type of the call
6662 // because there is no place to put the cast instruction (without breaking
6663 // the critical edge). Bail out in this case.
6664 if (!Caller->use_empty())
6665 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6666 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6667 UI != E; ++UI)
6668 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6669 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006670 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006671 return false;
6672 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006673
6674 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6675 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006676
Chris Lattner970c33a2003-06-19 17:00:31 +00006677 CallSite::arg_iterator AI = CS.arg_begin();
6678 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6679 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006680 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006681 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006682 //Either we can cast directly, or we can upconvert the argument
6683 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6684 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6685 ParamTy->isSigned() == ActTy->isSigned() &&
6686 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6687 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006688 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006689 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006690 }
6691
6692 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6693 Callee->isExternal())
6694 return false; // Do not delete arguments unless we have a function body...
6695
6696 // Okay, we decided that this is a safe thing to do: go ahead and start
6697 // inserting cast instructions as necessary...
6698 std::vector<Value*> Args;
6699 Args.reserve(NumActualArgs);
6700
6701 AI = CS.arg_begin();
6702 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6703 const Type *ParamTy = FT->getParamType(i);
6704 if ((*AI)->getType() == ParamTy) {
6705 Args.push_back(*AI);
6706 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006707 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6708 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006709 }
6710 }
6711
6712 // If the function takes more arguments than the call was taking, add them
6713 // now...
6714 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6715 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6716
6717 // If we are removing arguments to the function, emit an obnoxious warning...
6718 if (FT->getNumParams() < NumActualArgs)
6719 if (!FT->isVarArg()) {
6720 std::cerr << "WARNING: While resolving call to function '"
6721 << Callee->getName() << "' arguments were dropped!\n";
6722 } else {
6723 // Add all of the arguments in their promoted form to the arg list...
6724 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6725 const Type *PTy = getPromotedType((*AI)->getType());
6726 if (PTy != (*AI)->getType()) {
6727 // Must promote to pass through va_arg area!
6728 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6729 InsertNewInstBefore(Cast, *Caller);
6730 Args.push_back(Cast);
6731 } else {
6732 Args.push_back(*AI);
6733 }
6734 }
6735 }
6736
6737 if (FT->getReturnType() == Type::VoidTy)
6738 Caller->setName(""); // Void type should not have a name...
6739
6740 Instruction *NC;
6741 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006742 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006743 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006744 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006745 } else {
6746 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006747 if (cast<CallInst>(Caller)->isTailCall())
6748 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006749 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006750 }
6751
6752 // Insert a cast of the return type as necessary...
6753 Value *NV = NC;
6754 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6755 if (NV->getType() != Type::VoidTy) {
6756 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006757
6758 // If this is an invoke instruction, we should insert it after the first
6759 // non-phi, instruction in the normal successor block.
6760 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6761 BasicBlock::iterator I = II->getNormalDest()->begin();
6762 while (isa<PHINode>(I)) ++I;
6763 InsertNewInstBefore(NC, *I);
6764 } else {
6765 // Otherwise, it's a call, just insert cast right after the call instr
6766 InsertNewInstBefore(NC, *Caller);
6767 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006768 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006769 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006770 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006771 }
6772 }
6773
6774 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6775 Caller->replaceAllUsesWith(NV);
6776 Caller->getParent()->getInstList().erase(Caller);
6777 removeFromWorkList(Caller);
6778 return true;
6779}
6780
6781
Chris Lattner7515cab2004-11-14 19:13:23 +00006782// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6783// operator and they all are only used by the PHI, PHI together their
6784// inputs, and do the operation once, to the result of the PHI.
6785Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6786 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6787
6788 // Scan the instruction, looking for input operations that can be folded away.
6789 // If all input operands to the phi are the same instruction (e.g. a cast from
6790 // the same type or "+42") we can pull the operation through the PHI, reducing
6791 // code size and simplifying code.
6792 Constant *ConstantOp = 0;
6793 const Type *CastSrcTy = 0;
6794 if (isa<CastInst>(FirstInst)) {
6795 CastSrcTy = FirstInst->getOperand(0)->getType();
6796 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6797 // Can fold binop or shift if the RHS is a constant.
6798 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6799 if (ConstantOp == 0) return 0;
6800 } else {
6801 return 0; // Cannot fold this operation.
6802 }
6803
6804 // Check to see if all arguments are the same operation.
6805 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6806 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6807 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6808 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6809 return 0;
6810 if (CastSrcTy) {
6811 if (I->getOperand(0)->getType() != CastSrcTy)
6812 return 0; // Cast operation must match.
6813 } else if (I->getOperand(1) != ConstantOp) {
6814 return 0;
6815 }
6816 }
6817
6818 // Okay, they are all the same operation. Create a new PHI node of the
6819 // correct type, and PHI together all of the LHS's of the instructions.
6820 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6821 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006822 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006823
6824 Value *InVal = FirstInst->getOperand(0);
6825 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006826
6827 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006828 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6829 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6830 if (NewInVal != InVal)
6831 InVal = 0;
6832 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6833 }
6834
6835 Value *PhiVal;
6836 if (InVal) {
6837 // The new PHI unions all of the same values together. This is really
6838 // common, so we handle it intelligently here for compile-time speed.
6839 PhiVal = InVal;
6840 delete NewPN;
6841 } else {
6842 InsertNewInstBefore(NewPN, PN);
6843 PhiVal = NewPN;
6844 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006845
Chris Lattner7515cab2004-11-14 19:13:23 +00006846 // Insert and return the new operation.
6847 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006848 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006849 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006850 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006851 else
6852 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006853 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006854}
Chris Lattner48a44f72002-05-02 17:06:02 +00006855
Chris Lattner71536432005-01-17 05:10:15 +00006856/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6857/// that is dead.
6858static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6859 if (PN->use_empty()) return true;
6860 if (!PN->hasOneUse()) return false;
6861
6862 // Remember this node, and if we find the cycle, return.
6863 if (!PotentiallyDeadPHIs.insert(PN).second)
6864 return true;
6865
6866 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6867 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006868
Chris Lattner71536432005-01-17 05:10:15 +00006869 return false;
6870}
6871
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006872// PHINode simplification
6873//
Chris Lattner113f4f42002-06-25 16:13:24 +00006874Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006875 // If LCSSA is around, don't mess with Phi nodes
6876 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006877
Owen Andersonae8aa642006-07-10 22:03:18 +00006878 if (Value *V = PN.hasConstantValue())
6879 return ReplaceInstUsesWith(PN, V);
6880
6881 // If the only user of this instruction is a cast instruction, and all of the
6882 // incoming values are constants, change this PHI to merge together the casted
6883 // constants.
6884 if (PN.hasOneUse())
6885 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6886 if (CI->getType() != PN.getType()) { // noop casts will be folded
6887 bool AllConstant = true;
6888 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6889 if (!isa<Constant>(PN.getIncomingValue(i))) {
6890 AllConstant = false;
6891 break;
6892 }
6893 if (AllConstant) {
6894 // Make a new PHI with all casted values.
6895 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6896 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6897 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6898 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6899 PN.getIncomingBlock(i));
6900 }
6901
6902 // Update the cast instruction.
6903 CI->setOperand(0, New);
6904 WorkList.push_back(CI); // revisit the cast instruction to fold.
6905 WorkList.push_back(New); // Make sure to revisit the new Phi
6906 return &PN; // PN is now dead!
6907 }
6908 }
6909
6910 // If all PHI operands are the same operation, pull them through the PHI,
6911 // reducing code size.
6912 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6913 PN.getIncomingValue(0)->hasOneUse())
6914 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6915 return Result;
6916
6917 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6918 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6919 // PHI)... break the cycle.
6920 if (PN.hasOneUse())
6921 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6922 std::set<PHINode*> PotentiallyDeadPHIs;
6923 PotentiallyDeadPHIs.insert(&PN);
6924 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6925 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6926 }
6927
Chris Lattner91daeb52003-12-19 05:58:40 +00006928 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006929}
6930
Chris Lattner69193f92004-04-05 01:30:19 +00006931static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6932 Instruction *InsertPoint,
6933 InstCombiner *IC) {
6934 unsigned PS = IC->getTargetData().getPointerSize();
6935 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006936 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6937 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00006938 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
6939 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00006940}
6941
Chris Lattner48a44f72002-05-02 17:06:02 +00006942
Chris Lattner113f4f42002-06-25 16:13:24 +00006943Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006944 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006945 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006946 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006947 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006948 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006949
Chris Lattner81a7a232004-10-16 18:11:37 +00006950 if (isa<UndefValue>(GEP.getOperand(0)))
6951 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6952
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006953 bool HasZeroPointerIndex = false;
6954 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6955 HasZeroPointerIndex = C->isNullValue();
6956
6957 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006958 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006959
Chris Lattner69193f92004-04-05 01:30:19 +00006960 // Eliminate unneeded casts for indices.
6961 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006962 gep_type_iterator GTI = gep_type_begin(GEP);
6963 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6964 if (isa<SequentialType>(*GTI)) {
6965 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6966 Value *Src = CI->getOperand(0);
6967 const Type *SrcTy = Src->getType();
6968 const Type *DestTy = CI->getType();
6969 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006970 if (SrcTy->getPrimitiveSizeInBits() ==
6971 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006972 // We can always eliminate a cast from ulong or long to the other.
6973 // We can always eliminate a cast from uint to int or the other on
6974 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006975 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006976 MadeChange = true;
6977 GEP.setOperand(i, Src);
6978 }
6979 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6980 SrcTy->getPrimitiveSize() == 4) {
6981 // We can always eliminate a cast from int to [u]long. We can
6982 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6983 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006984 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006985 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006986 MadeChange = true;
6987 GEP.setOperand(i, Src);
6988 }
Chris Lattner69193f92004-04-05 01:30:19 +00006989 }
6990 }
6991 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006992 // If we are using a wider index than needed for this platform, shrink it
6993 // to what we need. If the incoming value needs a cast instruction,
6994 // insert it. This explicit cast can make subsequent optimizations more
6995 // obvious.
6996 Value *Op = GEP.getOperand(i);
6997 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006998 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006999 GEP.setOperand(i, ConstantExpr::getCast(C,
7000 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007001 MadeChange = true;
7002 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007003 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007004 GEP.setOperand(i, Op);
7005 MadeChange = true;
7006 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007007
7008 // If this is a constant idx, make sure to canonicalize it to be a signed
7009 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007010 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7011 if (CUI->getType()->isUnsigned()) {
7012 GEP.setOperand(i,
7013 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7014 MadeChange = true;
7015 }
Chris Lattner69193f92004-04-05 01:30:19 +00007016 }
7017 if (MadeChange) return &GEP;
7018
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007019 // Combine Indices - If the source pointer to this getelementptr instruction
7020 // is a getelementptr instruction, combine the indices of the two
7021 // getelementptr instructions into a single instruction.
7022 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007023 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007024 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007025 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007026
7027 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007028 // Note that if our source is a gep chain itself that we wait for that
7029 // chain to be resolved before we perform this transformation. This
7030 // avoids us creating a TON of code in some cases.
7031 //
7032 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7033 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7034 return 0; // Wait until our source is folded to completion.
7035
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007036 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007037
7038 // Find out whether the last index in the source GEP is a sequential idx.
7039 bool EndsWithSequential = false;
7040 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7041 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007042 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007043
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007044 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007045 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007046 // Replace: gep (gep %P, long B), long A, ...
7047 // With: T = long A+B; gep %P, T, ...
7048 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007049 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007050 if (SO1 == Constant::getNullValue(SO1->getType())) {
7051 Sum = GO1;
7052 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7053 Sum = SO1;
7054 } else {
7055 // If they aren't the same type, convert both to an integer of the
7056 // target's pointer size.
7057 if (SO1->getType() != GO1->getType()) {
7058 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7059 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7060 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7061 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7062 } else {
7063 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007064 if (SO1->getType()->getPrimitiveSize() == PS) {
7065 // Convert GO1 to SO1's type.
7066 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7067
7068 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7069 // Convert SO1 to GO1's type.
7070 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7071 } else {
7072 const Type *PT = TD->getIntPtrType();
7073 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7074 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7075 }
7076 }
7077 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007078 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7079 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7080 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007081 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7082 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007083 }
Chris Lattner69193f92004-04-05 01:30:19 +00007084 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007085
7086 // Recycle the GEP we already have if possible.
7087 if (SrcGEPOperands.size() == 2) {
7088 GEP.setOperand(0, SrcGEPOperands[0]);
7089 GEP.setOperand(1, Sum);
7090 return &GEP;
7091 } else {
7092 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7093 SrcGEPOperands.end()-1);
7094 Indices.push_back(Sum);
7095 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7096 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007097 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007098 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007099 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007100 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007101 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7102 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007103 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7104 }
7105
7106 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007107 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007108
Chris Lattner5f667a62004-05-07 22:09:22 +00007109 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007110 // GEP of global variable. If all of the indices for this GEP are
7111 // constants, we can promote this to a constexpr instead of an instruction.
7112
7113 // Scan for nonconstants...
7114 std::vector<Constant*> Indices;
7115 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7116 for (; I != E && isa<Constant>(*I); ++I)
7117 Indices.push_back(cast<Constant>(*I));
7118
7119 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007120 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007121
7122 // Replace all uses of the GEP with the new constexpr...
7123 return ReplaceInstUsesWith(GEP, CE);
7124 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007125 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7126 if (!isa<PointerType>(X->getType())) {
7127 // Not interesting. Source pointer must be a cast from pointer.
7128 } else if (HasZeroPointerIndex) {
7129 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7130 // into : GEP [10 x ubyte]* X, long 0, ...
7131 //
7132 // This occurs when the program declares an array extern like "int X[];"
7133 //
7134 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7135 const PointerType *XTy = cast<PointerType>(X->getType());
7136 if (const ArrayType *XATy =
7137 dyn_cast<ArrayType>(XTy->getElementType()))
7138 if (const ArrayType *CATy =
7139 dyn_cast<ArrayType>(CPTy->getElementType()))
7140 if (CATy->getElementType() == XATy->getElementType()) {
7141 // At this point, we know that the cast source type is a pointer
7142 // to an array of the same type as the destination pointer
7143 // array. Because the array type is never stepped over (there
7144 // is a leading zero) we can fold the cast into this GEP.
7145 GEP.setOperand(0, X);
7146 return &GEP;
7147 }
7148 } else if (GEP.getNumOperands() == 2) {
7149 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007150 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7151 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007152 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7153 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7154 if (isa<ArrayType>(SrcElTy) &&
7155 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7156 TD->getTypeSize(ResElTy)) {
7157 Value *V = InsertNewInstBefore(
7158 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7159 GEP.getOperand(1), GEP.getName()), GEP);
7160 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007161 }
Chris Lattner2a893292005-09-13 18:36:04 +00007162
7163 // Transform things like:
7164 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7165 // (where tmp = 8*tmp2) into:
7166 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7167
7168 if (isa<ArrayType>(SrcElTy) &&
7169 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7170 uint64_t ArrayEltSize =
7171 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7172
7173 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7174 // allow either a mul, shift, or constant here.
7175 Value *NewIdx = 0;
7176 ConstantInt *Scale = 0;
7177 if (ArrayEltSize == 1) {
7178 NewIdx = GEP.getOperand(1);
7179 Scale = ConstantInt::get(NewIdx->getType(), 1);
7180 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007181 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007182 Scale = CI;
7183 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7184 if (Inst->getOpcode() == Instruction::Shl &&
7185 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007186 unsigned ShAmt =
7187 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007188 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007189 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007190 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007191 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007192 NewIdx = Inst->getOperand(0);
7193 } else if (Inst->getOpcode() == Instruction::Mul &&
7194 isa<ConstantInt>(Inst->getOperand(1))) {
7195 Scale = cast<ConstantInt>(Inst->getOperand(1));
7196 NewIdx = Inst->getOperand(0);
7197 }
7198 }
7199
7200 // If the index will be to exactly the right offset with the scale taken
7201 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007202 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7203 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7204 Scale = ConstantInt::get(Scale->getType(),
7205 Scale->getZExtValue() / ArrayEltSize);
7206 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007207 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7208 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7209 NewIdx = InsertNewInstBefore(Sc, GEP);
7210 }
7211
7212 // Insert the new GEP instruction.
7213 Instruction *Idx =
7214 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7215 NewIdx, GEP.getName());
7216 Idx = InsertNewInstBefore(Idx, GEP);
7217 return new CastInst(Idx, GEP.getType());
7218 }
7219 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007220 }
Chris Lattnerca081252001-12-14 16:52:21 +00007221 }
7222
Chris Lattnerca081252001-12-14 16:52:21 +00007223 return 0;
7224}
7225
Chris Lattner1085bdf2002-11-04 16:18:53 +00007226Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7227 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7228 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007229 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7230 const Type *NewTy =
7231 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007232 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007233
7234 // Create and insert the replacement instruction...
7235 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007236 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007237 else {
7238 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007239 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007240 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007241
7242 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007243
Chris Lattner1085bdf2002-11-04 16:18:53 +00007244 // Scan to the end of the allocation instructions, to skip over a block of
7245 // allocas if possible...
7246 //
7247 BasicBlock::iterator It = New;
7248 while (isa<AllocationInst>(*It)) ++It;
7249
7250 // Now that I is pointing to the first non-allocation-inst in the block,
7251 // insert our getelementptr instruction...
7252 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007253 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7254 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7255 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007256
7257 // Now make everything use the getelementptr instead of the original
7258 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007259 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007260 } else if (isa<UndefValue>(AI.getArraySize())) {
7261 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007262 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007263
7264 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7265 // Note that we only do this for alloca's, because malloc should allocate and
7266 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007267 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007268 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007269 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7270
Chris Lattner1085bdf2002-11-04 16:18:53 +00007271 return 0;
7272}
7273
Chris Lattner8427bff2003-12-07 01:24:23 +00007274Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7275 Value *Op = FI.getOperand(0);
7276
7277 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7278 if (CastInst *CI = dyn_cast<CastInst>(Op))
7279 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7280 FI.setOperand(0, CI->getOperand(0));
7281 return &FI;
7282 }
7283
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007284 // free undef -> unreachable.
7285 if (isa<UndefValue>(Op)) {
7286 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007287 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007288 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7289 return EraseInstFromFunction(FI);
7290 }
7291
Chris Lattnerf3a36602004-02-28 04:57:37 +00007292 // If we have 'free null' delete the instruction. This can happen in stl code
7293 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007294 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007295 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007296
Chris Lattner8427bff2003-12-07 01:24:23 +00007297 return 0;
7298}
7299
7300
Chris Lattner72684fe2005-01-31 05:51:45 +00007301/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007302static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7303 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007304 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007305
7306 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007307 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007308 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007309
Chris Lattnerebca4762006-04-02 05:37:12 +00007310 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7311 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007312 // If the source is an array, the code below will not succeed. Check to
7313 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7314 // constants.
7315 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7316 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7317 if (ASrcTy->getNumElements() != 0) {
7318 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7319 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7320 SrcTy = cast<PointerType>(CastOp->getType());
7321 SrcPTy = SrcTy->getElementType();
7322 }
7323
Chris Lattnerebca4762006-04-02 05:37:12 +00007324 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7325 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007326 // Do not allow turning this into a load of an integer, which is then
7327 // casted to a pointer, this pessimizes pointer analysis a lot.
7328 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007329 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007330 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007331
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007332 // Okay, we are casting from one integer or pointer type to another of
7333 // the same size. Instead of casting the pointer before the load, cast
7334 // the result of the loaded value.
7335 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7336 CI->getName(),
7337 LI.isVolatile()),LI);
7338 // Now cast the result of the load.
7339 return new CastInst(NewLoad, LI.getType());
7340 }
Chris Lattner35e24772004-07-13 01:49:43 +00007341 }
7342 }
7343 return 0;
7344}
7345
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007346/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007347/// from this value cannot trap. If it is not obviously safe to load from the
7348/// specified pointer, we do a quick local scan of the basic block containing
7349/// ScanFrom, to determine if the address is already accessed.
7350static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7351 // If it is an alloca or global variable, it is always safe to load from.
7352 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7353
7354 // Otherwise, be a little bit agressive by scanning the local block where we
7355 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007356 // from/to. If so, the previous load or store would have already trapped,
7357 // so there is no harm doing an extra load (also, CSE will later eliminate
7358 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007359 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7360
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007361 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007362 --BBI;
7363
7364 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7365 if (LI->getOperand(0) == V) return true;
7366 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7367 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007368
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007369 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007370 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007371}
7372
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007373Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7374 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007375
Chris Lattnera9d84e32005-05-01 04:24:53 +00007376 // load (cast X) --> cast (load X) iff safe
7377 if (CastInst *CI = dyn_cast<CastInst>(Op))
7378 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7379 return Res;
7380
7381 // None of the following transforms are legal for volatile loads.
7382 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007383
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007384 if (&LI.getParent()->front() != &LI) {
7385 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007386 // If the instruction immediately before this is a store to the same
7387 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007388 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7389 if (SI->getOperand(1) == LI.getOperand(0))
7390 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007391 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7392 if (LIB->getOperand(0) == LI.getOperand(0))
7393 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007394 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007395
7396 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7397 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7398 isa<UndefValue>(GEPI->getOperand(0))) {
7399 // Insert a new store to null instruction before the load to indicate
7400 // that this code is not reachable. We do this instead of inserting
7401 // an unreachable instruction directly because we cannot modify the
7402 // CFG.
7403 new StoreInst(UndefValue::get(LI.getType()),
7404 Constant::getNullValue(Op->getType()), &LI);
7405 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7406 }
7407
Chris Lattner81a7a232004-10-16 18:11:37 +00007408 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007409 // load null/undef -> undef
7410 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007411 // Insert a new store to null instruction before the load to indicate that
7412 // this code is not reachable. We do this instead of inserting an
7413 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007414 new StoreInst(UndefValue::get(LI.getType()),
7415 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007416 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007417 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007418
Chris Lattner81a7a232004-10-16 18:11:37 +00007419 // Instcombine load (constant global) into the value loaded.
7420 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7421 if (GV->isConstant() && !GV->isExternal())
7422 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007423
Chris Lattner81a7a232004-10-16 18:11:37 +00007424 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7426 if (CE->getOpcode() == Instruction::GetElementPtr) {
7427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7428 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007429 if (Constant *V =
7430 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007431 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007432 if (CE->getOperand(0)->isNullValue()) {
7433 // Insert a new store to null instruction before the load to indicate
7434 // that this code is not reachable. We do this instead of inserting
7435 // an unreachable instruction directly because we cannot modify the
7436 // CFG.
7437 new StoreInst(UndefValue::get(LI.getType()),
7438 Constant::getNullValue(Op->getType()), &LI);
7439 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7440 }
7441
Chris Lattner81a7a232004-10-16 18:11:37 +00007442 } else if (CE->getOpcode() == Instruction::Cast) {
7443 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7444 return Res;
7445 }
7446 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007447
Chris Lattnera9d84e32005-05-01 04:24:53 +00007448 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007449 // Change select and PHI nodes to select values instead of addresses: this
7450 // helps alias analysis out a lot, allows many others simplifications, and
7451 // exposes redundancy in the code.
7452 //
7453 // Note that we cannot do the transformation unless we know that the
7454 // introduced loads cannot trap! Something like this is valid as long as
7455 // the condition is always false: load (select bool %C, int* null, int* %G),
7456 // but it would not be valid if we transformed it to load from null
7457 // unconditionally.
7458 //
7459 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7460 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007461 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7462 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007463 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007464 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007465 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007466 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007467 return new SelectInst(SI->getCondition(), V1, V2);
7468 }
7469
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007470 // load (select (cond, null, P)) -> load P
7471 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7472 if (C->isNullValue()) {
7473 LI.setOperand(0, SI->getOperand(2));
7474 return &LI;
7475 }
7476
7477 // load (select (cond, P, null)) -> load P
7478 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7479 if (C->isNullValue()) {
7480 LI.setOperand(0, SI->getOperand(1));
7481 return &LI;
7482 }
7483
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007484 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7485 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007486 bool Safe = PN->getParent() == LI.getParent();
7487
7488 // Scan all of the instructions between the PHI and the load to make
7489 // sure there are no instructions that might possibly alter the value
7490 // loaded from the PHI.
7491 if (Safe) {
7492 BasicBlock::iterator I = &LI;
7493 for (--I; !isa<PHINode>(I); --I)
7494 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7495 Safe = false;
7496 break;
7497 }
7498 }
7499
7500 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007501 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007502 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007503 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007504
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007505 if (Safe) {
7506 // Create the PHI.
7507 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7508 InsertNewInstBefore(NewPN, *PN);
7509 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7510
7511 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7512 BasicBlock *BB = PN->getIncomingBlock(i);
7513 Value *&TheLoad = LoadMap[BB];
7514 if (TheLoad == 0) {
7515 Value *InVal = PN->getIncomingValue(i);
7516 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7517 InVal->getName()+".val"),
7518 *BB->getTerminator());
7519 }
7520 NewPN->addIncoming(TheLoad, BB);
7521 }
7522 return ReplaceInstUsesWith(LI, NewPN);
7523 }
7524 }
7525 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007526 return 0;
7527}
7528
Chris Lattner72684fe2005-01-31 05:51:45 +00007529/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7530/// when possible.
7531static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7532 User *CI = cast<User>(SI.getOperand(1));
7533 Value *CastOp = CI->getOperand(0);
7534
7535 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7536 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7537 const Type *SrcPTy = SrcTy->getElementType();
7538
7539 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7540 // If the source is an array, the code below will not succeed. Check to
7541 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7542 // constants.
7543 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7544 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7545 if (ASrcTy->getNumElements() != 0) {
7546 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7547 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7548 SrcTy = cast<PointerType>(CastOp->getType());
7549 SrcPTy = SrcTy->getElementType();
7550 }
7551
7552 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007553 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007554 IC.getTargetData().getTypeSize(DestPTy)) {
7555
7556 // Okay, we are casting from one integer or pointer type to another of
7557 // the same size. Instead of casting the pointer before the store, cast
7558 // the value to be stored.
7559 Value *NewCast;
7560 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7561 NewCast = ConstantExpr::getCast(C, SrcPTy);
7562 else
7563 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7564 SrcPTy,
7565 SI.getOperand(0)->getName()+".c"), SI);
7566
7567 return new StoreInst(NewCast, CastOp);
7568 }
7569 }
7570 }
7571 return 0;
7572}
7573
Chris Lattner31f486c2005-01-31 05:36:43 +00007574Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7575 Value *Val = SI.getOperand(0);
7576 Value *Ptr = SI.getOperand(1);
7577
7578 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007579 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007580 ++NumCombined;
7581 return 0;
7582 }
7583
Chris Lattner5997cf92006-02-08 03:25:32 +00007584 // Do really simple DSE, to catch cases where there are several consequtive
7585 // stores to the same location, separated by a few arithmetic operations. This
7586 // situation often occurs with bitfield accesses.
7587 BasicBlock::iterator BBI = &SI;
7588 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7589 --ScanInsts) {
7590 --BBI;
7591
7592 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7593 // Prev store isn't volatile, and stores to the same location?
7594 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7595 ++NumDeadStore;
7596 ++BBI;
7597 EraseInstFromFunction(*PrevSI);
7598 continue;
7599 }
7600 break;
7601 }
7602
Chris Lattnerdab43b22006-05-26 19:19:20 +00007603 // If this is a load, we have to stop. However, if the loaded value is from
7604 // the pointer we're loading and is producing the pointer we're storing,
7605 // then *this* store is dead (X = load P; store X -> P).
7606 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7607 if (LI == Val && LI->getOperand(0) == Ptr) {
7608 EraseInstFromFunction(SI);
7609 ++NumCombined;
7610 return 0;
7611 }
7612 // Otherwise, this is a load from some other location. Stores before it
7613 // may not be dead.
7614 break;
7615 }
7616
Chris Lattner5997cf92006-02-08 03:25:32 +00007617 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007618 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007619 break;
7620 }
7621
7622
7623 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007624
7625 // store X, null -> turns into 'unreachable' in SimplifyCFG
7626 if (isa<ConstantPointerNull>(Ptr)) {
7627 if (!isa<UndefValue>(Val)) {
7628 SI.setOperand(0, UndefValue::get(Val->getType()));
7629 if (Instruction *U = dyn_cast<Instruction>(Val))
7630 WorkList.push_back(U); // Dropped a use.
7631 ++NumCombined;
7632 }
7633 return 0; // Do not modify these!
7634 }
7635
7636 // store undef, Ptr -> noop
7637 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007638 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007639 ++NumCombined;
7640 return 0;
7641 }
7642
Chris Lattner72684fe2005-01-31 05:51:45 +00007643 // If the pointer destination is a cast, see if we can fold the cast into the
7644 // source instead.
7645 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7646 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7647 return Res;
7648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7649 if (CE->getOpcode() == Instruction::Cast)
7650 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7651 return Res;
7652
Chris Lattner219175c2005-09-12 23:23:25 +00007653
7654 // If this store is the last instruction in the basic block, and if the block
7655 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007656 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007657 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7658 if (BI->isUnconditional()) {
7659 // Check to see if the successor block has exactly two incoming edges. If
7660 // so, see if the other predecessor contains a store to the same location.
7661 // if so, insert a PHI node (if needed) and move the stores down.
7662 BasicBlock *Dest = BI->getSuccessor(0);
7663
7664 pred_iterator PI = pred_begin(Dest);
7665 BasicBlock *Other = 0;
7666 if (*PI != BI->getParent())
7667 Other = *PI;
7668 ++PI;
7669 if (PI != pred_end(Dest)) {
7670 if (*PI != BI->getParent())
7671 if (Other)
7672 Other = 0;
7673 else
7674 Other = *PI;
7675 if (++PI != pred_end(Dest))
7676 Other = 0;
7677 }
7678 if (Other) { // If only one other pred...
7679 BBI = Other->getTerminator();
7680 // Make sure this other block ends in an unconditional branch and that
7681 // there is an instruction before the branch.
7682 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7683 BBI != Other->begin()) {
7684 --BBI;
7685 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7686
7687 // If this instruction is a store to the same location.
7688 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7689 // Okay, we know we can perform this transformation. Insert a PHI
7690 // node now if we need it.
7691 Value *MergedVal = OtherStore->getOperand(0);
7692 if (MergedVal != SI.getOperand(0)) {
7693 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7694 PN->reserveOperandSpace(2);
7695 PN->addIncoming(SI.getOperand(0), SI.getParent());
7696 PN->addIncoming(OtherStore->getOperand(0), Other);
7697 MergedVal = InsertNewInstBefore(PN, Dest->front());
7698 }
7699
7700 // Advance to a place where it is safe to insert the new store and
7701 // insert it.
7702 BBI = Dest->begin();
7703 while (isa<PHINode>(BBI)) ++BBI;
7704 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7705 OtherStore->isVolatile()), *BBI);
7706
7707 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007708 EraseInstFromFunction(SI);
7709 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007710 ++NumCombined;
7711 return 0;
7712 }
7713 }
7714 }
7715 }
7716
Chris Lattner31f486c2005-01-31 05:36:43 +00007717 return 0;
7718}
7719
7720
Chris Lattner9eef8a72003-06-04 04:46:00 +00007721Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7722 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007723 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007724 BasicBlock *TrueDest;
7725 BasicBlock *FalseDest;
7726 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7727 !isa<Constant>(X)) {
7728 // Swap Destinations and condition...
7729 BI.setCondition(X);
7730 BI.setSuccessor(0, FalseDest);
7731 BI.setSuccessor(1, TrueDest);
7732 return &BI;
7733 }
7734
7735 // Cannonicalize setne -> seteq
7736 Instruction::BinaryOps Op; Value *Y;
7737 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7738 TrueDest, FalseDest)))
7739 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7740 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7741 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7742 std::string Name = I->getName(); I->setName("");
7743 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7744 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007745 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007746 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007747 BI.setSuccessor(0, FalseDest);
7748 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007749 removeFromWorkList(I);
7750 I->getParent()->getInstList().erase(I);
7751 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007752 return &BI;
7753 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007754
Chris Lattner9eef8a72003-06-04 04:46:00 +00007755 return 0;
7756}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007757
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007758Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7759 Value *Cond = SI.getCondition();
7760 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7761 if (I->getOpcode() == Instruction::Add)
7762 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7763 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7764 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007765 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007766 AddRHS));
7767 SI.setOperand(0, I->getOperand(0));
7768 WorkList.push_back(I);
7769 return &SI;
7770 }
7771 }
7772 return 0;
7773}
7774
Chris Lattner6bc98652006-03-05 00:22:33 +00007775/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7776/// is to leave as a vector operation.
7777static bool CheapToScalarize(Value *V, bool isConstant) {
7778 if (isa<ConstantAggregateZero>(V))
7779 return true;
7780 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7781 if (isConstant) return true;
7782 // If all elts are the same, we can extract.
7783 Constant *Op0 = C->getOperand(0);
7784 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7785 if (C->getOperand(i) != Op0)
7786 return false;
7787 return true;
7788 }
7789 Instruction *I = dyn_cast<Instruction>(V);
7790 if (!I) return false;
7791
7792 // Insert element gets simplified to the inserted element or is deleted if
7793 // this is constant idx extract element and its a constant idx insertelt.
7794 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7795 isa<ConstantInt>(I->getOperand(2)))
7796 return true;
7797 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7798 return true;
7799 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7800 if (BO->hasOneUse() &&
7801 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7802 CheapToScalarize(BO->getOperand(1), isConstant)))
7803 return true;
7804
7805 return false;
7806}
7807
Chris Lattner12249be2006-05-25 23:48:38 +00007808/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7809/// elements into values that are larger than the #elts in the input.
7810static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7811 unsigned NElts = SVI->getType()->getNumElements();
7812 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7813 return std::vector<unsigned>(NElts, 0);
7814 if (isa<UndefValue>(SVI->getOperand(2)))
7815 return std::vector<unsigned>(NElts, 2*NElts);
7816
7817 std::vector<unsigned> Result;
7818 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7819 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7820 if (isa<UndefValue>(CP->getOperand(i)))
7821 Result.push_back(NElts*2); // undef -> 8
7822 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007823 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007824 return Result;
7825}
7826
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007827/// FindScalarElement - Given a vector and an element number, see if the scalar
7828/// value is already around as a register, for example if it were inserted then
7829/// extracted from the vector.
7830static Value *FindScalarElement(Value *V, unsigned EltNo) {
7831 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7832 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007833 unsigned Width = PTy->getNumElements();
7834 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007835 return UndefValue::get(PTy->getElementType());
7836
7837 if (isa<UndefValue>(V))
7838 return UndefValue::get(PTy->getElementType());
7839 else if (isa<ConstantAggregateZero>(V))
7840 return Constant::getNullValue(PTy->getElementType());
7841 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7842 return CP->getOperand(EltNo);
7843 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7844 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007845 if (!isa<ConstantInt>(III->getOperand(2)))
7846 return 0;
7847 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007848
7849 // If this is an insert to the element we are looking for, return the
7850 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007851 if (EltNo == IIElt)
7852 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007853
7854 // Otherwise, the insertelement doesn't modify the value, recurse on its
7855 // vector input.
7856 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007857 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007858 unsigned InEl = getShuffleMask(SVI)[EltNo];
7859 if (InEl < Width)
7860 return FindScalarElement(SVI->getOperand(0), InEl);
7861 else if (InEl < Width*2)
7862 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7863 else
7864 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007865 }
7866
7867 // Otherwise, we don't know.
7868 return 0;
7869}
7870
Robert Bocchinoa8352962006-01-13 22:48:06 +00007871Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007872
Chris Lattner92346c32006-03-31 18:25:14 +00007873 // If packed val is undef, replace extract with scalar undef.
7874 if (isa<UndefValue>(EI.getOperand(0)))
7875 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7876
7877 // If packed val is constant 0, replace extract with scalar 0.
7878 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7879 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7880
Robert Bocchinoa8352962006-01-13 22:48:06 +00007881 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7882 // If packed val is constant with uniform operands, replace EI
7883 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007884 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007885 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007886 if (C->getOperand(i) != op0) {
7887 op0 = 0;
7888 break;
7889 }
7890 if (op0)
7891 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007892 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007893
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007894 // If extracting a specified index from the vector, see if we can recursively
7895 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007896 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007897 // This instruction only demands the single element from the input vector.
7898 // If the input vector has a single use, simplify it based on this use
7899 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007900 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00007901 if (EI.getOperand(0)->hasOneUse()) {
7902 uint64_t UndefElts;
7903 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00007904 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00007905 UndefElts)) {
7906 EI.setOperand(0, V);
7907 return &EI;
7908 }
7909 }
7910
Reid Spencere0fc4df2006-10-20 07:07:24 +00007911 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007912 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007913 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007914
Chris Lattner83f65782006-05-25 22:53:38 +00007915 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007916 if (I->hasOneUse()) {
7917 // Push extractelement into predecessor operation if legal and
7918 // profitable to do so
7919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007920 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7921 if (CheapToScalarize(BO, isConstantElt)) {
7922 ExtractElementInst *newEI0 =
7923 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7924 EI.getName()+".lhs");
7925 ExtractElementInst *newEI1 =
7926 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7927 EI.getName()+".rhs");
7928 InsertNewInstBefore(newEI0, EI);
7929 InsertNewInstBefore(newEI1, EI);
7930 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7931 }
7932 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007933 Value *Ptr = InsertCastBefore(I->getOperand(0),
7934 PointerType::get(EI.getType()), EI);
7935 GetElementPtrInst *GEP =
7936 new GetElementPtrInst(Ptr, EI.getOperand(1),
7937 I->getName() + ".gep");
7938 InsertNewInstBefore(GEP, EI);
7939 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007940 }
7941 }
7942 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7943 // Extracting the inserted element?
7944 if (IE->getOperand(2) == EI.getOperand(1))
7945 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7946 // If the inserted and extracted elements are constants, they must not
7947 // be the same value, extract from the pre-inserted value instead.
7948 if (isa<Constant>(IE->getOperand(2)) &&
7949 isa<Constant>(EI.getOperand(1))) {
7950 AddUsesToWorkList(EI);
7951 EI.setOperand(0, IE->getOperand(0));
7952 return &EI;
7953 }
7954 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7955 // If this is extracting an element from a shufflevector, figure out where
7956 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007957 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7958 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00007959 Value *Src;
7960 if (SrcIdx < SVI->getType()->getNumElements())
7961 Src = SVI->getOperand(0);
7962 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7963 SrcIdx -= SVI->getType()->getNumElements();
7964 Src = SVI->getOperand(1);
7965 } else {
7966 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007967 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00007968 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007969 }
7970 }
Chris Lattner83f65782006-05-25 22:53:38 +00007971 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007972 return 0;
7973}
7974
Chris Lattner90951862006-04-16 00:51:47 +00007975/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7976/// elements from either LHS or RHS, return the shuffle mask and true.
7977/// Otherwise, return false.
7978static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7979 std::vector<Constant*> &Mask) {
7980 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7981 "Invalid CollectSingleShuffleElements");
7982 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7983
7984 if (isa<UndefValue>(V)) {
7985 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7986 return true;
7987 } else if (V == LHS) {
7988 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00007989 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00007990 return true;
7991 } else if (V == RHS) {
7992 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00007993 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00007994 return true;
7995 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7996 // If this is an insert of an extract from some other vector, include it.
7997 Value *VecOp = IEI->getOperand(0);
7998 Value *ScalarOp = IEI->getOperand(1);
7999 Value *IdxOp = IEI->getOperand(2);
8000
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008001 if (!isa<ConstantInt>(IdxOp))
8002 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008003 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008004
8005 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8006 // Okay, we can handle this if the vector we are insertinting into is
8007 // transitively ok.
8008 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8009 // If so, update the mask to reflect the inserted undef.
8010 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8011 return true;
8012 }
8013 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8014 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008015 EI->getOperand(0)->getType() == V->getType()) {
8016 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008017 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008018
8019 // This must be extracting from either LHS or RHS.
8020 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8021 // Okay, we can handle this if the vector we are insertinting into is
8022 // transitively ok.
8023 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8024 // If so, update the mask to reflect the inserted value.
8025 if (EI->getOperand(0) == LHS) {
8026 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008027 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008028 } else {
8029 assert(EI->getOperand(0) == RHS);
8030 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008031 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008032
8033 }
8034 return true;
8035 }
8036 }
8037 }
8038 }
8039 }
8040 // TODO: Handle shufflevector here!
8041
8042 return false;
8043}
8044
8045/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8046/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8047/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008048static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008049 Value *&RHS) {
8050 assert(isa<PackedType>(V->getType()) &&
8051 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008052 "Invalid shuffle!");
8053 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8054
8055 if (isa<UndefValue>(V)) {
8056 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8057 return V;
8058 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008059 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008060 return V;
8061 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8062 // If this is an insert of an extract from some other vector, include it.
8063 Value *VecOp = IEI->getOperand(0);
8064 Value *ScalarOp = IEI->getOperand(1);
8065 Value *IdxOp = IEI->getOperand(2);
8066
8067 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8068 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8069 EI->getOperand(0)->getType() == V->getType()) {
8070 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008071 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8072 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008073
8074 // Either the extracted from or inserted into vector must be RHSVec,
8075 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008076 if (EI->getOperand(0) == RHS || RHS == 0) {
8077 RHS = EI->getOperand(0);
8078 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008079 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008080 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008081 return V;
8082 }
8083
Chris Lattner90951862006-04-16 00:51:47 +00008084 if (VecOp == RHS) {
8085 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008086 // Everything but the extracted element is replaced with the RHS.
8087 for (unsigned i = 0; i != NumElts; ++i) {
8088 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008089 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008090 }
8091 return V;
8092 }
Chris Lattner90951862006-04-16 00:51:47 +00008093
8094 // If this insertelement is a chain that comes from exactly these two
8095 // vectors, return the vector and the effective shuffle.
8096 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8097 return EI->getOperand(0);
8098
Chris Lattner39fac442006-04-15 01:39:45 +00008099 }
8100 }
8101 }
Chris Lattner90951862006-04-16 00:51:47 +00008102 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008103
8104 // Otherwise, can't do anything fancy. Return an identity vector.
8105 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008106 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008107 return V;
8108}
8109
8110Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8111 Value *VecOp = IE.getOperand(0);
8112 Value *ScalarOp = IE.getOperand(1);
8113 Value *IdxOp = IE.getOperand(2);
8114
8115 // If the inserted element was extracted from some other vector, and if the
8116 // indexes are constant, try to turn this into a shufflevector operation.
8117 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8118 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8119 EI->getOperand(0)->getType() == IE.getType()) {
8120 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008121 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8122 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008123
8124 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8125 return ReplaceInstUsesWith(IE, VecOp);
8126
8127 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8128 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8129
8130 // If we are extracting a value from a vector, then inserting it right
8131 // back into the same place, just use the input vector.
8132 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8133 return ReplaceInstUsesWith(IE, VecOp);
8134
8135 // We could theoretically do this for ANY input. However, doing so could
8136 // turn chains of insertelement instructions into a chain of shufflevector
8137 // instructions, and right now we do not merge shufflevectors. As such,
8138 // only do this in a situation where it is clear that there is benefit.
8139 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8140 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8141 // the values of VecOp, except then one read from EIOp0.
8142 // Build a new shuffle mask.
8143 std::vector<Constant*> Mask;
8144 if (isa<UndefValue>(VecOp))
8145 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8146 else {
8147 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008148 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008149 NumVectorElts));
8150 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008151 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008152 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8153 ConstantPacked::get(Mask));
8154 }
8155
8156 // If this insertelement isn't used by some other insertelement, turn it
8157 // (and any insertelements it points to), into one big shuffle.
8158 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8159 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008160 Value *RHS = 0;
8161 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8162 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8163 // We now have a shuffle of LHS, RHS, Mask.
8164 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008165 }
8166 }
8167 }
8168
8169 return 0;
8170}
8171
8172
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008173Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8174 Value *LHS = SVI.getOperand(0);
8175 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008176 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008177
8178 bool MadeChange = false;
8179
Chris Lattner2deeaea2006-10-05 06:55:50 +00008180 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008181 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008182 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8183
Chris Lattner39fac442006-04-15 01:39:45 +00008184 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8185 // the undef, change them to undefs.
8186
Chris Lattner12249be2006-05-25 23:48:38 +00008187 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8188 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8189 if (LHS == RHS || isa<UndefValue>(LHS)) {
8190 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008191 // shuffle(undef,undef,mask) -> undef.
8192 return ReplaceInstUsesWith(SVI, LHS);
8193 }
8194
Chris Lattner12249be2006-05-25 23:48:38 +00008195 // Remap any references to RHS to use LHS.
8196 std::vector<Constant*> Elts;
8197 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008198 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008199 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008200 else {
8201 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8202 (Mask[i] < e && isa<UndefValue>(LHS)))
8203 Mask[i] = 2*e; // Turn into undef.
8204 else
8205 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008206 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008207 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008208 }
Chris Lattner12249be2006-05-25 23:48:38 +00008209 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008210 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008211 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008212 LHS = SVI.getOperand(0);
8213 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008214 MadeChange = true;
8215 }
8216
Chris Lattner0e477162006-05-26 00:29:06 +00008217 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008218 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008219
Chris Lattner12249be2006-05-25 23:48:38 +00008220 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8221 if (Mask[i] >= e*2) continue; // Ignore undef values.
8222 // Is this an identity shuffle of the LHS value?
8223 isLHSID &= (Mask[i] == i);
8224
8225 // Is this an identity shuffle of the RHS value?
8226 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008227 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008228
Chris Lattner12249be2006-05-25 23:48:38 +00008229 // Eliminate identity shuffles.
8230 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8231 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008232
Chris Lattner0e477162006-05-26 00:29:06 +00008233 // If the LHS is a shufflevector itself, see if we can combine it with this
8234 // one without producing an unusual shuffle. Here we are really conservative:
8235 // we are absolutely afraid of producing a shuffle mask not in the input
8236 // program, because the code gen may not be smart enough to turn a merged
8237 // shuffle into two specific shuffles: it may produce worse code. As such,
8238 // we only merge two shuffles if the result is one of the two input shuffle
8239 // masks. In this case, merging the shuffles just removes one instruction,
8240 // which we know is safe. This is good for things like turning:
8241 // (splat(splat)) -> splat.
8242 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8243 if (isa<UndefValue>(RHS)) {
8244 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8245
8246 std::vector<unsigned> NewMask;
8247 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8248 if (Mask[i] >= 2*e)
8249 NewMask.push_back(2*e);
8250 else
8251 NewMask.push_back(LHSMask[Mask[i]]);
8252
8253 // If the result mask is equal to the src shuffle or this shuffle mask, do
8254 // the replacement.
8255 if (NewMask == LHSMask || NewMask == Mask) {
8256 std::vector<Constant*> Elts;
8257 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8258 if (NewMask[i] >= e*2) {
8259 Elts.push_back(UndefValue::get(Type::UIntTy));
8260 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008261 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008262 }
8263 }
8264 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8265 LHSSVI->getOperand(1),
8266 ConstantPacked::get(Elts));
8267 }
8268 }
8269 }
8270
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008271 return MadeChange ? &SVI : 0;
8272}
8273
8274
Robert Bocchinoa8352962006-01-13 22:48:06 +00008275
Chris Lattner99f48c62002-09-02 04:59:56 +00008276void InstCombiner::removeFromWorkList(Instruction *I) {
8277 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8278 WorkList.end());
8279}
8280
Chris Lattner39c98bb2004-12-08 23:43:58 +00008281
8282/// TryToSinkInstruction - Try to move the specified instruction from its
8283/// current block into the beginning of DestBlock, which can only happen if it's
8284/// safe to move the instruction past all of the instructions between it and the
8285/// end of its block.
8286static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8287 assert(I->hasOneUse() && "Invariants didn't hold!");
8288
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008289 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8290 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008291
Chris Lattner39c98bb2004-12-08 23:43:58 +00008292 // Do not sink alloca instructions out of the entry block.
8293 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8294 return false;
8295
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008296 // We can only sink load instructions if there is nothing between the load and
8297 // the end of block that could change the value.
8298 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008299 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8300 Scan != E; ++Scan)
8301 if (Scan->mayWriteToMemory())
8302 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008303 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008304
8305 BasicBlock::iterator InsertPos = DestBlock->begin();
8306 while (isa<PHINode>(InsertPos)) ++InsertPos;
8307
Chris Lattner9f269e42005-08-08 19:11:57 +00008308 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008309 ++NumSunkInst;
8310 return true;
8311}
8312
Chris Lattner1443bc52006-05-11 17:11:52 +00008313/// OptimizeConstantExpr - Given a constant expression and target data layout
8314/// information, symbolically evaluation the constant expr to something simpler
8315/// if possible.
8316static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8317 if (!TD) return CE;
8318
8319 Constant *Ptr = CE->getOperand(0);
8320 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8321 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8322 // If this is a constant expr gep that is effectively computing an
8323 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8324 bool isFoldableGEP = true;
8325 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8326 if (!isa<ConstantInt>(CE->getOperand(i)))
8327 isFoldableGEP = false;
8328 if (isFoldableGEP) {
8329 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8330 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008331 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008332 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8333 return ConstantExpr::getCast(C, CE->getType());
8334 }
8335 }
8336
8337 return CE;
8338}
8339
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008340
8341/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8342/// all reachable code to the worklist.
8343///
8344/// This has a couple of tricks to make the code faster and more powerful. In
8345/// particular, we constant fold and DCE instructions as we go, to avoid adding
8346/// them to the worklist (this significantly speeds up instcombine on code where
8347/// many instructions are dead or constant). Additionally, if we find a branch
8348/// whose condition is a known constant, we only visit the reachable successors.
8349///
8350static void AddReachableCodeToWorklist(BasicBlock *BB,
8351 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008352 std::vector<Instruction*> &WorkList,
8353 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008354 // We have now visited this block! If we've already been here, bail out.
8355 if (!Visited.insert(BB).second) return;
8356
8357 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8358 Instruction *Inst = BBI++;
8359
8360 // DCE instruction if trivially dead.
8361 if (isInstructionTriviallyDead(Inst)) {
8362 ++NumDeadInst;
8363 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8364 Inst->eraseFromParent();
8365 continue;
8366 }
8367
8368 // ConstantProp instruction if trivially constant.
8369 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8371 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008372 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8373 Inst->replaceAllUsesWith(C);
8374 ++NumConstProp;
8375 Inst->eraseFromParent();
8376 continue;
8377 }
8378
8379 WorkList.push_back(Inst);
8380 }
8381
8382 // Recursively visit successors. If this is a branch or switch on a constant,
8383 // only visit the reachable successor.
8384 TerminatorInst *TI = BB->getTerminator();
8385 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8386 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8387 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008388 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8389 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008390 return;
8391 }
8392 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8393 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8394 // See if this is an explicit destination.
8395 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8396 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008397 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008398 return;
8399 }
8400
8401 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008402 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008403 return;
8404 }
8405 }
8406
8407 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008408 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008409}
8410
Chris Lattner113f4f42002-06-25 16:13:24 +00008411bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008412 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008413 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008414
Chris Lattner4ed40f72005-07-07 20:40:38 +00008415 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008416 // Do a depth-first traversal of the function, populate the worklist with
8417 // the reachable instructions. Ignore blocks that are not reachable. Keep
8418 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008419 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008420 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008421
Chris Lattner4ed40f72005-07-07 20:40:38 +00008422 // Do a quick scan over the function. If we find any blocks that are
8423 // unreachable, remove any instructions inside of them. This prevents
8424 // the instcombine code from having to deal with some bad special cases.
8425 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8426 if (!Visited.count(BB)) {
8427 Instruction *Term = BB->getTerminator();
8428 while (Term != BB->begin()) { // Remove instrs bottom-up
8429 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008430
Chris Lattner4ed40f72005-07-07 20:40:38 +00008431 DEBUG(std::cerr << "IC: DCE: " << *I);
8432 ++NumDeadInst;
8433
8434 if (!I->use_empty())
8435 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8436 I->eraseFromParent();
8437 }
8438 }
8439 }
Chris Lattnerca081252001-12-14 16:52:21 +00008440
8441 while (!WorkList.empty()) {
8442 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8443 WorkList.pop_back();
8444
Chris Lattner1443bc52006-05-11 17:11:52 +00008445 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008446 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008447 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008448 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008449 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008450 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008451
Chris Lattnercd517ff2005-01-28 19:32:01 +00008452 DEBUG(std::cerr << "IC: DCE: " << *I);
8453
8454 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008455 removeFromWorkList(I);
8456 continue;
8457 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008458
Chris Lattner1443bc52006-05-11 17:11:52 +00008459 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008460 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008461 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8462 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008463 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8464
Chris Lattner1443bc52006-05-11 17:11:52 +00008465 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008466 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008467 ReplaceInstUsesWith(*I, C);
8468
Chris Lattner99f48c62002-09-02 04:59:56 +00008469 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008470 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008471 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008472 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008473 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008474
Chris Lattner39c98bb2004-12-08 23:43:58 +00008475 // See if we can trivially sink this instruction to a successor basic block.
8476 if (I->hasOneUse()) {
8477 BasicBlock *BB = I->getParent();
8478 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8479 if (UserParent != BB) {
8480 bool UserIsSuccessor = false;
8481 // See if the user is one of our successors.
8482 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8483 if (*SI == UserParent) {
8484 UserIsSuccessor = true;
8485 break;
8486 }
8487
8488 // If the user is one of our immediate successors, and if that successor
8489 // only has us as a predecessors (we'd have to split the critical edge
8490 // otherwise), we can keep going.
8491 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8492 next(pred_begin(UserParent)) == pred_end(UserParent))
8493 // Okay, the CFG is simple enough, try to sink this instruction.
8494 Changed |= TryToSinkInstruction(I, UserParent);
8495 }
8496 }
8497
Chris Lattnerca081252001-12-14 16:52:21 +00008498 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008499 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008500 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008501 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008502 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008503 DEBUG(std::cerr << "IC: Old = " << *I
8504 << " New = " << *Result);
8505
Chris Lattner396dbfe2004-06-09 05:08:07 +00008506 // Everything uses the new instruction now.
8507 I->replaceAllUsesWith(Result);
8508
8509 // Push the new instruction and any users onto the worklist.
8510 WorkList.push_back(Result);
8511 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008512
8513 // Move the name to the new instruction first...
8514 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008515 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008516
8517 // Insert the new instruction into the basic block...
8518 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008519 BasicBlock::iterator InsertPos = I;
8520
8521 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8522 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8523 ++InsertPos;
8524
8525 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008526
Chris Lattner63d75af2004-05-01 23:27:23 +00008527 // Make sure that we reprocess all operands now that we reduced their
8528 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008529 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8530 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8531 WorkList.push_back(OpI);
8532
Chris Lattner396dbfe2004-06-09 05:08:07 +00008533 // Instructions can end up on the worklist more than once. Make sure
8534 // we do not process an instruction that has been deleted.
8535 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008536
8537 // Erase the old instruction.
8538 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008539 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008540 DEBUG(std::cerr << "IC: MOD = " << *I);
8541
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008542 // If the instruction was modified, it's possible that it is now dead.
8543 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008544 if (isInstructionTriviallyDead(I)) {
8545 // Make sure we process all operands now that we are reducing their
8546 // use counts.
8547 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8548 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8549 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008550
Chris Lattner63d75af2004-05-01 23:27:23 +00008551 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008552 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008553 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008554 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008555 } else {
8556 WorkList.push_back(Result);
8557 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008558 }
Chris Lattner053c0932002-05-14 15:24:07 +00008559 }
Chris Lattner260ab202002-04-18 17:39:14 +00008560 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008561 }
8562 }
8563
Chris Lattner260ab202002-04-18 17:39:14 +00008564 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008565}
8566
Brian Gaeke38b79e82004-07-27 17:43:21 +00008567FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008568 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008569}
Brian Gaeke960707c2003-11-11 22:41:34 +00008570