blob: 98c35ddb0cdfe16b1b7975d33c39924512feb7d6 [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 Spencer7eb55b32006-11-02 01:53:59 +0000134 Instruction *visitURem(BinaryOperator &I);
135 Instruction *visitSRem(BinaryOperator &I);
136 Instruction *visitFRem(BinaryOperator &I);
137 Instruction *commonRemTransforms(BinaryOperator &I);
138 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000139 Instruction *commonDivTransforms(BinaryOperator &I);
140 Instruction *commonIDivTransforms(BinaryOperator &I);
141 Instruction *visitUDiv(BinaryOperator &I);
142 Instruction *visitSDiv(BinaryOperator &I);
143 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitAnd(BinaryOperator &I);
145 Instruction *visitOr (BinaryOperator &I);
146 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000147 Instruction *visitSetCondInst(SetCondInst &I);
148 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149
Chris Lattner0798af32005-01-13 20:14:25 +0000150 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000155 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000156 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000158 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000159 Instruction *visitCallInst(CallInst &CI);
160 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000161 Instruction *visitPHINode(PHINode &PN);
162 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000163 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000164 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000165 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000166 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000167 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000168 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000169 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000170 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000171 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000172
173 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175
Chris Lattner970c33a2003-06-19 17:00:31 +0000176 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000177 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000178 bool transformConstExprCastCall(CallSite CS);
179
Chris Lattner69193f92004-04-05 01:30:19 +0000180 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000181 // InsertNewInstBefore - insert an instruction New before instruction Old
182 // in the program. Add the new instruction to the worklist.
183 //
Chris Lattner623826c2004-09-28 21:48:02 +0000184 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000185 assert(New && New->getParent() == 0 &&
186 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 BasicBlock *BB = Old.getParent();
188 BB->getInstList().insert(&Old, New); // Insert inst
189 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000190 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000191 }
192
Chris Lattner7e794272004-09-24 15:21:34 +0000193 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194 /// This also adds the cast to the worklist. Finally, this returns the
195 /// cast.
196 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000198
Chris Lattnere79d2492006-04-06 19:19:17 +0000199 if (Constant *CV = dyn_cast<Constant>(V))
200 return ConstantExpr::getCast(CV, Ty);
201
Chris Lattner7e794272004-09-24 15:21:34 +0000202 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203 WorkList.push_back(C);
204 return C;
205 }
206
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000207 // ReplaceInstUsesWith - This method is to be used when an instruction is
208 // found to be dead, replacable with another preexisting expression. Here
209 // we add all uses of I to the worklist, replace all uses of I with the new
210 // value, then return I, so that the inst combiner will know that I was
211 // modified.
212 //
213 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000214 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000215 if (&I != V) {
216 I.replaceAllUsesWith(V);
217 return &I;
218 } else {
219 // If we are replacing the instruction with itself, this must be in a
220 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000221 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000222 return &I;
223 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000225
Chris Lattner2590e512006-02-07 06:56:34 +0000226 // UpdateValueUsesWith - This method is to be used when an value is
227 // found to be replacable with another preexisting expression or was
228 // updated. Here we add all uses of I to the worklist, replace all uses of
229 // I with the new value (unless the instruction was just updated), then
230 // return true, so that the inst combiner will know that I was modified.
231 //
232 bool UpdateValueUsesWith(Value *Old, Value *New) {
233 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
234 if (Old != New)
235 Old->replaceAllUsesWith(New);
236 if (Instruction *I = dyn_cast<Instruction>(Old))
237 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000238 if (Instruction *I = dyn_cast<Instruction>(New))
239 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000240 return true;
241 }
242
Chris Lattner51ea1272004-02-28 05:22:00 +0000243 // EraseInstFromFunction - When dealing with an instruction that has side
244 // effects or produces a void value, we can't rely on DCE to delete the
245 // instruction. Instead, visit methods should return the value returned by
246 // this function.
247 Instruction *EraseInstFromFunction(Instruction &I) {
248 assert(I.use_empty() && "Cannot erase instruction that is used!");
249 AddUsesToWorkList(I);
250 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000251 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000252 return 0; // Don't do anything with FI
253 }
254
Chris Lattner3ac7c262003-08-13 20:16:26 +0000255 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000256 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257 /// InsertBefore instruction. This is specialized a bit to avoid inserting
258 /// casts that are known to not do anything...
259 ///
260 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261 Instruction *InsertBefore);
262
Chris Lattner7fb29e12003-03-11 00:12:48 +0000263 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000264 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000266
Chris Lattner0157e7f2006-02-11 09:31:47 +0000267 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
268 uint64_t &KnownZero, uint64_t &KnownOne,
269 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270
Chris Lattner2deeaea2006-10-05 06:55:50 +0000271 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272 uint64_t &UndefElts, unsigned Depth = 0);
273
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000274 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275 // PHI node as operand #0, see if we can fold the instruction into the PHI
276 // (which is only possible if all operands to the PHI are constants).
277 Instruction *FoldOpIntoPhi(Instruction &I);
278
Chris Lattner7515cab2004-11-14 19:13:23 +0000279 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280 // operator and they all are only used by the PHI, PHI together their
281 // inputs, and do the operation once, to the result of the PHI.
282 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000283 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
284
285
Chris Lattnerba1cb382003-09-19 17:17:26 +0000286 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000288
289 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000291 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000293 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000294 Instruction *MatchBSwap(BinaryOperator &I);
295
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000296 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000297 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000298
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000299 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000300}
301
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000303// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000304static unsigned getComplexity(Value *V) {
305 if (isa<Instruction>(V)) {
306 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000307 return 3;
308 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000310 if (isa<Argument>(V)) return 3;
311 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000312}
Chris Lattner260ab202002-04-18 17:39:14 +0000313
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314// isOnlyUse - Return true if this instruction will be deleted if we stop using
315// it.
316static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000317 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318}
319
Chris Lattnere79e8542004-02-23 06:38:22 +0000320// getPromotedType - Return the specified type promoted as it would be to pass
321// though a va_arg area...
322static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000323 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000324 case Type::SByteTyID:
325 case Type::ShortTyID: return Type::IntTy;
326 case Type::UByteTyID:
327 case Type::UShortTyID: return Type::UIntTy;
328 case Type::FloatTyID: return Type::DoubleTy;
329 default: return Ty;
330 }
331}
332
Chris Lattner567b81f2005-09-13 00:40:14 +0000333/// isCast - If the specified operand is a CastInst or a constant expr cast,
334/// return the operand value, otherwise return null.
335static Value *isCast(Value *V) {
336 if (CastInst *I = dyn_cast<CastInst>(V))
337 return I->getOperand(0);
338 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339 if (CE->getOpcode() == Instruction::Cast)
340 return CE->getOperand(0);
341 return 0;
342}
343
Chris Lattner1d441ad2006-05-06 09:00:16 +0000344enum CastType {
345 Noop = 0,
346 Truncate = 1,
347 Signext = 2,
348 Zeroext = 3
349};
350
351/// getCastType - In the future, we will split the cast instruction into these
352/// various types. Until then, we have to do the analysis here.
353static CastType getCastType(const Type *Src, const Type *Dest) {
354 assert(Src->isIntegral() && Dest->isIntegral() &&
355 "Only works on integral types!");
356 unsigned SrcSize = Src->getPrimitiveSizeInBits();
357 unsigned DestSize = Dest->getPrimitiveSizeInBits();
358
359 if (SrcSize == DestSize) return Noop;
360 if (SrcSize > DestSize) return Truncate;
361 if (Src->isSigned()) return Signext;
362 return Zeroext;
363}
364
365
366// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
367// instruction.
368//
369static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370 const Type *DstTy, TargetData *TD) {
371
372 // It is legal to eliminate the instruction if casting A->B->A if the sizes
373 // are identical and the bits don't get reinterpreted (for example
374 // int->float->int would not be allowed).
375 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
376 return true;
377
378 // If we are casting between pointer and integer types, treat pointers as
379 // integers of the appropriate size for the code below.
380 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383
384 // Allow free casting and conversion of sizes as long as the sign doesn't
385 // change...
386 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387 CastType FirstCast = getCastType(SrcTy, MidTy);
388 CastType SecondCast = getCastType(MidTy, DstTy);
389
390 // Capture the effect of these two casts. If the result is a legal cast,
391 // the CastType is stored here, otherwise a special code is used.
392 static const unsigned CastResult[] = {
393 // First cast is noop
394 0, 1, 2, 3,
395 // First cast is a truncate
396 1, 1, 4, 4, // trunc->extend is not safe to eliminate
397 // First cast is a sign ext
398 2, 5, 2, 4, // signext->zeroext never ok
399 // First cast is a zero ext
400 3, 5, 3, 3,
401 };
402
403 unsigned Result = CastResult[FirstCast*4+SecondCast];
404 switch (Result) {
405 default: assert(0 && "Illegal table value!");
406 case 0:
407 case 1:
408 case 2:
409 case 3:
410 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411 // truncates, we could eliminate more casts.
412 return (unsigned)getCastType(SrcTy, DstTy) == Result;
413 case 4:
414 return false; // Not possible to eliminate this here.
415 case 5:
416 // Sign or zero extend followed by truncate is always ok if the result
417 // is a truncate or noop.
418 CastType ResultCast = getCastType(SrcTy, DstTy);
419 if (ResultCast == Noop || ResultCast == Truncate)
420 return true;
421 // Otherwise we are still growing the value, we are only safe if the
422 // result will match the sign/zeroextendness of the result.
423 return ResultCast == FirstCast;
424 }
425 }
426
427 // If this is a cast from 'float -> double -> integer', cast from
428 // 'float -> integer' directly, as the value isn't changed by the
429 // float->double conversion.
430 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431 DstTy->isIntegral() &&
432 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
433 return true;
434
435 // Packed type conversions don't modify bits.
436 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
437 return true;
438
439 return false;
440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
445static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
448 // If this is a noop cast, it isn't real codegen.
449 if (V->getType()->isLosslesslyConvertibleTo(Ty))
450 return false;
451
Chris Lattner99155be2006-05-25 23:24:33 +0000452 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000453 if (const CastInst *CI = dyn_cast<CastInst>(V))
454 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
455 TD))
456 return false;
457 return true;
458}
459
460/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461/// InsertBefore instruction. This is specialized a bit to avoid inserting
462/// casts that are known to not do anything...
463///
464Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465 Instruction *InsertBefore) {
466 if (V->getType() == DestTy) return V;
467 if (Constant *C = dyn_cast<Constant>(V))
468 return ConstantExpr::getCast(C, DestTy);
469
Reid Spencer00c482b2006-10-26 19:19:06 +0000470 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000471}
472
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000473// SimplifyCommutative - This performs a few simplifications for commutative
474// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000475//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000476// 1. Order operands such that they are listed from right (least complex) to
477// left (most complex). This puts constants before unary operators before
478// binary operators.
479//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000480// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000484 bool Changed = false;
485 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000487
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000488 if (!I.isAssociative()) return Changed;
489 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000493 Constant *Folded = ConstantExpr::get(I.getOpcode(),
494 cast<Constant>(I.getOperand(1)),
495 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496 I.setOperand(0, Op->getOperand(0));
497 I.setOperand(1, Folded);
498 return true;
499 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501 isOnlyUse(Op) && isOnlyUse(Op1)) {
502 Constant *C1 = cast<Constant>(Op->getOperand(1));
503 Constant *C2 = cast<Constant>(Op1->getOperand(1));
504
505 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000507 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508 Op1->getOperand(0),
509 Op1->getName(), &I);
510 WorkList.push_back(New);
511 I.setOperand(0, New);
512 I.setOperand(1, Folded);
513 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000515 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000516 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000517}
Chris Lattnerca081252001-12-14 16:52:21 +0000518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000521//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522static inline Value *dyn_castNegVal(Value *V) {
523 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000524 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525
Chris Lattner9ad0d552004-12-14 20:08:06 +0000526 // Constants can be considered to be negated values if they can be folded.
527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000530}
531
Chris Lattnerbb74e222003-03-10 23:06:50 +0000532static inline Value *dyn_castNotVal(Value *V) {
533 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000534 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535
536 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000537 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000538 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000539 return 0;
540}
541
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542// dyn_castFoldableMul - If this value is a multiply that can be folded into
543// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544// non-constant operand of the multiply, and set CST to point to the multiplier.
545// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000548 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000551 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000553 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000554 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000555 // The multiplier is really 1 << CST.
556 Constant *One = ConstantInt::get(V->getType(), 1);
557 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558 return I->getOperand(0);
559 }
560 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000561 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000562}
Chris Lattner31ae8632002-08-14 17:51:49 +0000563
Chris Lattner0798af32005-01-13 20:14:25 +0000564/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565/// expression, return it.
566static User *dyn_castGetElementPtr(Value *V) {
567 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569 if (CE->getOpcode() == Instruction::GetElementPtr)
570 return cast<User>(V);
571 return false;
572}
573
Chris Lattner623826c2004-09-28 21:48:02 +0000574// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000575static ConstantInt *AddOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getAdd(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000578}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000579static ConstantInt *SubOne(ConstantInt *C) {
580 return cast<ConstantInt>(ConstantExpr::getSub(C,
581 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000582}
583
Chris Lattner0157e7f2006-02-11 09:31:47 +0000584/// GetConstantInType - Return a ConstantInt with the specified type and value.
585///
Chris Lattneree0f2802006-02-12 02:07:56 +0000586static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000587 if (Ty->isUnsigned())
588 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000589 else if (Ty->getTypeID() == Type::BoolTyID)
590 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591 int64_t SVal = Val;
592 SVal <<= 64-Ty->getPrimitiveSizeInBits();
593 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000594 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000595}
596
597
Chris Lattner4534dd592006-02-09 07:38:58 +0000598/// ComputeMaskedBits - Determine which of the bits specified in Mask are
599/// known to be either zero or one and return them in the KnownZero/KnownOne
600/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
601/// processing.
602static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000604 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
605 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000606 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000607 // optimized based on the contradictory assumption that it is non-zero.
608 // Because instcombine aggressively folds operations with undef args anyway,
609 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000610 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000612 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000613 KnownZero = ~KnownOne & Mask;
614 return;
615 }
616
617 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000618 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000619 return; // Limit search depth.
620
621 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000622 Instruction *I = dyn_cast<Instruction>(V);
623 if (!I) return;
624
Chris Lattnerfb296922006-05-04 17:33:35 +0000625 Mask &= V->getType()->getIntegralTypeMask();
626
Chris Lattner0157e7f2006-02-11 09:31:47 +0000627 switch (I->getOpcode()) {
628 case Instruction::And:
629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631 Mask &= ~KnownZero;
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
641 case Instruction::Or:
642 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643 Mask &= ~KnownOne;
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647
648 // Output known-0 bits are only known if clear in both the LHS & RHS.
649 KnownZero &= KnownZero2;
650 // Output known-1 are known to be set if set in either the LHS | RHS.
651 KnownOne |= KnownOne2;
652 return;
653 case Instruction::Xor: {
654 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
658
659 // Output known-0 bits are known if clear or set in both the LHS & RHS.
660 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661 // Output known-1 are known to be set if set in only one of the LHS, RHS.
662 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663 KnownZero = KnownZeroOut;
664 return;
665 }
666 case Instruction::Select:
667 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
670 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
671
672 // Only known if known in both the LHS and RHS.
673 KnownOne &= KnownOne2;
674 KnownZero &= KnownZero2;
675 return;
676 case Instruction::Cast: {
677 const Type *SrcTy = I->getOperand(0)->getType();
678 if (!SrcTy->isIntegral()) return;
679
680 // If this is an integer truncate or noop, just look in the input.
681 if (SrcTy->getPrimitiveSizeInBits() >=
682 I->getType()->getPrimitiveSizeInBits()) {
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000684 return;
685 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000686
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 // Sign or Zero extension. Compute the bits in the result that are not
688 // present in the input.
689 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000691
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692 // Handle zero extension.
693 if (!SrcTy->isSigned()) {
694 Mask &= SrcTy->getIntegralTypeMask();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // The top bits are known to be zero.
698 KnownZero |= NewBits;
699 } else {
700 // Sign extension.
701 Mask &= SrcTy->getIntegralTypeMask();
702 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000704
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
707 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000709 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000710 KnownOne &= ~NewBits;
711 } else if (KnownOne & InSignBit) { // Input sign bit known set
712 KnownOne |= NewBits;
713 KnownZero &= ~NewBits;
714 } else { // Input sign bit unknown
715 KnownZero &= ~NewBits;
716 KnownOne &= ~NewBits;
717 }
718 }
719 return;
720 }
721 case Instruction::Shl:
722 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000723 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724 uint64_t ShiftAmt = SA->getZExtValue();
725 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000728 KnownZero <<= ShiftAmt;
729 KnownOne <<= ShiftAmt;
730 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000731 return;
732 }
733 break;
734 case Instruction::Shr:
735 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000736 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000738 uint64_t ShiftAmt = SA->getZExtValue();
739 uint64_t HighBits = (1ULL << ShiftAmt)-1;
740 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741
742 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000743 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000749 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000750 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000753 KnownZero >>= ShiftAmt;
754 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755
756 // Handle the sign bits.
757 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000758 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000759
760 if (KnownZero & SignBit) { // New bits are known zero.
761 KnownZero |= HighBits;
762 } else if (KnownOne & SignBit) { // New bits are known one.
763 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000764 }
765 }
766 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000767 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000768 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000769 }
Chris Lattner92a68652006-02-07 08:05:22 +0000770}
771
772/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
773/// this predicate to simplify operations downstream. Mask is known to be zero
774/// for bits that V cannot have.
775static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000776 uint64_t KnownZero, KnownOne;
777 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
778 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
779 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000780}
781
Chris Lattner0157e7f2006-02-11 09:31:47 +0000782/// ShrinkDemandedConstant - Check to see if the specified operand of the
783/// specified instruction is a constant integer. If so, check to see if there
784/// are any bits set in the constant that are not demanded. If so, shrink the
785/// constant and return true.
786static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
787 uint64_t Demanded) {
788 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
789 if (!OpC) return false;
790
791 // If there are no bits set that aren't demanded, nothing to do.
792 if ((~Demanded & OpC->getZExtValue()) == 0)
793 return false;
794
795 // This is producing any bits that are not needed, shrink the RHS.
796 uint64_t Val = Demanded & OpC->getZExtValue();
797 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
798 return true;
799}
800
Chris Lattneree0f2802006-02-12 02:07:56 +0000801// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
802// set of known zero and one bits, compute the maximum and minimum values that
803// could have the specified known zero and known one bits, returning them in
804// min/max.
805static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
806 uint64_t KnownZero,
807 uint64_t KnownOne,
808 int64_t &Min, int64_t &Max) {
809 uint64_t TypeBits = Ty->getIntegralTypeMask();
810 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
811
812 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
813
814 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
815 // bit if it is unknown.
816 Min = KnownOne;
817 Max = KnownOne|UnknownBits;
818
819 if (SignBit & UnknownBits) { // Sign bit is unknown
820 Min |= SignBit;
821 Max &= ~SignBit;
822 }
823
824 // Sign extend the min/max values.
825 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
826 Min = (Min << ShAmt) >> ShAmt;
827 Max = (Max << ShAmt) >> ShAmt;
828}
829
830// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
831// a set of known zero and one bits, compute the maximum and minimum values that
832// could have the specified known zero and known one bits, returning them in
833// min/max.
834static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
835 uint64_t KnownZero,
836 uint64_t KnownOne,
837 uint64_t &Min,
838 uint64_t &Max) {
839 uint64_t TypeBits = Ty->getIntegralTypeMask();
840 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
841
842 // The minimum value is when the unknown bits are all zeros.
843 Min = KnownOne;
844 // The maximum value is when the unknown bits are all ones.
845 Max = KnownOne|UnknownBits;
846}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000847
848
849/// SimplifyDemandedBits - Look at V. At this point, we know that only the
850/// DemandedMask bits of the result of V are ever used downstream. If we can
851/// use this information to simplify V, do so and return true. Otherwise,
852/// analyze the expression and return a mask of KnownOne and KnownZero bits for
853/// the expression (used to simplify the caller). The KnownZero/One bits may
854/// only be accurate for those bits in the DemandedMask.
855bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
856 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000857 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000858 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
859 // We know all of the bits for a constant!
860 KnownOne = CI->getZExtValue() & DemandedMask;
861 KnownZero = ~KnownOne & DemandedMask;
862 return false;
863 }
864
865 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000866 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 if (Depth != 0) { // Not at the root.
868 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
869 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000870 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000871 }
Chris Lattner2590e512006-02-07 06:56:34 +0000872 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000873 // just set the DemandedMask to all bits.
874 DemandedMask = V->getType()->getIntegralTypeMask();
875 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000876 if (V != UndefValue::get(V->getType()))
877 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
878 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000879 } else if (Depth == 6) { // Limit search depth.
880 return false;
881 }
882
883 Instruction *I = dyn_cast<Instruction>(V);
884 if (!I) return false; // Only analyze instructions.
885
Chris Lattnerfb296922006-05-04 17:33:35 +0000886 DemandedMask &= V->getType()->getIntegralTypeMask();
887
Chris Lattner0157e7f2006-02-11 09:31:47 +0000888 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000889 switch (I->getOpcode()) {
890 default: break;
891 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000892 // If either the LHS or the RHS are Zero, the result is zero.
893 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894 KnownZero, KnownOne, Depth+1))
895 return true;
896 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
897
898 // If something is known zero on the RHS, the bits aren't demanded on the
899 // LHS.
900 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
901 KnownZero2, KnownOne2, Depth+1))
902 return true;
903 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
904
905 // If all of the demanded bits are known one on one side, return the other.
906 // These bits cannot contribute to the result of the 'and'.
907 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
908 return UpdateValueUsesWith(I, I->getOperand(0));
909 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
910 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000911
912 // If all of the demanded bits in the inputs are known zeros, return zero.
913 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
914 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
915
Chris Lattner0157e7f2006-02-11 09:31:47 +0000916 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000917 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918 return UpdateValueUsesWith(I, I);
919
920 // Output known-1 bits are only known if set in both the LHS & RHS.
921 KnownOne &= KnownOne2;
922 // Output known-0 are known to be clear if zero in either the LHS | RHS.
923 KnownZero |= KnownZero2;
924 break;
925 case Instruction::Or:
926 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
927 KnownZero, KnownOne, Depth+1))
928 return true;
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
931 KnownZero2, KnownOne2, Depth+1))
932 return true;
933 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934
935 // If all of the demanded bits are known zero on one side, return the other.
936 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000937 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000938 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000939 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000941
942 // If all of the potentially set bits on one side are known to be set on
943 // the other side, just use the 'other' side.
944 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
945 (DemandedMask & (~KnownZero)))
946 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000947 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
948 (DemandedMask & (~KnownZero2)))
949 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000950
951 // If the RHS is a constant, see if we can simplify it.
952 if (ShrinkDemandedConstant(I, 1, DemandedMask))
953 return UpdateValueUsesWith(I, I);
954
955 // Output known-0 bits are only known if clear in both the LHS & RHS.
956 KnownZero &= KnownZero2;
957 // Output known-1 are known to be set if set in either the LHS | RHS.
958 KnownOne |= KnownOne2;
959 break;
960 case Instruction::Xor: {
961 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962 KnownZero, KnownOne, Depth+1))
963 return true;
964 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
965 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
966 KnownZero2, KnownOne2, Depth+1))
967 return true;
968 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
969
970 // If all of the demanded bits are known zero on one side, return the other.
971 // These bits cannot contribute to the result of the 'xor'.
972 if ((DemandedMask & KnownZero) == DemandedMask)
973 return UpdateValueUsesWith(I, I->getOperand(0));
974 if ((DemandedMask & KnownZero2) == DemandedMask)
975 return UpdateValueUsesWith(I, I->getOperand(1));
976
977 // Output known-0 bits are known if clear or set in both the LHS & RHS.
978 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
979 // Output known-1 are known to be set if set in only one of the LHS, RHS.
980 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
981
982 // If all of the unknown bits are known to be zero on one side or the other
983 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000984 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000985 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
986 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
987 Instruction *Or =
988 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
989 I->getName());
990 InsertNewInstBefore(Or, *I);
991 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000992 }
993 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000994
Chris Lattner5b2edb12006-02-12 08:02:11 +0000995 // If all of the demanded bits on one side are known, and all of the set
996 // bits on that side are also known to be set on the other side, turn this
997 // into an AND, as we know the bits will be cleared.
998 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
999 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1000 if ((KnownOne & KnownOne2) == KnownOne) {
1001 Constant *AndC = GetConstantInType(I->getType(),
1002 ~KnownOne & DemandedMask);
1003 Instruction *And =
1004 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1005 InsertNewInstBefore(And, *I);
1006 return UpdateValueUsesWith(I, And);
1007 }
1008 }
1009
Chris Lattner0157e7f2006-02-11 09:31:47 +00001010 // If the RHS is a constant, see if we can simplify it.
1011 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1012 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1013 return UpdateValueUsesWith(I, I);
1014
1015 KnownZero = KnownZeroOut;
1016 KnownOne = KnownOneOut;
1017 break;
1018 }
1019 case Instruction::Select:
1020 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1021 KnownZero, KnownOne, Depth+1))
1022 return true;
1023 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1024 KnownZero2, KnownOne2, Depth+1))
1025 return true;
1026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1027 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1028
1029 // If the operands are constants, see if we can simplify them.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 return UpdateValueUsesWith(I, I);
1032 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1033 return UpdateValueUsesWith(I, I);
1034
1035 // Only known if known in both the LHS and RHS.
1036 KnownOne &= KnownOne2;
1037 KnownZero &= KnownZero2;
1038 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001039 case Instruction::Cast: {
1040 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001041 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001042
Chris Lattner0157e7f2006-02-11 09:31:47 +00001043 // If this is an integer truncate or noop, just look in the input.
1044 if (SrcTy->getPrimitiveSizeInBits() >=
1045 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001046 // Cast to bool is a comparison against 0, which demands all bits. We
1047 // can't propagate anything useful up.
1048 if (I->getType() == Type::BoolTy)
1049 break;
1050
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1052 KnownZero, KnownOne, Depth+1))
1053 return true;
1054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1055 break;
1056 }
1057
1058 // Sign or Zero extension. Compute the bits in the result that are not
1059 // present in the input.
1060 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1061 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1062
1063 // Handle zero extension.
1064 if (!SrcTy->isSigned()) {
1065 DemandedMask &= SrcTy->getIntegralTypeMask();
1066 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1067 KnownZero, KnownOne, Depth+1))
1068 return true;
1069 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1070 // The top bits are known to be zero.
1071 KnownZero |= NewBits;
1072 } else {
1073 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001074 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1075 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1076
1077 // If any of the sign extended bits are demanded, we know that the sign
1078 // bit is demanded.
1079 if (NewBits & DemandedMask)
1080 InputDemandedBits |= InSignBit;
1081
1082 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001083 KnownZero, KnownOne, Depth+1))
1084 return true;
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086
1087 // If the sign bit of the input is known set or clear, then we know the
1088 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001089
Chris Lattner0157e7f2006-02-11 09:31:47 +00001090 // If the input sign bit is known zero, or if the NewBits are not demanded
1091 // convert this into a zero extension.
1092 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001093 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001094 Value *NewVal =
1095 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001096 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001097 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001098 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001099 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100 } else if (KnownOne & InSignBit) { // Input sign bit known set
1101 KnownOne |= NewBits;
1102 KnownZero &= ~NewBits;
1103 } else { // Input sign bit unknown
1104 KnownZero &= ~NewBits;
1105 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001106 }
Chris Lattner2590e512006-02-07 06:56:34 +00001107 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001108 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001109 }
Chris Lattner2590e512006-02-07 06:56:34 +00001110 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001111 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1112 uint64_t ShiftAmt = SA->getZExtValue();
1113 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001114 KnownZero, KnownOne, Depth+1))
1115 return true;
1116 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001117 KnownZero <<= ShiftAmt;
1118 KnownOne <<= ShiftAmt;
1119 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001120 }
Chris Lattner2590e512006-02-07 06:56:34 +00001121 break;
1122 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001123 // If this is an arithmetic shift right and only the low-bit is set, we can
1124 // always convert this into a logical shr, even if the shift amount is
1125 // variable. The low bit of the shift cannot be an input sign bit unless
1126 // the shift amount is >= the size of the datatype, which is undefined.
1127 if (DemandedMask == 1 && I->getType()->isSigned()) {
1128 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001129 Value *NewVal = InsertCastBefore(I->getOperand(0),
1130 I->getType()->getUnsignedVersion(), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001131 // Perform the unsigned shift right.
1132 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1133 I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001134 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001135 // Then cast that to the destination type.
1136 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001137 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001138 return UpdateValueUsesWith(I, NewVal);
1139 }
1140
Reid Spencere0fc4df2006-10-20 07:07:24 +00001141 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1142 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001143
1144 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001145 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1146 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001147 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001148 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001149 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001150 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001151 KnownZero, KnownOne, Depth+1))
1152 return true;
1153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001154 KnownZero &= TypeMask;
1155 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001156 KnownZero >>= ShiftAmt;
1157 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001158 KnownZero |= HighBits; // high bits known zero.
1159 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001160 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001161 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001162 KnownZero, KnownOne, Depth+1))
1163 return true;
1164 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001165 KnownZero &= TypeMask;
1166 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001167 KnownZero >>= ShiftAmt;
1168 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001169
1170 // Handle the sign bits.
1171 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001172 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001173
1174 // If the input sign bit is known to be zero, or if none of the top bits
1175 // are demanded, turn this into an unsigned shift right.
1176 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1177 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001178 Value *NewVal = InsertCastBefore(I->getOperand(0),
1179 I->getType()->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001180 // Perform the unsigned shift right.
1181 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001182 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001183 // Then cast that to the destination type.
1184 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001185 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001186 return UpdateValueUsesWith(I, NewVal);
1187 } else if (KnownOne & SignBit) { // New bits are known one.
1188 KnownOne |= HighBits;
1189 }
Chris Lattner2590e512006-02-07 06:56:34 +00001190 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001191 }
Chris Lattner2590e512006-02-07 06:56:34 +00001192 break;
1193 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001194
1195 // If the client is only demanding bits that we know, return the known
1196 // constant.
1197 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1198 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001199 return false;
1200}
1201
Chris Lattner2deeaea2006-10-05 06:55:50 +00001202
1203/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1204/// 64 or fewer elements. DemandedElts contains the set of elements that are
1205/// actually used by the caller. This method analyzes which elements of the
1206/// operand are undef and returns that information in UndefElts.
1207///
1208/// If the information about demanded elements can be used to simplify the
1209/// operation, the operation is simplified, then the resultant value is
1210/// returned. This returns null if no change was made.
1211Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1212 uint64_t &UndefElts,
1213 unsigned Depth) {
1214 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1215 assert(VWidth <= 64 && "Vector too wide to analyze!");
1216 uint64_t EltMask = ~0ULL >> (64-VWidth);
1217 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1218 "Invalid DemandedElts!");
1219
1220 if (isa<UndefValue>(V)) {
1221 // If the entire vector is undefined, just return this info.
1222 UndefElts = EltMask;
1223 return 0;
1224 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1225 UndefElts = EltMask;
1226 return UndefValue::get(V->getType());
1227 }
1228
1229 UndefElts = 0;
1230 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1231 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1232 Constant *Undef = UndefValue::get(EltTy);
1233
1234 std::vector<Constant*> Elts;
1235 for (unsigned i = 0; i != VWidth; ++i)
1236 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1237 Elts.push_back(Undef);
1238 UndefElts |= (1ULL << i);
1239 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1240 Elts.push_back(Undef);
1241 UndefElts |= (1ULL << i);
1242 } else { // Otherwise, defined.
1243 Elts.push_back(CP->getOperand(i));
1244 }
1245
1246 // If we changed the constant, return it.
1247 Constant *NewCP = ConstantPacked::get(Elts);
1248 return NewCP != CP ? NewCP : 0;
1249 } else if (isa<ConstantAggregateZero>(V)) {
1250 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1251 // set to undef.
1252 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1253 Constant *Zero = Constant::getNullValue(EltTy);
1254 Constant *Undef = UndefValue::get(EltTy);
1255 std::vector<Constant*> Elts;
1256 for (unsigned i = 0; i != VWidth; ++i)
1257 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1258 UndefElts = DemandedElts ^ EltMask;
1259 return ConstantPacked::get(Elts);
1260 }
1261
1262 if (!V->hasOneUse()) { // Other users may use these bits.
1263 if (Depth != 0) { // Not at the root.
1264 // TODO: Just compute the UndefElts information recursively.
1265 return false;
1266 }
1267 return false;
1268 } else if (Depth == 10) { // Limit search depth.
1269 return false;
1270 }
1271
1272 Instruction *I = dyn_cast<Instruction>(V);
1273 if (!I) return false; // Only analyze instructions.
1274
1275 bool MadeChange = false;
1276 uint64_t UndefElts2;
1277 Value *TmpV;
1278 switch (I->getOpcode()) {
1279 default: break;
1280
1281 case Instruction::InsertElement: {
1282 // If this is a variable index, we don't know which element it overwrites.
1283 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001284 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001285 if (Idx == 0) {
1286 // Note that we can't propagate undef elt info, because we don't know
1287 // which elt is getting updated.
1288 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1289 UndefElts2, Depth+1);
1290 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1291 break;
1292 }
1293
1294 // If this is inserting an element that isn't demanded, remove this
1295 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001296 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001297 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1298 return AddSoonDeadInstToWorklist(*I, 0);
1299
1300 // Otherwise, the element inserted overwrites whatever was there, so the
1301 // input demanded set is simpler than the output set.
1302 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1303 DemandedElts & ~(1ULL << IdxNo),
1304 UndefElts, Depth+1);
1305 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1306
1307 // The inserted element is defined.
1308 UndefElts |= 1ULL << IdxNo;
1309 break;
1310 }
1311
1312 case Instruction::And:
1313 case Instruction::Or:
1314 case Instruction::Xor:
1315 case Instruction::Add:
1316 case Instruction::Sub:
1317 case Instruction::Mul:
1318 // div/rem demand all inputs, because they don't want divide by zero.
1319 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1320 UndefElts, Depth+1);
1321 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1322 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1323 UndefElts2, Depth+1);
1324 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1325
1326 // Output elements are undefined if both are undefined. Consider things
1327 // like undef&0. The result is known zero, not undef.
1328 UndefElts &= UndefElts2;
1329 break;
1330
1331 case Instruction::Call: {
1332 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1333 if (!II) break;
1334 switch (II->getIntrinsicID()) {
1335 default: break;
1336
1337 // Binary vector operations that work column-wise. A dest element is a
1338 // function of the corresponding input elements from the two inputs.
1339 case Intrinsic::x86_sse_sub_ss:
1340 case Intrinsic::x86_sse_mul_ss:
1341 case Intrinsic::x86_sse_min_ss:
1342 case Intrinsic::x86_sse_max_ss:
1343 case Intrinsic::x86_sse2_sub_sd:
1344 case Intrinsic::x86_sse2_mul_sd:
1345 case Intrinsic::x86_sse2_min_sd:
1346 case Intrinsic::x86_sse2_max_sd:
1347 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1348 UndefElts, Depth+1);
1349 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1350 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1351 UndefElts2, Depth+1);
1352 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1353
1354 // If only the low elt is demanded and this is a scalarizable intrinsic,
1355 // scalarize it now.
1356 if (DemandedElts == 1) {
1357 switch (II->getIntrinsicID()) {
1358 default: break;
1359 case Intrinsic::x86_sse_sub_ss:
1360 case Intrinsic::x86_sse_mul_ss:
1361 case Intrinsic::x86_sse2_sub_sd:
1362 case Intrinsic::x86_sse2_mul_sd:
1363 // TODO: Lower MIN/MAX/ABS/etc
1364 Value *LHS = II->getOperand(1);
1365 Value *RHS = II->getOperand(2);
1366 // Extract the element as scalars.
1367 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1368 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1369
1370 switch (II->getIntrinsicID()) {
1371 default: assert(0 && "Case stmts out of sync!");
1372 case Intrinsic::x86_sse_sub_ss:
1373 case Intrinsic::x86_sse2_sub_sd:
1374 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1375 II->getName()), *II);
1376 break;
1377 case Intrinsic::x86_sse_mul_ss:
1378 case Intrinsic::x86_sse2_mul_sd:
1379 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1380 II->getName()), *II);
1381 break;
1382 }
1383
1384 Instruction *New =
1385 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1386 II->getName());
1387 InsertNewInstBefore(New, *II);
1388 AddSoonDeadInstToWorklist(*II, 0);
1389 return New;
1390 }
1391 }
1392
1393 // Output elements are undefined if both are undefined. Consider things
1394 // like undef&0. The result is known zero, not undef.
1395 UndefElts &= UndefElts2;
1396 break;
1397 }
1398 break;
1399 }
1400 }
1401 return MadeChange ? I : 0;
1402}
1403
Chris Lattner623826c2004-09-28 21:48:02 +00001404// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1405// true when both operands are equal...
1406//
1407static bool isTrueWhenEqual(Instruction &I) {
1408 return I.getOpcode() == Instruction::SetEQ ||
1409 I.getOpcode() == Instruction::SetGE ||
1410 I.getOpcode() == Instruction::SetLE;
1411}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001412
1413/// AssociativeOpt - Perform an optimization on an associative operator. This
1414/// function is designed to check a chain of associative operators for a
1415/// potential to apply a certain optimization. Since the optimization may be
1416/// applicable if the expression was reassociated, this checks the chain, then
1417/// reassociates the expression as necessary to expose the optimization
1418/// opportunity. This makes use of a special Functor, which must define
1419/// 'shouldApply' and 'apply' methods.
1420///
1421template<typename Functor>
1422Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1423 unsigned Opcode = Root.getOpcode();
1424 Value *LHS = Root.getOperand(0);
1425
1426 // Quick check, see if the immediate LHS matches...
1427 if (F.shouldApply(LHS))
1428 return F.apply(Root);
1429
1430 // Otherwise, if the LHS is not of the same opcode as the root, return.
1431 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001432 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001433 // Should we apply this transform to the RHS?
1434 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1435
1436 // If not to the RHS, check to see if we should apply to the LHS...
1437 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1438 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1439 ShouldApply = true;
1440 }
1441
1442 // If the functor wants to apply the optimization to the RHS of LHSI,
1443 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1444 if (ShouldApply) {
1445 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001446
Chris Lattnerb8b97502003-08-13 19:01:45 +00001447 // Now all of the instructions are in the current basic block, go ahead
1448 // and perform the reassociation.
1449 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1450
1451 // First move the selected RHS to the LHS of the root...
1452 Root.setOperand(0, LHSI->getOperand(1));
1453
1454 // Make what used to be the LHS of the root be the user of the root...
1455 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001456 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001457 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1458 return 0;
1459 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001460 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001461 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001462 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1463 BasicBlock::iterator ARI = &Root; ++ARI;
1464 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1465 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001466
1467 // Now propagate the ExtraOperand down the chain of instructions until we
1468 // get to LHSI.
1469 while (TmpLHSI != LHSI) {
1470 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001471 // Move the instruction to immediately before the chain we are
1472 // constructing to avoid breaking dominance properties.
1473 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1474 BB->getInstList().insert(ARI, NextLHSI);
1475 ARI = NextLHSI;
1476
Chris Lattnerb8b97502003-08-13 19:01:45 +00001477 Value *NextOp = NextLHSI->getOperand(1);
1478 NextLHSI->setOperand(1, ExtraOperand);
1479 TmpLHSI = NextLHSI;
1480 ExtraOperand = NextOp;
1481 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001482
Chris Lattnerb8b97502003-08-13 19:01:45 +00001483 // Now that the instructions are reassociated, have the functor perform
1484 // the transformation...
1485 return F.apply(Root);
1486 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001487
Chris Lattnerb8b97502003-08-13 19:01:45 +00001488 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1489 }
1490 return 0;
1491}
1492
1493
1494// AddRHS - Implements: X + X --> X << 1
1495struct AddRHS {
1496 Value *RHS;
1497 AddRHS(Value *rhs) : RHS(rhs) {}
1498 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1499 Instruction *apply(BinaryOperator &Add) const {
1500 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1501 ConstantInt::get(Type::UByteTy, 1));
1502 }
1503};
1504
1505// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1506// iff C1&C2 == 0
1507struct AddMaskingAnd {
1508 Constant *C2;
1509 AddMaskingAnd(Constant *c) : C2(c) {}
1510 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001511 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001512 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001513 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001514 }
1515 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001516 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 }
1518};
1519
Chris Lattner86102b82005-01-01 16:22:27 +00001520static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001521 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001522 if (isa<CastInst>(I)) {
1523 if (Constant *SOC = dyn_cast<Constant>(SO))
1524 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001525
Chris Lattner86102b82005-01-01 16:22:27 +00001526 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1527 SO->getName() + ".cast"), I);
1528 }
1529
Chris Lattner183b3362004-04-09 19:05:30 +00001530 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001531 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1532 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001533
Chris Lattner183b3362004-04-09 19:05:30 +00001534 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1535 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001536 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1537 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001538 }
1539
1540 Value *Op0 = SO, *Op1 = ConstOperand;
1541 if (!ConstIsRHS)
1542 std::swap(Op0, Op1);
1543 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1545 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1546 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1547 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001548 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001549 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001550 abort();
1551 }
Chris Lattner86102b82005-01-01 16:22:27 +00001552 return IC->InsertNewInstBefore(New, I);
1553}
1554
1555// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1556// constant as the other operand, try to fold the binary operator into the
1557// select arguments. This also works for Cast instructions, which obviously do
1558// not have a second operand.
1559static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1560 InstCombiner *IC) {
1561 // Don't modify shared select instructions
1562 if (!SI->hasOneUse()) return 0;
1563 Value *TV = SI->getOperand(1);
1564 Value *FV = SI->getOperand(2);
1565
1566 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001567 // Bool selects with constant operands can be folded to logical ops.
1568 if (SI->getType() == Type::BoolTy) return 0;
1569
Chris Lattner86102b82005-01-01 16:22:27 +00001570 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1571 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1572
1573 return new SelectInst(SI->getCondition(), SelectTrueVal,
1574 SelectFalseVal);
1575 }
1576 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001577}
1578
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001579
1580/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1581/// node as operand #0, see if we can fold the instruction into the PHI (which
1582/// is only possible if all operands to the PHI are constants).
1583Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1584 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001585 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001586 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001587
Chris Lattner04689872006-09-09 22:02:56 +00001588 // Check to see if all of the operands of the PHI are constants. If there is
1589 // one non-constant value, remember the BB it is. If there is more than one
1590 // bail out.
1591 BasicBlock *NonConstBB = 0;
1592 for (unsigned i = 0; i != NumPHIValues; ++i)
1593 if (!isa<Constant>(PN->getIncomingValue(i))) {
1594 if (NonConstBB) return 0; // More than one non-const value.
1595 NonConstBB = PN->getIncomingBlock(i);
1596
1597 // If the incoming non-constant value is in I's block, we have an infinite
1598 // loop.
1599 if (NonConstBB == I.getParent())
1600 return 0;
1601 }
1602
1603 // If there is exactly one non-constant value, we can insert a copy of the
1604 // operation in that block. However, if this is a critical edge, we would be
1605 // inserting the computation one some other paths (e.g. inside a loop). Only
1606 // do this if the pred block is unconditionally branching into the phi block.
1607 if (NonConstBB) {
1608 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1609 if (!BI || !BI->isUnconditional()) return 0;
1610 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001611
1612 // Okay, we can do the transformation: create the new PHI node.
1613 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1614 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001615 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001616 InsertNewInstBefore(NewPN, *PN);
1617
1618 // Next, add all of the operands to the PHI.
1619 if (I.getNumOperands() == 2) {
1620 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001621 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001622 Value *InV;
1623 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1624 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1625 } else {
1626 assert(PN->getIncomingBlock(i) == NonConstBB);
1627 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1628 InV = BinaryOperator::create(BO->getOpcode(),
1629 PN->getIncomingValue(i), C, "phitmp",
1630 NonConstBB->getTerminator());
1631 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1632 InV = new ShiftInst(SI->getOpcode(),
1633 PN->getIncomingValue(i), C, "phitmp",
1634 NonConstBB->getTerminator());
1635 else
1636 assert(0 && "Unknown binop!");
1637
1638 WorkList.push_back(cast<Instruction>(InV));
1639 }
1640 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001641 }
1642 } else {
1643 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1644 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001645 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001646 Value *InV;
1647 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1648 InV = ConstantExpr::getCast(InC, RetTy);
1649 } else {
1650 assert(PN->getIncomingBlock(i) == NonConstBB);
1651 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1652 NonConstBB->getTerminator());
1653 WorkList.push_back(cast<Instruction>(InV));
1654 }
1655 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001656 }
1657 }
1658 return ReplaceInstUsesWith(I, NewPN);
1659}
1660
Chris Lattner113f4f42002-06-25 16:13:24 +00001661Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001662 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001663 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001664
Chris Lattnercf4a9962004-04-10 22:01:55 +00001665 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001666 // X + undef -> undef
1667 if (isa<UndefValue>(RHS))
1668 return ReplaceInstUsesWith(I, RHS);
1669
Chris Lattnercf4a9962004-04-10 22:01:55 +00001670 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001671 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1672 if (RHSC->isNullValue())
1673 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001674 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1675 if (CFP->isExactlyValue(-0.0))
1676 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001677 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001678
Chris Lattnercf4a9962004-04-10 22:01:55 +00001679 // X + (signbit) --> X ^ signbit
1680 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001681 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001682 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001683 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001684 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001685
1686 if (isa<PHINode>(LHS))
1687 if (Instruction *NV = FoldOpIntoPhi(I))
1688 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001689
Chris Lattner330628a2006-01-06 17:59:59 +00001690 ConstantInt *XorRHS = 0;
1691 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001692 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1693 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1694 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1695 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1696
1697 uint64_t C0080Val = 1ULL << 31;
1698 int64_t CFF80Val = -C0080Val;
1699 unsigned Size = 32;
1700 do {
1701 if (TySizeBits > Size) {
1702 bool Found = false;
1703 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1704 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1705 if (RHSSExt == CFF80Val) {
1706 if (XorRHS->getZExtValue() == C0080Val)
1707 Found = true;
1708 } else if (RHSZExt == C0080Val) {
1709 if (XorRHS->getSExtValue() == CFF80Val)
1710 Found = true;
1711 }
1712 if (Found) {
1713 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001714 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001715 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001716 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001717 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001718 Size = 0; // Not a sign ext, but can't be any others either.
1719 goto FoundSExt;
1720 }
1721 }
1722 Size >>= 1;
1723 C0080Val >>= Size;
1724 CFF80Val >>= Size;
1725 } while (Size >= 8);
1726
1727FoundSExt:
1728 const Type *MiddleType = 0;
1729 switch (Size) {
1730 default: break;
1731 case 32: MiddleType = Type::IntTy; break;
1732 case 16: MiddleType = Type::ShortTy; break;
1733 case 8: MiddleType = Type::SByteTy; break;
1734 }
1735 if (MiddleType) {
1736 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1737 InsertNewInstBefore(NewTrunc, I);
1738 return new CastInst(NewTrunc, I.getType());
1739 }
1740 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001741 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001742
Chris Lattnerb8b97502003-08-13 19:01:45 +00001743 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001744 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001745 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001746
1747 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1748 if (RHSI->getOpcode() == Instruction::Sub)
1749 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1750 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1751 }
1752 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1753 if (LHSI->getOpcode() == Instruction::Sub)
1754 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1755 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1756 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001757 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001758
Chris Lattner147e9752002-05-08 22:46:53 +00001759 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001760 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001761 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001762
1763 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001764 if (!isa<Constant>(RHS))
1765 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001766 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001767
Misha Brukmanb1c93172005-04-21 23:48:37 +00001768
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001769 ConstantInt *C2;
1770 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1771 if (X == RHS) // X*C + X --> X * (C+1)
1772 return BinaryOperator::createMul(RHS, AddOne(C2));
1773
1774 // X*C1 + X*C2 --> X * (C1+C2)
1775 ConstantInt *C1;
1776 if (X == dyn_castFoldableMul(RHS, C1))
1777 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001778 }
1779
1780 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001781 if (dyn_castFoldableMul(RHS, C2) == LHS)
1782 return BinaryOperator::createMul(LHS, AddOne(C2));
1783
Chris Lattner57c8d992003-02-18 19:57:07 +00001784
Chris Lattnerb8b97502003-08-13 19:01:45 +00001785 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001786 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001787 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001788
Chris Lattnerb9cde762003-10-02 15:11:26 +00001789 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001790 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001791 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1792 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1793 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001794 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001795
Chris Lattnerbff91d92004-10-08 05:07:56 +00001796 // (X & FF00) + xx00 -> (X+xx00) & FF00
1797 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1798 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1799 if (Anded == CRHS) {
1800 // See if all bits from the first bit set in the Add RHS up are included
1801 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001802 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001803
1804 // Form a mask of all bits from the lowest bit added through the top.
1805 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001806 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001807
1808 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001809 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001810
Chris Lattnerbff91d92004-10-08 05:07:56 +00001811 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1812 // Okay, the xform is safe. Insert the new add pronto.
1813 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1814 LHS->getName()), I);
1815 return BinaryOperator::createAnd(NewAdd, C2);
1816 }
1817 }
1818 }
1819
Chris Lattnerd4252a72004-07-30 07:50:03 +00001820 // Try to fold constant add into select arguments.
1821 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001822 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001823 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001824 }
1825
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001826 // add (cast *A to intptrtype) B ->
1827 // cast (GEP (cast *A to sbyte*) B) ->
1828 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001829 {
1830 CastInst* CI = dyn_cast<CastInst>(LHS);
1831 Value* Other = RHS;
1832 if (!CI) {
1833 CI = dyn_cast<CastInst>(RHS);
1834 Other = LHS;
1835 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001836 if (CI && CI->getType()->isSized() &&
1837 (CI->getType()->getPrimitiveSize() ==
1838 TD->getIntPtrType()->getPrimitiveSize())
1839 && isa<PointerType>(CI->getOperand(0)->getType())) {
1840 Value* I2 = InsertCastBefore(CI->getOperand(0),
1841 PointerType::get(Type::SByteTy), I);
1842 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1843 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001844 }
1845 }
1846
Chris Lattner113f4f42002-06-25 16:13:24 +00001847 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001848}
1849
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001850// isSignBit - Return true if the value represented by the constant only has the
1851// highest order bit set.
1852static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001853 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001854 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001855}
1856
Chris Lattner022167f2004-03-13 00:11:49 +00001857/// RemoveNoopCast - Strip off nonconverting casts from the value.
1858///
1859static Value *RemoveNoopCast(Value *V) {
1860 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1861 const Type *CTy = CI->getType();
1862 const Type *OpTy = CI->getOperand(0)->getType();
1863 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001864 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001865 return RemoveNoopCast(CI->getOperand(0));
1866 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1867 return RemoveNoopCast(CI->getOperand(0));
1868 }
1869 return V;
1870}
1871
Chris Lattner113f4f42002-06-25 16:13:24 +00001872Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001874
Chris Lattnere6794492002-08-12 21:17:25 +00001875 if (Op0 == Op1) // sub X, X -> 0
1876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001877
Chris Lattnere6794492002-08-12 21:17:25 +00001878 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001879 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001880 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001881
Chris Lattner81a7a232004-10-16 18:11:37 +00001882 if (isa<UndefValue>(Op0))
1883 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1884 if (isa<UndefValue>(Op1))
1885 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1886
Chris Lattner8f2f5982003-11-05 01:06:05 +00001887 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1888 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001889 if (C->isAllOnesValue())
1890 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001891
Chris Lattner8f2f5982003-11-05 01:06:05 +00001892 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001893 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 if (match(Op1, m_Not(m_Value(X))))
1895 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001896 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001897 // -((uint)X >> 31) -> ((int)X >> 31)
1898 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001899 if (C->isNullValue()) {
1900 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1901 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001902 if (SI->getOpcode() == Instruction::Shr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001903 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001904 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001905 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001906 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001907 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001908 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001909 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001910 if (CU->getZExtValue() ==
1911 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001912 // Ok, the transformation is safe. Insert a cast of the incoming
1913 // value, then the new shift, then the new cast.
Reid Spencer00c482b2006-10-26 19:19:06 +00001914 Value *InV = InsertCastBefore(SI->getOperand(0), NewTy, I);
1915 Instruction *NewShift = new ShiftInst(Instruction::Shr, InV,
Chris Lattner92295c52004-03-12 23:53:13 +00001916 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001917 if (NewShift->getType() == I.getType())
1918 return NewShift;
1919 else {
Reid Spencer00c482b2006-10-26 19:19:06 +00001920 InsertNewInstBefore(NewShift, I);
Chris Lattner022167f2004-03-13 00:11:49 +00001921 return new CastInst(NewShift, I.getType());
1922 }
Chris Lattner92295c52004-03-12 23:53:13 +00001923 }
1924 }
Chris Lattner022167f2004-03-13 00:11:49 +00001925 }
Chris Lattner183b3362004-04-09 19:05:30 +00001926
1927 // Try to fold constant sub into select arguments.
1928 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001930 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001931
1932 if (isa<PHINode>(Op0))
1933 if (Instruction *NV = FoldOpIntoPhi(I))
1934 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001935 }
1936
Chris Lattnera9be4492005-04-07 16:15:25 +00001937 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1938 if (Op1I->getOpcode() == Instruction::Add &&
1939 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001940 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001941 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001942 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001943 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001944 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1945 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1946 // C1-(X+C2) --> (C1-C2)-X
1947 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1948 Op1I->getOperand(0));
1949 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001950 }
1951
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001952 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001953 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1954 // is not used by anyone else...
1955 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001956 if (Op1I->getOpcode() == Instruction::Sub &&
1957 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001958 // Swap the two operands of the subexpr...
1959 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1960 Op1I->setOperand(0, IIOp1);
1961 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001962
Chris Lattner3082c5a2003-02-18 19:28:33 +00001963 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001964 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001965 }
1966
1967 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1968 //
1969 if (Op1I->getOpcode() == Instruction::And &&
1970 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1971 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1972
Chris Lattner396dbfe2004-06-09 05:08:07 +00001973 Value *NewNot =
1974 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001975 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001976 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001977
Reid Spencer3c514952006-10-16 23:08:08 +00001978 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001979 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001980 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001981 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001982 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001983 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001984 ConstantExpr::getNeg(DivRHS));
1985
Chris Lattner57c8d992003-02-18 19:57:07 +00001986 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001987 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001988 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001989 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001990 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001991 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001992 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001993 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001994 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001995
Chris Lattner47060462005-04-07 17:14:51 +00001996 if (!Op0->getType()->isFloatingPoint())
1997 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1998 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001999 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2000 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2001 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2002 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002003 } else if (Op0I->getOpcode() == Instruction::Sub) {
2004 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2005 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002006 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002007
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002008 ConstantInt *C1;
2009 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2010 if (X == Op1) { // X*C - X --> X * (C-1)
2011 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2012 return BinaryOperator::createMul(Op1, CP1);
2013 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002014
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002015 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2016 if (X == dyn_castFoldableMul(Op1, C2))
2017 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2018 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002019 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002020}
2021
Chris Lattnere79e8542004-02-23 06:38:22 +00002022/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2023/// really just returns true if the most significant (sign) bit is set.
2024static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2025 if (RHS->getType()->isSigned()) {
2026 // True if source is LHS < 0 or LHS <= -1
2027 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2028 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2029 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002030 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002031 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2032 // the size of the integer type.
2033 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002034 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002035 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002036 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002037 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002038 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002039 }
2040 return false;
2041}
2042
Chris Lattner113f4f42002-06-25 16:13:24 +00002043Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002044 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002045 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002046
Chris Lattner81a7a232004-10-16 18:11:37 +00002047 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2049
Chris Lattnere6794492002-08-12 21:17:25 +00002050 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002053
2054 // ((X << C1)*C2) == (X * (C2 << C1))
2055 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2056 if (SI->getOpcode() == Instruction::Shl)
2057 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002058 return BinaryOperator::createMul(SI->getOperand(0),
2059 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002060
Chris Lattnercce81be2003-09-11 22:24:54 +00002061 if (CI->isNullValue())
2062 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2063 if (CI->equalsInt(1)) // X * 1 == X
2064 return ReplaceInstUsesWith(I, Op0);
2065 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002066 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002067
Reid Spencere0fc4df2006-10-20 07:07:24 +00002068 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002069 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2070 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002071 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002072 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002073 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002074 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002075 if (Op1F->isNullValue())
2076 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002077
Chris Lattner3082c5a2003-02-18 19:28:33 +00002078 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2079 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2080 if (Op1F->getValue() == 1.0)
2081 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2082 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002083
2084 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2085 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2086 isa<ConstantInt>(Op0I->getOperand(1))) {
2087 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2088 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2089 Op1, "tmp");
2090 InsertNewInstBefore(Add, I);
2091 Value *C1C2 = ConstantExpr::getMul(Op1,
2092 cast<Constant>(Op0I->getOperand(1)));
2093 return BinaryOperator::createAdd(Add, C1C2);
2094
2095 }
Chris Lattner183b3362004-04-09 19:05:30 +00002096
2097 // Try to fold constant mul into select arguments.
2098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002100 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002101
2102 if (isa<PHINode>(Op0))
2103 if (Instruction *NV = FoldOpIntoPhi(I))
2104 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002105 }
2106
Chris Lattner934a64cf2003-03-10 23:23:04 +00002107 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2108 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002109 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002110
Chris Lattner2635b522004-02-23 05:39:21 +00002111 // If one of the operands of the multiply is a cast from a boolean value, then
2112 // we know the bool is either zero or one, so this is a 'masking' multiply.
2113 // See if we can simplify things based on how the boolean was originally
2114 // formed.
2115 CastInst *BoolCast = 0;
2116 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2117 if (CI->getOperand(0)->getType() == Type::BoolTy)
2118 BoolCast = CI;
2119 if (!BoolCast)
2120 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2121 if (CI->getOperand(0)->getType() == Type::BoolTy)
2122 BoolCast = CI;
2123 if (BoolCast) {
2124 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2125 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2126 const Type *SCOpTy = SCIOp0->getType();
2127
Chris Lattnere79e8542004-02-23 06:38:22 +00002128 // If the setcc is true iff the sign bit of X is set, then convert this
2129 // multiply into a shift/and combination.
2130 if (isa<ConstantInt>(SCIOp1) &&
2131 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002132 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002133 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002134 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002135 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002136 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002137 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002138 }
2139
2140 Value *V =
2141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142 BoolCast->getOperand(0)->getName()+
2143 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002144
2145 // If the multiply type is not the same as the source type, sign extend
2146 // or truncate to the multiply type.
2147 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002148 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002149
Chris Lattner2635b522004-02-23 05:39:21 +00002150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002151 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002152 }
2153 }
2154 }
2155
Chris Lattner113f4f42002-06-25 16:13:24 +00002156 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002157}
2158
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002159/// This function implements the transforms on div instructions that work
2160/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2161/// used by the visitors to those instructions.
2162/// @brief Transforms common to all three div instructions
2163Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002165
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002166 // undef / X -> 0
2167 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002168 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002169
2170 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002171 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002172 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002173
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002174 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002175 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2176 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002177 // same basic block, then we replace the select with Y, and the condition
2178 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002179 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002180 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002181 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2182 if (ST->isNullValue()) {
2183 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2184 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002185 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002186 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2187 I.setOperand(1, SI->getOperand(2));
2188 else
2189 UpdateValueUsesWith(SI, SI->getOperand(2));
2190 return &I;
2191 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002192
Chris Lattnerd79dc792006-09-09 20:26:32 +00002193 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2194 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2195 if (ST->isNullValue()) {
2196 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2197 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002198 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002199 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2200 I.setOperand(1, SI->getOperand(1));
2201 else
2202 UpdateValueUsesWith(SI, SI->getOperand(1));
2203 return &I;
2204 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002205 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002206
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002207 return 0;
2208}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002209
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002210/// This function implements the transforms common to both integer division
2211/// instructions (udiv and sdiv). It is called by the visitors to those integer
2212/// division instructions.
2213/// @brief Common integer divide transforms
2214Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2215 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2216
2217 if (Instruction *Common = commonDivTransforms(I))
2218 return Common;
2219
2220 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2221 // div X, 1 == X
2222 if (RHS->equalsInt(1))
2223 return ReplaceInstUsesWith(I, Op0);
2224
2225 // (X / C1) / C2 -> X / (C1*C2)
2226 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2227 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2228 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2229 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2230 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002231 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002232
2233 if (!RHS->isNullValue()) { // avoid X udiv 0
2234 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2235 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2236 return R;
2237 if (isa<PHINode>(Op0))
2238 if (Instruction *NV = FoldOpIntoPhi(I))
2239 return NV;
2240 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002241 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002242
Chris Lattner3082c5a2003-02-18 19:28:33 +00002243 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002244 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002245 if (LHS->equalsInt(0))
2246 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2247
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002248 return 0;
2249}
2250
2251Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2253
2254 // Handle the integer div common cases
2255 if (Instruction *Common = commonIDivTransforms(I))
2256 return Common;
2257
2258 // X udiv C^2 -> X >> C
2259 // Check to see if this is an unsigned division with an exact power of 2,
2260 // if so, convert to a right shift.
2261 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2262 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2263 if (isPowerOf2_64(Val)) {
2264 uint64_t ShiftAmt = Log2_64(Val);
2265 Value* X = Op0;
2266 const Type* XTy = X->getType();
2267 bool isSigned = XTy->isSigned();
2268 if (isSigned)
2269 X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2270 Instruction* Result =
2271 new ShiftInst(Instruction::Shr, X,
2272 ConstantInt::get(Type::UByteTy, ShiftAmt));
2273 if (!isSigned)
2274 return Result;
2275 InsertNewInstBefore(Result, I);
2276 return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2277 }
2278 }
2279
2280 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2281 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2282 if (RHSI->getOpcode() == Instruction::Shl &&
2283 isa<ConstantInt>(RHSI->getOperand(0))) {
2284 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2285 if (isPowerOf2_64(C1)) {
2286 Value *N = RHSI->getOperand(1);
2287 const Type* NTy = N->getType();
2288 bool isSigned = NTy->isSigned();
2289 if (uint64_t C2 = Log2_64(C1)) {
2290 if (isSigned) {
2291 NTy = NTy->getUnsignedVersion();
2292 N = InsertCastBefore(N, NTy, I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002293 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002294 Constant *C2V = ConstantInt::get(NTy, C2);
2295 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002296 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002297 Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2298 if (!isSigned)
2299 return Result;
2300 InsertNewInstBefore(Result, I);
2301 return new CastInst(Result, NTy->getSignedVersion(), I.getName());
Chris Lattner2e90b732006-02-05 07:54:04 +00002302 }
2303 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002304 }
2305
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002306 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2307 // where C1&C2 are powers of two.
2308 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2309 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2310 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2311 if (!STO->isNullValue() && !STO->isNullValue()) {
2312 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2313 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2314 // Compute the shift amounts
2315 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2316 // Make sure we get the unsigned version of X
2317 Value* X = Op0;
2318 const Type* origXTy = X->getType();
2319 bool isSigned = origXTy->isSigned();
2320 if (isSigned)
2321 X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2322 // Construct the "on true" case of the select
2323 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2324 Instruction *TSI =
2325 new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2326 TSI = InsertNewInstBefore(TSI, I);
2327
2328 // Construct the "on false" case of the select
2329 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2330 Instruction *FSI =
2331 new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2332 FSI = InsertNewInstBefore(FSI, I);
2333
2334 // construct the select instruction and return it.
2335 SelectInst* NewSI =
2336 new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2337 if (!isSigned)
2338 return NewSI;
2339 InsertNewInstBefore(NewSI, I);
2340 return new CastInst(NewSI, origXTy, NewSI->getName());
2341 }
2342 }
2343 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002344 return 0;
2345}
2346
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002347Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2349
2350 // Handle the integer div common cases
2351 if (Instruction *Common = commonIDivTransforms(I))
2352 return Common;
2353
2354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2355 // sdiv X, -1 == -X
2356 if (RHS->isAllOnesValue())
2357 return BinaryOperator::createNeg(Op0);
2358
2359 // -X/C -> X/-C
2360 if (Value *LHSNeg = dyn_castNegVal(Op0))
2361 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2362 }
2363
2364 // If the sign bits of both operands are zero (i.e. we can prove they are
2365 // unsigned inputs), turn this into a udiv.
2366 if (I.getType()->isInteger()) {
2367 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2368 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2369 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2370 }
2371 }
2372
2373 return 0;
2374}
2375
2376Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2377 return commonDivTransforms(I);
2378}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002379
Chris Lattner85dda9a2006-03-02 06:50:58 +00002380/// GetFactor - If we can prove that the specified value is at least a multiple
2381/// of some factor, return that factor.
2382static Constant *GetFactor(Value *V) {
2383 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2384 return CI;
2385
2386 // Unless we can be tricky, we know this is a multiple of 1.
2387 Constant *Result = ConstantInt::get(V->getType(), 1);
2388
2389 Instruction *I = dyn_cast<Instruction>(V);
2390 if (!I) return Result;
2391
2392 if (I->getOpcode() == Instruction::Mul) {
2393 // Handle multiplies by a constant, etc.
2394 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2395 GetFactor(I->getOperand(1)));
2396 } else if (I->getOpcode() == Instruction::Shl) {
2397 // (X<<C) -> X * (1 << C)
2398 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2399 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2400 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2401 }
2402 } else if (I->getOpcode() == Instruction::And) {
2403 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2404 // X & 0xFFF0 is known to be a multiple of 16.
2405 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2406 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2407 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002408 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002409 }
2410 } else if (I->getOpcode() == Instruction::Cast) {
2411 Value *Op = I->getOperand(0);
2412 // Only handle int->int casts.
2413 if (!Op->getType()->isInteger()) return Result;
2414 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2415 }
2416 return Result;
2417}
2418
Reid Spencer7eb55b32006-11-02 01:53:59 +00002419/// This function implements the transforms on rem instructions that work
2420/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2421/// is used by the visitors to those instructions.
2422/// @brief Transforms common to all three rem instructions
2423Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002425
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002426 // 0 % X == 0, we don't need to preserve faults!
2427 if (Constant *LHS = dyn_cast<Constant>(Op0))
2428 if (LHS->isNullValue())
2429 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2430
2431 if (isa<UndefValue>(Op0)) // undef % X -> 0
2432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2433 if (isa<UndefValue>(Op1))
2434 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002435
2436 // Handle cases involving: rem X, (select Cond, Y, Z)
2437 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2438 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2439 // the same basic block, then we replace the select with Y, and the
2440 // condition of the select with false (if the cond value is in the same
2441 // BB). If the select has uses other than the div, this allows them to be
2442 // simplified also.
2443 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2444 if (ST->isNullValue()) {
2445 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2446 if (CondI && CondI->getParent() == I.getParent())
2447 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2448 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2449 I.setOperand(1, SI->getOperand(2));
2450 else
2451 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002452 return &I;
2453 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002454 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2455 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2456 if (ST->isNullValue()) {
2457 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2458 if (CondI && CondI->getParent() == I.getParent())
2459 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2460 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2461 I.setOperand(1, SI->getOperand(1));
2462 else
2463 UpdateValueUsesWith(SI, SI->getOperand(1));
2464 return &I;
2465 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002466 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002467
Reid Spencer7eb55b32006-11-02 01:53:59 +00002468 return 0;
2469}
2470
2471/// This function implements the transforms common to both integer remainder
2472/// instructions (urem and srem). It is called by the visitors to those integer
2473/// remainder instructions.
2474/// @brief Common integer remainder transforms
2475Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2476 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2477
2478 if (Instruction *common = commonRemTransforms(I))
2479 return common;
2480
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002481 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002482 // X % 0 == undef, we don't need to preserve faults!
2483 if (RHS->equalsInt(0))
2484 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2485
Chris Lattner3082c5a2003-02-18 19:28:33 +00002486 if (RHS->equalsInt(1)) // X % 1 == 0
2487 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2488
Chris Lattnerb70f1412006-02-28 05:49:21 +00002489 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2490 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2491 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2492 return R;
2493 } else if (isa<PHINode>(Op0I)) {
2494 if (Instruction *NV = FoldOpIntoPhi(I))
2495 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002496 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002497 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2498 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002500 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002501 }
2502
Reid Spencer7eb55b32006-11-02 01:53:59 +00002503 return 0;
2504}
2505
2506Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2508
2509 if (Instruction *common = commonIRemTransforms(I))
2510 return common;
2511
2512 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2513 // X urem C^2 -> X and C
2514 // Check to see if this is an unsigned remainder with an exact power of 2,
2515 // if so, convert to a bitwise and.
2516 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2517 if (isPowerOf2_64(C->getZExtValue()))
2518 return BinaryOperator::createAnd(Op0, SubOne(C));
2519 }
2520
Chris Lattner2e90b732006-02-05 07:54:04 +00002521 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002522 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2523 if (RHSI->getOpcode() == Instruction::Shl &&
2524 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002525 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002526 if (isPowerOf2_64(C1)) {
2527 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2528 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2529 "tmp"), I);
2530 return BinaryOperator::createAnd(Op0, Add);
2531 }
2532 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002533 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002534
Reid Spencer7eb55b32006-11-02 01:53:59 +00002535 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2536 // where C1&C2 are powers of two.
2537 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2538 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2539 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2540 // STO == 0 and SFO == 0 handled above.
2541 if (isPowerOf2_64(STO->getZExtValue()) &&
2542 isPowerOf2_64(SFO->getZExtValue())) {
2543 Value *TrueAnd = InsertNewInstBefore(
2544 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2545 Value *FalseAnd = InsertNewInstBefore(
2546 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2547 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2548 }
2549 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002550 }
2551
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002552 return 0;
2553}
2554
Reid Spencer7eb55b32006-11-02 01:53:59 +00002555Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2557
2558 if (Instruction *common = commonIRemTransforms(I))
2559 return common;
2560
2561 if (Value *RHSNeg = dyn_castNegVal(Op1))
2562 if (!isa<ConstantInt>(RHSNeg) ||
2563 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2564 // X % -Y -> X % Y
2565 AddUsesToWorkList(I);
2566 I.setOperand(1, RHSNeg);
2567 return &I;
2568 }
2569
2570 // If the top bits of both operands are zero (i.e. we can prove they are
2571 // unsigned inputs), turn this into a urem.
2572 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2573 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2574 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2575 return BinaryOperator::createURem(Op0, Op1, I.getName());
2576 }
2577
2578 return 0;
2579}
2580
2581Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002582 return commonRemTransforms(I);
2583}
2584
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002585// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002586static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002587 if (C->getType()->isUnsigned())
2588 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002589
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002590 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002591 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002592 int64_t Val = INT64_MAX; // All ones
2593 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002594 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002595}
2596
2597// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002598static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002599 if (C->getType()->isUnsigned())
2600 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002601
2602 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002603 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002604 int64_t Val = -1; // All ones
2605 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002606 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002607}
2608
Chris Lattner35167c32004-06-09 07:59:58 +00002609// isOneBitSet - Return true if there is exactly one bit set in the specified
2610// constant.
2611static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002612 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002613 return V && (V & (V-1)) == 0;
2614}
2615
Chris Lattner8fc5af42004-09-23 21:46:38 +00002616#if 0 // Currently unused
2617// isLowOnes - Return true if the constant is of the form 0+1+.
2618static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002619 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002620
2621 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002622 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002623
2624 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2625 return U && V && (U & V) == 0;
2626}
2627#endif
2628
2629// isHighOnes - Return true if the constant is of the form 1+0+.
2630// This is the same as lowones(~X).
2631static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002632 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002633 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002634
2635 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002636 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002637
2638 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2639 return U && V && (U & V) == 0;
2640}
2641
2642
Chris Lattner3ac7c262003-08-13 20:16:26 +00002643/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2644/// are carefully arranged to allow folding of expressions such as:
2645///
2646/// (A < B) | (A > B) --> (A != B)
2647///
2648/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2649/// represents that the comparison is true if A == B, and bit value '1' is true
2650/// if A < B.
2651///
2652static unsigned getSetCondCode(const SetCondInst *SCI) {
2653 switch (SCI->getOpcode()) {
2654 // False -> 0
2655 case Instruction::SetGT: return 1;
2656 case Instruction::SetEQ: return 2;
2657 case Instruction::SetGE: return 3;
2658 case Instruction::SetLT: return 4;
2659 case Instruction::SetNE: return 5;
2660 case Instruction::SetLE: return 6;
2661 // True -> 7
2662 default:
2663 assert(0 && "Invalid SetCC opcode!");
2664 return 0;
2665 }
2666}
2667
2668/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2669/// opcode and two operands into either a constant true or false, or a brand new
2670/// SetCC instruction.
2671static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2672 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002673 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002674 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2675 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2676 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2677 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2678 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2679 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002680 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002681 default: assert(0 && "Illegal SetCCCode!"); return 0;
2682 }
2683}
2684
2685// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2686struct FoldSetCCLogical {
2687 InstCombiner &IC;
2688 Value *LHS, *RHS;
2689 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2690 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2691 bool shouldApply(Value *V) const {
2692 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2693 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2694 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2695 return false;
2696 }
2697 Instruction *apply(BinaryOperator &Log) const {
2698 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2699 if (SCI->getOperand(0) != LHS) {
2700 assert(SCI->getOperand(1) == LHS);
2701 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2702 }
2703
2704 unsigned LHSCode = getSetCondCode(SCI);
2705 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2706 unsigned Code;
2707 switch (Log.getOpcode()) {
2708 case Instruction::And: Code = LHSCode & RHSCode; break;
2709 case Instruction::Or: Code = LHSCode | RHSCode; break;
2710 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002711 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002712 }
2713
2714 Value *RV = getSetCCValue(Code, LHS, RHS);
2715 if (Instruction *I = dyn_cast<Instruction>(RV))
2716 return I;
2717 // Otherwise, it's a constant boolean value...
2718 return IC.ReplaceInstUsesWith(Log, RV);
2719 }
2720};
2721
Chris Lattnerba1cb382003-09-19 17:17:26 +00002722// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2723// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2724// guaranteed to be either a shift instruction or a binary operator.
2725Instruction *InstCombiner::OptAndOp(Instruction *Op,
2726 ConstantIntegral *OpRHS,
2727 ConstantIntegral *AndRHS,
2728 BinaryOperator &TheAnd) {
2729 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002730 Constant *Together = 0;
2731 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002732 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002733
Chris Lattnerba1cb382003-09-19 17:17:26 +00002734 switch (Op->getOpcode()) {
2735 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002736 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002737 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2738 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002739 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002740 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002741 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002742 }
2743 break;
2744 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002745 if (Together == AndRHS) // (X | C) & C --> C
2746 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002747
Chris Lattner86102b82005-01-01 16:22:27 +00002748 if (Op->hasOneUse() && Together != OpRHS) {
2749 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2750 std::string Op0Name = Op->getName(); Op->setName("");
2751 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2752 InsertNewInstBefore(Or, TheAnd);
2753 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002754 }
2755 break;
2756 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002757 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002758 // Adding a one to a single bit bit-field should be turned into an XOR
2759 // of the bit. First thing to check is to see if this AND is with a
2760 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002761 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002762
2763 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002764 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002765
2766 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002767 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002768 // Ok, at this point, we know that we are masking the result of the
2769 // ADD down to exactly one bit. If the constant we are adding has
2770 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002771 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002772
Chris Lattnerba1cb382003-09-19 17:17:26 +00002773 // Check to see if any bits below the one bit set in AndRHSV are set.
2774 if ((AddRHS & (AndRHSV-1)) == 0) {
2775 // If not, the only thing that can effect the output of the AND is
2776 // the bit specified by AndRHSV. If that bit is set, the effect of
2777 // the XOR is to toggle the bit. If it is clear, then the ADD has
2778 // no effect.
2779 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2780 TheAnd.setOperand(0, X);
2781 return &TheAnd;
2782 } else {
2783 std::string Name = Op->getName(); Op->setName("");
2784 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002785 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002786 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002787 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002788 }
2789 }
2790 }
2791 }
2792 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002793
2794 case Instruction::Shl: {
2795 // We know that the AND will not produce any of the bits shifted in, so if
2796 // the anded constant includes them, clear them now!
2797 //
2798 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002799 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2800 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002801
Chris Lattner7e794272004-09-24 15:21:34 +00002802 if (CI == ShlMask) { // Masking out bits that the shift already masks
2803 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2804 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002805 TheAnd.setOperand(1, CI);
2806 return &TheAnd;
2807 }
2808 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002809 }
Chris Lattner2da29172003-09-19 19:05:02 +00002810 case Instruction::Shr:
2811 // We know that the AND will not produce any of the bits shifted in, so if
2812 // the anded constant includes them, clear them now! This only applies to
2813 // unsigned shifts, because a signed shr may bring in set bits!
2814 //
2815 if (AndRHS->getType()->isUnsigned()) {
2816 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002817 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2818 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2819
2820 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2821 return ReplaceInstUsesWith(TheAnd, Op);
2822 } else if (CI != AndRHS) {
2823 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002824 return &TheAnd;
2825 }
Chris Lattner7e794272004-09-24 15:21:34 +00002826 } else { // Signed shr.
2827 // See if this is shifting in some sign extension, then masking it out
2828 // with an and.
2829 if (Op->hasOneUse()) {
2830 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2831 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2832 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002833 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002834 // Make the argument unsigned.
2835 Value *ShVal = Op->getOperand(0);
2836 ShVal = InsertCastBefore(ShVal,
2837 ShVal->getType()->getUnsignedVersion(),
2838 TheAnd);
2839 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2840 OpRHS, Op->getName()),
2841 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002842 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2843 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2844 TheAnd.getName()),
2845 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002846 return new CastInst(ShVal, Op->getType());
2847 }
2848 }
Chris Lattner2da29172003-09-19 19:05:02 +00002849 }
2850 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002851 }
2852 return 0;
2853}
2854
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002855
Chris Lattner6862fbd2004-09-29 17:40:11 +00002856/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2857/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2858/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2859/// insert new instructions.
2860Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2861 bool Inside, Instruction &IB) {
2862 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2863 "Lo is not <= Hi in range emission code!");
2864 if (Inside) {
2865 if (Lo == Hi) // Trivially false.
2866 return new SetCondInst(Instruction::SetNE, V, V);
2867 if (cast<ConstantIntegral>(Lo)->isMinValue())
2868 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002869
Chris Lattner6862fbd2004-09-29 17:40:11 +00002870 Constant *AddCST = ConstantExpr::getNeg(Lo);
2871 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2872 InsertNewInstBefore(Add, IB);
2873 // Convert to unsigned for the comparison.
2874 const Type *UnsType = Add->getType()->getUnsignedVersion();
2875 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2876 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2877 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2878 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2879 }
2880
2881 if (Lo == Hi) // Trivially true.
2882 return new SetCondInst(Instruction::SetEQ, V, V);
2883
2884 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002885
2886 // V < 0 || V >= Hi ->'V > Hi-1'
2887 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002888 return new SetCondInst(Instruction::SetGT, V, Hi);
2889
2890 // Emit X-Lo > Hi-Lo-1
2891 Constant *AddCST = ConstantExpr::getNeg(Lo);
2892 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2893 InsertNewInstBefore(Add, IB);
2894 // Convert to unsigned for the comparison.
2895 const Type *UnsType = Add->getType()->getUnsignedVersion();
2896 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2897 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2898 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2899 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2900}
2901
Chris Lattnerb4b25302005-09-18 07:22:02 +00002902// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2903// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2904// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2905// not, since all 1s are not contiguous.
2906static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002907 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002908 if (!isShiftedMask_64(V)) return false;
2909
2910 // look for the first zero bit after the run of ones
2911 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2912 // look for the first non-zero bit
2913 ME = 64-CountLeadingZeros_64(V);
2914 return true;
2915}
2916
2917
2918
2919/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2920/// where isSub determines whether the operator is a sub. If we can fold one of
2921/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002922///
2923/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2924/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2925/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2926///
2927/// return (A +/- B).
2928///
2929Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2930 ConstantIntegral *Mask, bool isSub,
2931 Instruction &I) {
2932 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2933 if (!LHSI || LHSI->getNumOperands() != 2 ||
2934 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2935
2936 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2937
2938 switch (LHSI->getOpcode()) {
2939 default: return 0;
2940 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002941 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2942 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002943 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002944 break;
2945
2946 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2947 // part, we don't need any explicit masks to take them out of A. If that
2948 // is all N is, ignore it.
2949 unsigned MB, ME;
2950 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002951 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2952 Mask >>= 64-MB+1;
2953 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002954 break;
2955 }
2956 }
Chris Lattneraf517572005-09-18 04:24:45 +00002957 return 0;
2958 case Instruction::Or:
2959 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002960 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002961 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002962 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002963 break;
2964 return 0;
2965 }
2966
2967 Instruction *New;
2968 if (isSub)
2969 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2970 else
2971 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2972 return InsertNewInstBefore(New, I);
2973}
2974
Chris Lattner113f4f42002-06-25 16:13:24 +00002975Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002976 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002978
Chris Lattner81a7a232004-10-16 18:11:37 +00002979 if (isa<UndefValue>(Op1)) // X & undef -> 0
2980 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2981
Chris Lattner86102b82005-01-01 16:22:27 +00002982 // and X, X = X
2983 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002984 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002985
Chris Lattner5b2edb12006-02-12 08:02:11 +00002986 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002987 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002988 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002989 if (!isa<PackedType>(I.getType()) &&
2990 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002991 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002992 return &I;
2993
Chris Lattner86102b82005-01-01 16:22:27 +00002994 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002995 uint64_t AndRHSMask = AndRHS->getZExtValue();
2996 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002997 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002998
Chris Lattnerba1cb382003-09-19 17:17:26 +00002999 // Optimize a variety of ((val OP C1) & C2) combinations...
3000 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3001 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003002 Value *Op0LHS = Op0I->getOperand(0);
3003 Value *Op0RHS = Op0I->getOperand(1);
3004 switch (Op0I->getOpcode()) {
3005 case Instruction::Xor:
3006 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003007 // If the mask is only needed on one incoming arm, push it up.
3008 if (Op0I->hasOneUse()) {
3009 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3010 // Not masking anything out for the LHS, move to RHS.
3011 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3012 Op0RHS->getName()+".masked");
3013 InsertNewInstBefore(NewRHS, I);
3014 return BinaryOperator::create(
3015 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003016 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003017 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003018 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3019 // Not masking anything out for the RHS, move to LHS.
3020 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3021 Op0LHS->getName()+".masked");
3022 InsertNewInstBefore(NewLHS, I);
3023 return BinaryOperator::create(
3024 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3025 }
3026 }
3027
Chris Lattner86102b82005-01-01 16:22:27 +00003028 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003029 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003030 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3031 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3032 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3033 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3034 return BinaryOperator::createAnd(V, AndRHS);
3035 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3036 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003037 break;
3038
3039 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003040 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3041 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3042 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3043 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3044 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003045 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003046 }
3047
Chris Lattner16464b32003-07-23 19:25:52 +00003048 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003049 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003050 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003051 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3052 const Type *SrcTy = CI->getOperand(0)->getType();
3053
Chris Lattner2c14cf72005-08-07 07:03:10 +00003054 // If this is an integer truncation or change from signed-to-unsigned, and
3055 // if the source is an and/or with immediate, transform it. This
3056 // frequently occurs for bitfield accesses.
3057 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3058 if (SrcTy->getPrimitiveSizeInBits() >=
3059 I.getType()->getPrimitiveSizeInBits() &&
3060 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003061 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003062 if (CastOp->getOpcode() == Instruction::And) {
3063 // Change: and (cast (and X, C1) to T), C2
3064 // into : and (cast X to T), trunc(C1)&C2
3065 // This will folds the two ands together, which may allow other
3066 // simplifications.
3067 Instruction *NewCast =
3068 new CastInst(CastOp->getOperand(0), I.getType(),
3069 CastOp->getName()+".shrunk");
3070 NewCast = InsertNewInstBefore(NewCast, I);
3071
3072 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3073 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3074 return BinaryOperator::createAnd(NewCast, C3);
3075 } else if (CastOp->getOpcode() == Instruction::Or) {
3076 // Change: and (cast (or X, C1) to T), C2
3077 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3078 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3079 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3080 return ReplaceInstUsesWith(I, AndRHS);
3081 }
3082 }
Chris Lattner33217db2003-07-23 19:36:21 +00003083 }
Chris Lattner183b3362004-04-09 19:05:30 +00003084
3085 // Try to fold constant and into select arguments.
3086 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003087 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003088 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003089 if (isa<PHINode>(Op0))
3090 if (Instruction *NV = FoldOpIntoPhi(I))
3091 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003092 }
3093
Chris Lattnerbb74e222003-03-10 23:06:50 +00003094 Value *Op0NotVal = dyn_castNotVal(Op0);
3095 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003096
Chris Lattner023a4832004-06-18 06:07:51 +00003097 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3099
Misha Brukman9c003d82004-07-30 12:50:08 +00003100 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003101 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003102 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3103 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003104 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003105 return BinaryOperator::createNot(Or);
3106 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003107
3108 {
3109 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003110 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3111 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3112 return ReplaceInstUsesWith(I, Op1);
3113 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3114 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3115 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003116
3117 if (Op0->hasOneUse() &&
3118 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3119 if (A == Op1) { // (A^B)&A -> A&(A^B)
3120 I.swapOperands(); // Simplify below
3121 std::swap(Op0, Op1);
3122 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3123 cast<BinaryOperator>(Op0)->swapOperands();
3124 I.swapOperands(); // Simplify below
3125 std::swap(Op0, Op1);
3126 }
3127 }
3128 if (Op1->hasOneUse() &&
3129 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3130 if (B == Op0) { // B&(A^B) -> B&(B^A)
3131 cast<BinaryOperator>(Op1)->swapOperands();
3132 std::swap(A, B);
3133 }
3134 if (A == Op0) { // A&(A^B) -> A & ~B
3135 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3136 InsertNewInstBefore(NotB, I);
3137 return BinaryOperator::createAnd(A, NotB);
3138 }
3139 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003140 }
3141
Chris Lattner3082c5a2003-02-18 19:28:33 +00003142
Chris Lattner623826c2004-09-28 21:48:02 +00003143 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3144 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003145 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3146 return R;
3147
Chris Lattner623826c2004-09-28 21:48:02 +00003148 Value *LHSVal, *RHSVal;
3149 ConstantInt *LHSCst, *RHSCst;
3150 Instruction::BinaryOps LHSCC, RHSCC;
3151 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3152 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3153 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3154 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003155 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003156 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3157 // Ensure that the larger constant is on the RHS.
3158 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3159 SetCondInst *LHS = cast<SetCondInst>(Op0);
3160 if (cast<ConstantBool>(Cmp)->getValue()) {
3161 std::swap(LHS, RHS);
3162 std::swap(LHSCst, RHSCst);
3163 std::swap(LHSCC, RHSCC);
3164 }
3165
3166 // At this point, we know we have have two setcc instructions
3167 // comparing a value against two constants and and'ing the result
3168 // together. Because of the above check, we know that we only have
3169 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3170 // FoldSetCCLogical check above), that the two constants are not
3171 // equal.
3172 assert(LHSCst != RHSCst && "Compares not folded above?");
3173
3174 switch (LHSCC) {
3175 default: assert(0 && "Unknown integer condition code!");
3176 case Instruction::SetEQ:
3177 switch (RHSCC) {
3178 default: assert(0 && "Unknown integer condition code!");
3179 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3180 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003181 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003182 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3183 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3184 return ReplaceInstUsesWith(I, LHS);
3185 }
3186 case Instruction::SetNE:
3187 switch (RHSCC) {
3188 default: assert(0 && "Unknown integer condition code!");
3189 case Instruction::SetLT:
3190 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3191 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3192 break; // (X != 13 & X < 15) -> no change
3193 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3194 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3195 return ReplaceInstUsesWith(I, RHS);
3196 case Instruction::SetNE:
3197 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3198 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3199 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3200 LHSVal->getName()+".off");
3201 InsertNewInstBefore(Add, I);
3202 const Type *UnsType = Add->getType()->getUnsignedVersion();
3203 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3204 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3205 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3206 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3207 }
3208 break; // (X != 13 & X != 15) -> no change
3209 }
3210 break;
3211 case Instruction::SetLT:
3212 switch (RHSCC) {
3213 default: assert(0 && "Unknown integer condition code!");
3214 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3215 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003216 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003217 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3218 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3219 return ReplaceInstUsesWith(I, LHS);
3220 }
3221 case Instruction::SetGT:
3222 switch (RHSCC) {
3223 default: assert(0 && "Unknown integer condition code!");
3224 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3225 return ReplaceInstUsesWith(I, LHS);
3226 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3227 return ReplaceInstUsesWith(I, RHS);
3228 case Instruction::SetNE:
3229 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3230 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3231 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003232 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3233 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003234 }
3235 }
3236 }
3237 }
3238
Chris Lattner3af10532006-05-05 06:39:07 +00003239 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3240 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003241 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003243 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003244 // Only do this if the casts both really cause code to be generated.
3245 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3246 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003247 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3248 Op1C->getOperand(0),
3249 I.getName());
3250 InsertNewInstBefore(NewOp, I);
3251 return new CastInst(NewOp, I.getType());
3252 }
3253 }
3254
Chris Lattner113f4f42002-06-25 16:13:24 +00003255 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003256}
3257
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003258/// CollectBSwapParts - Look to see if the specified value defines a single byte
3259/// in the result. If it does, and if the specified byte hasn't been filled in
3260/// yet, fill it in and return false.
3261static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3262 Instruction *I = dyn_cast<Instruction>(V);
3263 if (I == 0) return true;
3264
3265 // If this is an or instruction, it is an inner node of the bswap.
3266 if (I->getOpcode() == Instruction::Or)
3267 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3268 CollectBSwapParts(I->getOperand(1), ByteValues);
3269
3270 // If this is a shift by a constant int, and it is "24", then its operand
3271 // defines a byte. We only handle unsigned types here.
3272 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3273 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003274 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003275 8*(ByteValues.size()-1))
3276 return true;
3277
3278 unsigned DestNo;
3279 if (I->getOpcode() == Instruction::Shl) {
3280 // X << 24 defines the top byte with the lowest of the input bytes.
3281 DestNo = ByteValues.size()-1;
3282 } else {
3283 // X >>u 24 defines the low byte with the highest of the input bytes.
3284 DestNo = 0;
3285 }
3286
3287 // If the destination byte value is already defined, the values are or'd
3288 // together, which isn't a bswap (unless it's an or of the same bits).
3289 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3290 return true;
3291 ByteValues[DestNo] = I->getOperand(0);
3292 return false;
3293 }
3294
3295 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3296 // don't have this.
3297 Value *Shift = 0, *ShiftLHS = 0;
3298 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3299 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3300 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3301 return true;
3302 Instruction *SI = cast<Instruction>(Shift);
3303
3304 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003305 if (ShiftAmt->getZExtValue() & 7 ||
3306 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003307 return true;
3308
3309 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3310 unsigned DestByte;
3311 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003312 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003313 break;
3314 // Unknown mask for bswap.
3315 if (DestByte == ByteValues.size()) return true;
3316
Reid Spencere0fc4df2006-10-20 07:07:24 +00003317 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003318 unsigned SrcByte;
3319 if (SI->getOpcode() == Instruction::Shl)
3320 SrcByte = DestByte - ShiftBytes;
3321 else
3322 SrcByte = DestByte + ShiftBytes;
3323
3324 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3325 if (SrcByte != ByteValues.size()-DestByte-1)
3326 return true;
3327
3328 // If the destination byte value is already defined, the values are or'd
3329 // together, which isn't a bswap (unless it's an or of the same bits).
3330 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3331 return true;
3332 ByteValues[DestByte] = SI->getOperand(0);
3333 return false;
3334}
3335
3336/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3337/// If so, insert the new bswap intrinsic and return it.
3338Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3339 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3340 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3341 return 0;
3342
3343 /// ByteValues - For each byte of the result, we keep track of which value
3344 /// defines each byte.
3345 std::vector<Value*> ByteValues;
3346 ByteValues.resize(I.getType()->getPrimitiveSize());
3347
3348 // Try to find all the pieces corresponding to the bswap.
3349 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3350 CollectBSwapParts(I.getOperand(1), ByteValues))
3351 return 0;
3352
3353 // Check to see if all of the bytes come from the same value.
3354 Value *V = ByteValues[0];
3355 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3356
3357 // Check to make sure that all of the bytes come from the same value.
3358 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3359 if (ByteValues[i] != V)
3360 return 0;
3361
3362 // If they do then *success* we can turn this into a bswap. Figure out what
3363 // bswap to make it into.
3364 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003365 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003366 if (I.getType() == Type::UShortTy)
3367 FnName = "llvm.bswap.i16";
3368 else if (I.getType() == Type::UIntTy)
3369 FnName = "llvm.bswap.i32";
3370 else if (I.getType() == Type::ULongTy)
3371 FnName = "llvm.bswap.i64";
3372 else
3373 assert(0 && "Unknown integer type!");
3374 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3375
3376 return new CallInst(F, V);
3377}
3378
3379
Chris Lattner113f4f42002-06-25 16:13:24 +00003380Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003381 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003383
Chris Lattner81a7a232004-10-16 18:11:37 +00003384 if (isa<UndefValue>(Op1))
3385 return ReplaceInstUsesWith(I, // X | undef -> -1
3386 ConstantIntegral::getAllOnesValue(I.getType()));
3387
Chris Lattner5b2edb12006-02-12 08:02:11 +00003388 // or X, X = X
3389 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003390 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003391
Chris Lattner5b2edb12006-02-12 08:02:11 +00003392 // See if we can simplify any instructions used by the instruction whose sole
3393 // purpose is to compute bits we don't care about.
3394 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003395 if (!isa<PackedType>(I.getType()) &&
3396 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003397 KnownZero, KnownOne))
3398 return &I;
3399
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003400 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003401 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003402 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003403 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3404 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003405 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3406 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003407 InsertNewInstBefore(Or, I);
3408 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3409 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003410
Chris Lattnerd4252a72004-07-30 07:50:03 +00003411 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3412 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3413 std::string Op0Name = Op0->getName(); Op0->setName("");
3414 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3415 InsertNewInstBefore(Or, I);
3416 return BinaryOperator::createXor(Or,
3417 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003418 }
Chris Lattner183b3362004-04-09 19:05:30 +00003419
3420 // Try to fold constant and into select arguments.
3421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003423 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003424 if (isa<PHINode>(Op0))
3425 if (Instruction *NV = FoldOpIntoPhi(I))
3426 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003427 }
3428
Chris Lattner330628a2006-01-06 17:59:59 +00003429 Value *A = 0, *B = 0;
3430 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003431
3432 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3433 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3434 return ReplaceInstUsesWith(I, Op1);
3435 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3436 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3437 return ReplaceInstUsesWith(I, Op0);
3438
Chris Lattnerb7845d62006-07-10 20:25:24 +00003439 // (A | B) | C and A | (B | C) -> bswap if possible.
3440 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003441 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003442 match(Op1, m_Or(m_Value(), m_Value())) ||
3443 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3444 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003445 if (Instruction *BSwap = MatchBSwap(I))
3446 return BSwap;
3447 }
3448
Chris Lattnerb62f5082005-05-09 04:58:36 +00003449 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3450 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003451 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003452 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3453 Op0->setName("");
3454 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3455 }
3456
3457 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3458 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003459 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003460 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3461 Op0->setName("");
3462 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3463 }
3464
Chris Lattner15212982005-09-18 03:42:07 +00003465 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003466 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003467 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3468
3469 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3470 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3471
3472
Chris Lattner01f56c62005-09-18 06:02:59 +00003473 // If we have: ((V + N) & C1) | (V & C2)
3474 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3475 // replace with V+N.
3476 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003477 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003478 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003479 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3480 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003481 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003482 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003483 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003484 return ReplaceInstUsesWith(I, A);
3485 }
3486 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003487 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003488 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3489 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003490 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003491 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003492 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003493 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003494 }
3495 }
3496 }
Chris Lattner812aab72003-08-12 19:11:07 +00003497
Chris Lattnerd4252a72004-07-30 07:50:03 +00003498 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3499 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003500 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003501 ConstantIntegral::getAllOnesValue(I.getType()));
3502 } else {
3503 A = 0;
3504 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003505 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003506 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3507 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003508 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003509 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003510
Misha Brukman9c003d82004-07-30 12:50:08 +00003511 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003512 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3513 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3514 I.getName()+".demorgan"), I);
3515 return BinaryOperator::createNot(And);
3516 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003517 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003518
Chris Lattner3ac7c262003-08-13 20:16:26 +00003519 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003520 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003521 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3522 return R;
3523
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003524 Value *LHSVal, *RHSVal;
3525 ConstantInt *LHSCst, *RHSCst;
3526 Instruction::BinaryOps LHSCC, RHSCC;
3527 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3528 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3529 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3530 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003531 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003532 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3533 // Ensure that the larger constant is on the RHS.
3534 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3535 SetCondInst *LHS = cast<SetCondInst>(Op0);
3536 if (cast<ConstantBool>(Cmp)->getValue()) {
3537 std::swap(LHS, RHS);
3538 std::swap(LHSCst, RHSCst);
3539 std::swap(LHSCC, RHSCC);
3540 }
3541
3542 // At this point, we know we have have two setcc instructions
3543 // comparing a value against two constants and or'ing the result
3544 // together. Because of the above check, we know that we only have
3545 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3546 // FoldSetCCLogical check above), that the two constants are not
3547 // equal.
3548 assert(LHSCst != RHSCst && "Compares not folded above?");
3549
3550 switch (LHSCC) {
3551 default: assert(0 && "Unknown integer condition code!");
3552 case Instruction::SetEQ:
3553 switch (RHSCC) {
3554 default: assert(0 && "Unknown integer condition code!");
3555 case Instruction::SetEQ:
3556 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3557 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3558 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3559 LHSVal->getName()+".off");
3560 InsertNewInstBefore(Add, I);
3561 const Type *UnsType = Add->getType()->getUnsignedVersion();
3562 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3563 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3564 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3565 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3566 }
3567 break; // (X == 13 | X == 15) -> no change
3568
Chris Lattner5c219462005-04-19 06:04:18 +00003569 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3570 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003571 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3572 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3573 return ReplaceInstUsesWith(I, RHS);
3574 }
3575 break;
3576 case Instruction::SetNE:
3577 switch (RHSCC) {
3578 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003579 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3580 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3581 return ReplaceInstUsesWith(I, LHS);
3582 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003583 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003584 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003585 }
3586 break;
3587 case Instruction::SetLT:
3588 switch (RHSCC) {
3589 default: assert(0 && "Unknown integer condition code!");
3590 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3591 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003592 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3593 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003594 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3595 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3596 return ReplaceInstUsesWith(I, RHS);
3597 }
3598 break;
3599 case Instruction::SetGT:
3600 switch (RHSCC) {
3601 default: assert(0 && "Unknown integer condition code!");
3602 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3603 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3604 return ReplaceInstUsesWith(I, LHS);
3605 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3606 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003607 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003608 }
3609 }
3610 }
3611 }
Chris Lattner3af10532006-05-05 06:39:07 +00003612
3613 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3614 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003615 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003616 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003617 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003618 // Only do this if the casts both really cause code to be generated.
3619 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3620 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003621 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3622 Op1C->getOperand(0),
3623 I.getName());
3624 InsertNewInstBefore(NewOp, I);
3625 return new CastInst(NewOp, I.getType());
3626 }
3627 }
3628
Chris Lattner15212982005-09-18 03:42:07 +00003629
Chris Lattner113f4f42002-06-25 16:13:24 +00003630 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003631}
3632
Chris Lattnerc2076352004-02-16 01:20:27 +00003633// XorSelf - Implements: X ^ X --> 0
3634struct XorSelf {
3635 Value *RHS;
3636 XorSelf(Value *rhs) : RHS(rhs) {}
3637 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3638 Instruction *apply(BinaryOperator &Xor) const {
3639 return &Xor;
3640 }
3641};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003642
3643
Chris Lattner113f4f42002-06-25 16:13:24 +00003644Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003645 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003646 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003647
Chris Lattner81a7a232004-10-16 18:11:37 +00003648 if (isa<UndefValue>(Op1))
3649 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3650
Chris Lattnerc2076352004-02-16 01:20:27 +00003651 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3652 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3653 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003655 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003656
3657 // See if we can simplify any instructions used by the instruction whose sole
3658 // purpose is to compute bits we don't care about.
3659 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003660 if (!isa<PackedType>(I.getType()) &&
3661 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003662 KnownZero, KnownOne))
3663 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003664
Chris Lattner97638592003-07-23 21:37:07 +00003665 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003666 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003667 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003668 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003669 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003670 return new SetCondInst(SCI->getInverseCondition(),
3671 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003672
Chris Lattner8f2f5982003-11-05 01:06:05 +00003673 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003674 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3675 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003676 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3677 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003678 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003679 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003680 }
Chris Lattner023a4832004-06-18 06:07:51 +00003681
3682 // ~(~X & Y) --> (X | ~Y)
3683 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3684 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3685 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3686 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003687 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003688 Op0I->getOperand(1)->getName()+".not");
3689 InsertNewInstBefore(NotY, I);
3690 return BinaryOperator::createOr(Op0NotVal, NotY);
3691 }
3692 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003693
Chris Lattner97638592003-07-23 21:37:07 +00003694 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003695 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003696 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003697 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003698 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3699 return BinaryOperator::createSub(
3700 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003701 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003702 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003703 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003704 } else if (Op0I->getOpcode() == Instruction::Or) {
3705 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3706 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3707 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3708 // Anything in both C1 and C2 is known to be zero, remove it from
3709 // NewRHS.
3710 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3711 NewRHS = ConstantExpr::getAnd(NewRHS,
3712 ConstantExpr::getNot(CommonBits));
3713 WorkList.push_back(Op0I);
3714 I.setOperand(0, Op0I->getOperand(0));
3715 I.setOperand(1, NewRHS);
3716 return &I;
3717 }
Chris Lattner97638592003-07-23 21:37:07 +00003718 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003719 }
Chris Lattner183b3362004-04-09 19:05:30 +00003720
3721 // Try to fold constant and into select arguments.
3722 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003723 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003724 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003725 if (isa<PHINode>(Op0))
3726 if (Instruction *NV = FoldOpIntoPhi(I))
3727 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003728 }
3729
Chris Lattnerbb74e222003-03-10 23:06:50 +00003730 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003731 if (X == Op1)
3732 return ReplaceInstUsesWith(I,
3733 ConstantIntegral::getAllOnesValue(I.getType()));
3734
Chris Lattnerbb74e222003-03-10 23:06:50 +00003735 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003736 if (X == Op0)
3737 return ReplaceInstUsesWith(I,
3738 ConstantIntegral::getAllOnesValue(I.getType()));
3739
Chris Lattnerdcd07922006-04-01 08:03:55 +00003740 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003741 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003742 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003743 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003744 I.swapOperands();
3745 std::swap(Op0, Op1);
3746 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003747 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003748 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003749 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003750 } else if (Op1I->getOpcode() == Instruction::Xor) {
3751 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3752 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3753 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3754 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003755 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3756 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3757 Op1I->swapOperands();
3758 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3759 I.swapOperands(); // Simplified below.
3760 std::swap(Op0, Op1);
3761 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003762 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003763
Chris Lattnerdcd07922006-04-01 08:03:55 +00003764 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003765 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003766 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003767 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003768 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003769 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3770 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003771 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003772 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003773 } else if (Op0I->getOpcode() == Instruction::Xor) {
3774 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3775 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3776 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3777 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003778 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3779 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3780 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003781 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3782 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003783 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3784 InsertNewInstBefore(N, I);
3785 return BinaryOperator::createAnd(N, Op1);
3786 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003787 }
3788
Chris Lattner3ac7c262003-08-13 20:16:26 +00003789 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3790 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3791 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3792 return R;
3793
Chris Lattner3af10532006-05-05 06:39:07 +00003794 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3795 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003796 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003797 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003798 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003799 // Only do this if the casts both really cause code to be generated.
3800 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3801 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003802 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3803 Op1C->getOperand(0),
3804 I.getName());
3805 InsertNewInstBefore(NewOp, I);
3806 return new CastInst(NewOp, I.getType());
3807 }
3808 }
3809
Chris Lattner113f4f42002-06-25 16:13:24 +00003810 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003811}
3812
Chris Lattner6862fbd2004-09-29 17:40:11 +00003813static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003814 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003815}
3816
3817/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3818/// overflowed for this type.
3819static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3820 ConstantInt *In2) {
3821 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3822
3823 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003824 return cast<ConstantInt>(Result)->getZExtValue() <
3825 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003826 if (isPositive(In1) != isPositive(In2))
3827 return false;
3828 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003829 return cast<ConstantInt>(Result)->getSExtValue() <
3830 cast<ConstantInt>(In1)->getSExtValue();
3831 return cast<ConstantInt>(Result)->getSExtValue() >
3832 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003833}
3834
Chris Lattner0798af32005-01-13 20:14:25 +00003835/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3836/// code necessary to compute the offset from the base pointer (without adding
3837/// in the base pointer). Return the result as a signed integer of intptr size.
3838static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3839 TargetData &TD = IC.getTargetData();
3840 gep_type_iterator GTI = gep_type_begin(GEP);
3841 const Type *UIntPtrTy = TD.getIntPtrType();
3842 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3843 Value *Result = Constant::getNullValue(SIntPtrTy);
3844
3845 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003846 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003847
Chris Lattner0798af32005-01-13 20:14:25 +00003848 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3849 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003850 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003851 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003852 SIntPtrTy);
3853 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3854 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003855 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003856 Scale = ConstantExpr::getMul(OpC, Scale);
3857 if (Constant *RC = dyn_cast<Constant>(Result))
3858 Result = ConstantExpr::getAdd(RC, Scale);
3859 else {
3860 // Emit an add instruction.
3861 Result = IC.InsertNewInstBefore(
3862 BinaryOperator::createAdd(Result, Scale,
3863 GEP->getName()+".offs"), I);
3864 }
3865 }
3866 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003867 // Convert to correct type.
3868 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3869 Op->getName()+".c"), I);
3870 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003871 // We'll let instcombine(mul) convert this to a shl if possible.
3872 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3873 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003874
3875 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003876 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003877 GEP->getName()+".offs"), I);
3878 }
3879 }
3880 return Result;
3881}
3882
3883/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3884/// else. At this point we know that the GEP is on the LHS of the comparison.
3885Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3886 Instruction::BinaryOps Cond,
3887 Instruction &I) {
3888 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003889
3890 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3891 if (isa<PointerType>(CI->getOperand(0)->getType()))
3892 RHS = CI->getOperand(0);
3893
Chris Lattner0798af32005-01-13 20:14:25 +00003894 Value *PtrBase = GEPLHS->getOperand(0);
3895 if (PtrBase == RHS) {
3896 // As an optimization, we don't actually have to compute the actual value of
3897 // OFFSET if this is a seteq or setne comparison, just return whether each
3898 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003899 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3900 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003901 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3902 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003903 bool EmitIt = true;
3904 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3905 if (isa<UndefValue>(C)) // undef index -> undef.
3906 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3907 if (C->isNullValue())
3908 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003909 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3910 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003911 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003912 return ReplaceInstUsesWith(I, // No comparison is needed here.
3913 ConstantBool::get(Cond == Instruction::SetNE));
3914 }
3915
3916 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003917 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003918 new SetCondInst(Cond, GEPLHS->getOperand(i),
3919 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3920 if (InVal == 0)
3921 InVal = Comp;
3922 else {
3923 InVal = InsertNewInstBefore(InVal, I);
3924 InsertNewInstBefore(Comp, I);
3925 if (Cond == Instruction::SetNE) // True if any are unequal
3926 InVal = BinaryOperator::createOr(InVal, Comp);
3927 else // True if all are equal
3928 InVal = BinaryOperator::createAnd(InVal, Comp);
3929 }
3930 }
3931 }
3932
3933 if (InVal)
3934 return InVal;
3935 else
3936 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3937 ConstantBool::get(Cond == Instruction::SetEQ));
3938 }
Chris Lattner0798af32005-01-13 20:14:25 +00003939
3940 // Only lower this if the setcc is the only user of the GEP or if we expect
3941 // the result to fold to a constant!
3942 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3943 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3944 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3945 return new SetCondInst(Cond, Offset,
3946 Constant::getNullValue(Offset->getType()));
3947 }
3948 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003949 // If the base pointers are different, but the indices are the same, just
3950 // compare the base pointer.
3951 if (PtrBase != GEPRHS->getOperand(0)) {
3952 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003953 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003954 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003955 if (IndicesTheSame)
3956 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3957 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3958 IndicesTheSame = false;
3959 break;
3960 }
3961
3962 // If all indices are the same, just compare the base pointers.
3963 if (IndicesTheSame)
3964 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3965 GEPRHS->getOperand(0));
3966
3967 // Otherwise, the base pointers are different and the indices are
3968 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003969 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003970 }
Chris Lattner0798af32005-01-13 20:14:25 +00003971
Chris Lattner81e84172005-01-13 22:25:21 +00003972 // If one of the GEPs has all zero indices, recurse.
3973 bool AllZeros = true;
3974 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3975 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3976 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3977 AllZeros = false;
3978 break;
3979 }
3980 if (AllZeros)
3981 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3982 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003983
3984 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003985 AllZeros = true;
3986 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3987 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3988 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3989 AllZeros = false;
3990 break;
3991 }
3992 if (AllZeros)
3993 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3994
Chris Lattner4fa89822005-01-14 00:20:05 +00003995 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3996 // If the GEPs only differ by one index, compare it.
3997 unsigned NumDifferences = 0; // Keep track of # differences.
3998 unsigned DiffOperand = 0; // The operand that differs.
3999 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4000 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004001 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4002 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004003 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004004 NumDifferences = 2;
4005 break;
4006 } else {
4007 if (NumDifferences++) break;
4008 DiffOperand = i;
4009 }
4010 }
4011
4012 if (NumDifferences == 0) // SAME GEP?
4013 return ReplaceInstUsesWith(I, // No comparison is needed here.
4014 ConstantBool::get(Cond == Instruction::SetEQ));
4015 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004016 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4017 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004018
4019 // Convert the operands to signed values to make sure to perform a
4020 // signed comparison.
4021 const Type *NewTy = LHSV->getType()->getSignedVersion();
4022 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004023 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004024 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004025 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004026 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004027 }
4028 }
4029
Chris Lattner0798af32005-01-13 20:14:25 +00004030 // Only lower this if the setcc is the only user of the GEP or if we expect
4031 // the result to fold to a constant!
4032 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4033 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4034 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4035 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4036 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4037 return new SetCondInst(Cond, L, R);
4038 }
4039 }
4040 return 0;
4041}
4042
4043
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004044Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004045 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004046 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4047 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004048
4049 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004050 if (Op0 == Op1)
4051 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004052
Chris Lattner81a7a232004-10-16 18:11:37 +00004053 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4054 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4055
Chris Lattner15ff1e12004-11-14 07:33:16 +00004056 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4057 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004058 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4059 isa<ConstantPointerNull>(Op0)) &&
4060 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004061 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004062 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4063
4064 // setcc's with boolean values can always be turned into bitwise operations
4065 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004066 switch (I.getOpcode()) {
4067 default: assert(0 && "Invalid setcc instruction!");
4068 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004069 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004070 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004071 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004072 }
Chris Lattner4456da62004-08-11 00:50:51 +00004073 case Instruction::SetNE:
4074 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004075
Chris Lattner4456da62004-08-11 00:50:51 +00004076 case Instruction::SetGT:
4077 std::swap(Op0, Op1); // Change setgt -> setlt
4078 // FALL THROUGH
4079 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4080 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4081 InsertNewInstBefore(Not, I);
4082 return BinaryOperator::createAnd(Not, Op1);
4083 }
4084 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004085 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004086 // FALL THROUGH
4087 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4088 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4089 InsertNewInstBefore(Not, I);
4090 return BinaryOperator::createOr(Not, Op1);
4091 }
4092 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004093 }
4094
Chris Lattner2dd01742004-06-09 04:24:29 +00004095 // See if we are doing a comparison between a constant and an instruction that
4096 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004097 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004098 // Check to see if we are comparing against the minimum or maximum value...
4099 if (CI->isMinValue()) {
4100 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004101 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004102 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004103 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004104 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4105 return BinaryOperator::createSetEQ(Op0, Op1);
4106 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4107 return BinaryOperator::createSetNE(Op0, Op1);
4108
4109 } else if (CI->isMaxValue()) {
4110 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004111 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004112 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004113 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004114 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4115 return BinaryOperator::createSetEQ(Op0, Op1);
4116 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4117 return BinaryOperator::createSetNE(Op0, Op1);
4118
4119 // Comparing against a value really close to min or max?
4120 } else if (isMinValuePlusOne(CI)) {
4121 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4122 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4123 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4124 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4125
4126 } else if (isMaxValueMinusOne(CI)) {
4127 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4128 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4129 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4130 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4131 }
4132
4133 // If we still have a setle or setge instruction, turn it into the
4134 // appropriate setlt or setgt instruction. Since the border cases have
4135 // already been handled above, this requires little checking.
4136 //
4137 if (I.getOpcode() == Instruction::SetLE)
4138 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4139 if (I.getOpcode() == Instruction::SetGE)
4140 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4141
Chris Lattneree0f2802006-02-12 02:07:56 +00004142
4143 // See if we can fold the comparison based on bits known to be zero or one
4144 // in the input.
4145 uint64_t KnownZero, KnownOne;
4146 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4147 KnownZero, KnownOne, 0))
4148 return &I;
4149
4150 // Given the known and unknown bits, compute a range that the LHS could be
4151 // in.
4152 if (KnownOne | KnownZero) {
4153 if (Ty->isUnsigned()) { // Unsigned comparison.
4154 uint64_t Min, Max;
4155 uint64_t RHSVal = CI->getZExtValue();
4156 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4157 Min, Max);
4158 switch (I.getOpcode()) { // LE/GE have been folded already.
4159 default: assert(0 && "Unknown setcc opcode!");
4160 case Instruction::SetEQ:
4161 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004162 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004163 break;
4164 case Instruction::SetNE:
4165 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004166 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004167 break;
4168 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004169 if (Max < RHSVal)
4170 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4171 if (Min > RHSVal)
4172 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004173 break;
4174 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004175 if (Min > RHSVal)
4176 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4177 if (Max < RHSVal)
4178 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004179 break;
4180 }
4181 } else { // Signed comparison.
4182 int64_t Min, Max;
4183 int64_t RHSVal = CI->getSExtValue();
4184 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4185 Min, Max);
4186 switch (I.getOpcode()) { // LE/GE have been folded already.
4187 default: assert(0 && "Unknown setcc opcode!");
4188 case Instruction::SetEQ:
4189 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004190 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004191 break;
4192 case Instruction::SetNE:
4193 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004194 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004195 break;
4196 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004197 if (Max < RHSVal)
4198 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4199 if (Min > RHSVal)
4200 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004201 break;
4202 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004203 if (Min > RHSVal)
4204 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4205 if (Max < RHSVal)
4206 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004207 break;
4208 }
4209 }
4210 }
4211
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004212 // Since the RHS is a constantInt (CI), if the left hand side is an
4213 // instruction, see if that instruction also has constants so that the
4214 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004215 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004216 switch (LHSI->getOpcode()) {
4217 case Instruction::And:
4218 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4219 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004220 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4221
4222 // If an operand is an AND of a truncating cast, we can widen the
4223 // and/compare to be the input width without changing the value
4224 // produced, eliminating a cast.
4225 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4226 // We can do this transformation if either the AND constant does not
4227 // have its sign bit set or if it is an equality comparison.
4228 // Extending a relational comparison when we're checking the sign
4229 // bit would not work.
4230 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4231 (I.isEquality() ||
4232 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4233 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4234 ConstantInt *NewCST;
4235 ConstantInt *NewCI;
4236 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004237 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004238 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004239 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004240 CI->getZExtValue());
4241 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004242 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004243 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004244 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004245 CI->getZExtValue());
4246 }
4247 Instruction *NewAnd =
4248 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4249 LHSI->getName());
4250 InsertNewInstBefore(NewAnd, I);
4251 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4252 }
4253 }
4254
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004255 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4256 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4257 // happens a LOT in code produced by the C front-end, for bitfield
4258 // access.
4259 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004260
4261 // Check to see if there is a noop-cast between the shift and the and.
4262 if (!Shift) {
4263 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4264 if (CI->getOperand(0)->getType()->isIntegral() &&
4265 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4266 CI->getType()->getPrimitiveSizeInBits())
4267 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4268 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004269
Reid Spencere0fc4df2006-10-20 07:07:24 +00004270 ConstantInt *ShAmt;
4271 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004272 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4273 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004274
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004275 // We can fold this as long as we can't shift unknown bits
4276 // into the mask. This can only happen with signed shift
4277 // rights, as they sign-extend.
4278 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004279 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004280 if (!CanFold) {
4281 // To test for the bad case of the signed shr, see if any
4282 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004283 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004284 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4285
Reid Spencere0fc4df2006-10-20 07:07:24 +00004286 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004287 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004288 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4289 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004290 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4291 CanFold = true;
4292 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004293
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004294 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004295 Constant *NewCst;
4296 if (Shift->getOpcode() == Instruction::Shl)
4297 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4298 else
4299 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004300
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004301 // Check to see if we are shifting out any of the bits being
4302 // compared.
4303 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4304 // If we shifted bits out, the fold is not going to work out.
4305 // As a special case, check to see if this means that the
4306 // result is always true or false now.
4307 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004308 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004309 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004310 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004311 } else {
4312 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004313 Constant *NewAndCST;
4314 if (Shift->getOpcode() == Instruction::Shl)
4315 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4316 else
4317 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4318 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004319 if (AndTy == Ty)
4320 LHSI->setOperand(0, Shift->getOperand(0));
4321 else {
4322 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4323 *Shift);
4324 LHSI->setOperand(0, NewCast);
4325 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004326 WorkList.push_back(Shift); // Shift is dead.
4327 AddUsesToWorkList(I);
4328 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004329 }
4330 }
Chris Lattner35167c32004-06-09 07:59:58 +00004331 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004332
4333 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4334 // preferable because it allows the C<<Y expression to be hoisted out
4335 // of a loop if Y is invariant and X is not.
4336 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004337 I.isEquality() && !Shift->isArithmeticShift() &&
4338 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004339 // Compute C << Y.
4340 Value *NS;
4341 if (Shift->getOpcode() == Instruction::Shr) {
4342 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4343 "tmp");
4344 } else {
4345 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004346 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004347 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004348 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004349 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004350 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4351 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004352 }
4353 InsertNewInstBefore(cast<Instruction>(NS), I);
4354
4355 // If C's sign doesn't agree with the and, insert a cast now.
4356 if (NS->getType() != LHSI->getType())
4357 NS = InsertCastBefore(NS, LHSI->getType(), I);
4358
4359 Value *ShiftOp = Shift->getOperand(0);
4360 if (ShiftOp->getType() != LHSI->getType())
4361 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4362
4363 // Compute X & (C << Y).
4364 Instruction *NewAnd =
4365 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4366 InsertNewInstBefore(NewAnd, I);
4367
4368 I.setOperand(0, NewAnd);
4369 return &I;
4370 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004371 }
4372 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004373
Chris Lattner272d5ca2004-09-28 18:22:15 +00004374 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004375 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004376 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004377 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4378
4379 // Check that the shift amount is in range. If not, don't perform
4380 // undefined shifts. When the shift is visited it will be
4381 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004382 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004383 break;
4384
Chris Lattner272d5ca2004-09-28 18:22:15 +00004385 // If we are comparing against bits always shifted out, the
4386 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004387 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004388 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4389 if (Comp != CI) {// Comparing against a bit that we know is zero.
4390 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4391 Constant *Cst = ConstantBool::get(IsSetNE);
4392 return ReplaceInstUsesWith(I, Cst);
4393 }
4394
4395 if (LHSI->hasOneUse()) {
4396 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004397 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004398 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4399
4400 Constant *Mask;
4401 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004402 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004403 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004404 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004405 } else {
4406 Mask = ConstantInt::getAllOnesValue(CI->getType());
4407 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004408
Chris Lattner272d5ca2004-09-28 18:22:15 +00004409 Instruction *AndI =
4410 BinaryOperator::createAnd(LHSI->getOperand(0),
4411 Mask, LHSI->getName()+".mask");
4412 Value *And = InsertNewInstBefore(AndI, I);
4413 return new SetCondInst(I.getOpcode(), And,
4414 ConstantExpr::getUShr(CI, ShAmt));
4415 }
4416 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004417 }
4418 break;
4419
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004420 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004421 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004422 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004423 // Check that the shift amount is in range. If not, don't perform
4424 // undefined shifts. When the shift is visited it will be
4425 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004426 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004427 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004428 break;
4429
Chris Lattner1023b872004-09-27 16:18:50 +00004430 // If we are comparing against bits always shifted out, the
4431 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004432 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004433 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004434
Chris Lattner1023b872004-09-27 16:18:50 +00004435 if (Comp != CI) {// Comparing against a bit that we know is zero.
4436 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4437 Constant *Cst = ConstantBool::get(IsSetNE);
4438 return ReplaceInstUsesWith(I, Cst);
4439 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004440
Chris Lattner1023b872004-09-27 16:18:50 +00004441 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004442 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004443
Chris Lattner1023b872004-09-27 16:18:50 +00004444 // Otherwise strength reduce the shift into an and.
4445 uint64_t Val = ~0ULL; // All ones.
4446 Val <<= ShAmtVal; // Shift over to the right spot.
4447
4448 Constant *Mask;
4449 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004450 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004451 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004452 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004453 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004454 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004455
Chris Lattner1023b872004-09-27 16:18:50 +00004456 Instruction *AndI =
4457 BinaryOperator::createAnd(LHSI->getOperand(0),
4458 Mask, LHSI->getName()+".mask");
4459 Value *And = InsertNewInstBefore(AndI, I);
4460 return new SetCondInst(I.getOpcode(), And,
4461 ConstantExpr::getShl(CI, ShAmt));
4462 }
Chris Lattner1023b872004-09-27 16:18:50 +00004463 }
4464 }
4465 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004466
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004467 case Instruction::SDiv:
4468 case Instruction::UDiv:
4469 // Fold: setcc ([us]div X, C1), C2 -> range test
4470 // Fold this div into the comparison, producing a range check.
4471 // Determine, based on the divide type, what the range is being
4472 // checked. If there is an overflow on the low or high side, remember
4473 // it, otherwise compute the range [low, hi) bounding the new value.
4474 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004475 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004476 // FIXME: If the operand types don't match the type of the divide
4477 // then don't attempt this transform. The code below doesn't have the
4478 // logic to deal with a signed divide and an unsigned compare (and
4479 // vice versa). This is because (x /s C1) <s C2 produces different
4480 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4481 // (x /u C1) <u C2. Simply casting the operands and result won't
4482 // work. :( The if statement below tests that condition and bails
4483 // if it finds it.
4484 const Type* DivRHSTy = DivRHS->getType();
4485 unsigned DivOpCode = LHSI->getOpcode();
4486 if (I.isEquality() &&
4487 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4488 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4489 break;
4490
4491 // Initialize the variables that will indicate the nature of the
4492 // range check.
4493 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004494 ConstantInt *LoBound = 0, *HiBound = 0;
4495
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004496 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4497 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4498 // C2 (CI). By solving for X we can turn this into a range check
4499 // instead of computing a divide.
4500 ConstantInt *Prod =
4501 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004502
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004503 // Determine if the product overflows by seeing if the product is
4504 // not equal to the divide. Make sure we do the same kind of divide
4505 // as in the LHS instruction that we're folding.
4506 bool ProdOV = !DivRHS->isNullValue() &&
4507 (DivOpCode == Instruction::SDiv ?
4508 ConstantExpr::getSDiv(Prod, DivRHS) :
4509 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4510
4511 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004512 Instruction::BinaryOps Opcode = I.getOpcode();
4513
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004514 if (DivRHS->isNullValue()) {
4515 // Don't hack on divide by zeros!
4516 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004517 LoBound = Prod;
4518 LoOverflow = ProdOV;
4519 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004520 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004521 if (CI->isNullValue()) { // (X / pos) op 0
4522 // Can't overflow.
4523 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4524 HiBound = DivRHS;
4525 } else if (isPositive(CI)) { // (X / pos) op pos
4526 LoBound = Prod;
4527 LoOverflow = ProdOV;
4528 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4529 } else { // (X / pos) op neg
4530 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4531 LoOverflow = AddWithOverflow(LoBound, Prod,
4532 cast<ConstantInt>(DivRHSH));
4533 HiBound = Prod;
4534 HiOverflow = ProdOV;
4535 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004536 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004537 if (CI->isNullValue()) { // (X / neg) op 0
4538 LoBound = AddOne(DivRHS);
4539 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004540 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004541 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004542 } else if (isPositive(CI)) { // (X / neg) op pos
4543 HiOverflow = LoOverflow = ProdOV;
4544 if (!LoOverflow)
4545 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4546 HiBound = AddOne(Prod);
4547 } else { // (X / neg) op neg
4548 LoBound = Prod;
4549 LoOverflow = HiOverflow = ProdOV;
4550 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4551 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004552
Chris Lattnera92af962004-10-11 19:40:04 +00004553 // Dividing by a negate swaps the condition.
4554 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004555 }
4556
4557 if (LoBound) {
4558 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004559 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004560 default: assert(0 && "Unhandled setcc opcode!");
4561 case Instruction::SetEQ:
4562 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004563 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004564 else if (HiOverflow)
4565 return new SetCondInst(Instruction::SetGE, X, LoBound);
4566 else if (LoOverflow)
4567 return new SetCondInst(Instruction::SetLT, X, HiBound);
4568 else
4569 return InsertRangeTest(X, LoBound, HiBound, true, I);
4570 case Instruction::SetNE:
4571 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004572 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004573 else if (HiOverflow)
4574 return new SetCondInst(Instruction::SetLT, X, LoBound);
4575 else if (LoOverflow)
4576 return new SetCondInst(Instruction::SetGE, X, HiBound);
4577 else
4578 return InsertRangeTest(X, LoBound, HiBound, false, I);
4579 case Instruction::SetLT:
4580 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004581 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004582 return new SetCondInst(Instruction::SetLT, X, LoBound);
4583 case Instruction::SetGT:
4584 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004585 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004586 return new SetCondInst(Instruction::SetGE, X, HiBound);
4587 }
4588 }
4589 }
4590 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004591 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004592
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004593 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004594 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004595 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4596
Reid Spencere0fc4df2006-10-20 07:07:24 +00004597 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4598 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004599 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4600 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004601 case Instruction::SRem:
4602 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4603 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4604 BO->hasOneUse()) {
4605 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4606 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004607 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4608 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004609 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004610 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004611 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004612 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004613 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004614 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004615 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4616 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004617 if (BO->hasOneUse())
4618 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4619 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004620 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004621 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4622 // efficiently invertible, or if the add has just this one use.
4623 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004624
Chris Lattnerc992add2003-08-13 05:33:12 +00004625 if (Value *NegVal = dyn_castNegVal(BOp1))
4626 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4627 else if (Value *NegVal = dyn_castNegVal(BOp0))
4628 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004629 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004630 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4631 BO->setName("");
4632 InsertNewInstBefore(Neg, I);
4633 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4634 }
4635 }
4636 break;
4637 case Instruction::Xor:
4638 // For the xor case, we can xor two constants together, eliminating
4639 // the explicit xor.
4640 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4641 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004642 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004643
4644 // FALLTHROUGH
4645 case Instruction::Sub:
4646 // Replace (([sub|xor] A, B) != 0) with (A != B)
4647 if (CI->isNullValue())
4648 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4649 BO->getOperand(1));
4650 break;
4651
4652 case Instruction::Or:
4653 // If bits are being or'd in that are not present in the constant we
4654 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004655 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004656 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004657 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004658 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004659 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004660 break;
4661
4662 case Instruction::And:
4663 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004664 // If bits are being compared against that are and'd out, then the
4665 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004666 if (!ConstantExpr::getAnd(CI,
4667 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004668 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004669
Chris Lattner35167c32004-06-09 07:59:58 +00004670 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004671 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004672 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4673 Instruction::SetNE, Op0,
4674 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004675
Chris Lattnerc992add2003-08-13 05:33:12 +00004676 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4677 // to be a signed value as appropriate.
4678 if (isSignBit(BOC)) {
4679 Value *X = BO->getOperand(0);
4680 // If 'X' is not signed, insert a cast now...
4681 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004682 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004683 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004684 }
4685 return new SetCondInst(isSetNE ? Instruction::SetLT :
4686 Instruction::SetGE, X,
4687 Constant::getNullValue(X->getType()));
4688 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004689
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004690 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004691 if (CI->isNullValue() && isHighOnes(BOC)) {
4692 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004693 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004694
4695 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004696 if (NegX->getType()->isSigned()) {
4697 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4698 X = InsertCastBefore(X, DestTy, I);
4699 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004700 }
4701
4702 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004703 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004704 }
4705
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004706 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004707 default: break;
4708 }
4709 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004710 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004711 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004712 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4713 Value *CastOp = Cast->getOperand(0);
4714 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004715 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004716 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004717 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004718 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004719 "Source and destination signednesses should differ!");
4720 if (Cast->getType()->isSigned()) {
4721 // If this is a signed comparison, check for comparisons in the
4722 // vicinity of zero.
4723 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4724 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004725 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004726 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004727 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004728 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004729 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004730 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004731 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004732 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004733 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004734 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004735 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004736 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004737 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004738 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004739 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004740 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004741 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004742 return BinaryOperator::createSetLT(CastOp,
4743 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004744 }
4745 }
4746 }
Chris Lattnere967b342003-06-04 05:10:11 +00004747 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004748 }
4749
Chris Lattner77c32c32005-04-23 15:31:55 +00004750 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4751 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4752 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4753 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004754 case Instruction::GetElementPtr:
4755 if (RHSC->isNullValue()) {
4756 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4757 bool isAllZeros = true;
4758 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4759 if (!isa<Constant>(LHSI->getOperand(i)) ||
4760 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4761 isAllZeros = false;
4762 break;
4763 }
4764 if (isAllZeros)
4765 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4766 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4767 }
4768 break;
4769
Chris Lattner77c32c32005-04-23 15:31:55 +00004770 case Instruction::PHI:
4771 if (Instruction *NV = FoldOpIntoPhi(I))
4772 return NV;
4773 break;
4774 case Instruction::Select:
4775 // If either operand of the select is a constant, we can fold the
4776 // comparison into the select arms, which will cause one to be
4777 // constant folded and the select turned into a bitwise or.
4778 Value *Op1 = 0, *Op2 = 0;
4779 if (LHSI->hasOneUse()) {
4780 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4781 // Fold the known value into the constant operand.
4782 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4783 // Insert a new SetCC of the other select operand.
4784 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4785 LHSI->getOperand(2), RHSC,
4786 I.getName()), I);
4787 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4788 // Fold the known value into the constant operand.
4789 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4790 // Insert a new SetCC of the other select operand.
4791 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4792 LHSI->getOperand(1), RHSC,
4793 I.getName()), I);
4794 }
4795 }
Jeff Cohen82639852005-04-23 21:38:35 +00004796
Chris Lattner77c32c32005-04-23 15:31:55 +00004797 if (Op1)
4798 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4799 break;
4800 }
4801 }
4802
Chris Lattner0798af32005-01-13 20:14:25 +00004803 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4804 if (User *GEP = dyn_castGetElementPtr(Op0))
4805 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4806 return NI;
4807 if (User *GEP = dyn_castGetElementPtr(Op1))
4808 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4809 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4810 return NI;
4811
Chris Lattner16930792003-11-03 04:25:02 +00004812 // Test to see if the operands of the setcc are casted versions of other
4813 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004814 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4815 Value *CastOp0 = CI->getOperand(0);
4816 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004817 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004818 // We keep moving the cast from the left operand over to the right
4819 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004820 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004821
Chris Lattner16930792003-11-03 04:25:02 +00004822 // If operand #1 is a cast instruction, see if we can eliminate it as
4823 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004824 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4825 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004826 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004827 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004828
Chris Lattner16930792003-11-03 04:25:02 +00004829 // If Op1 is a constant, we can fold the cast into the constant.
4830 if (Op1->getType() != Op0->getType())
4831 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4832 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4833 } else {
4834 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004835 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004836 }
4837 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4838 }
4839
Chris Lattner6444c372003-11-03 05:17:03 +00004840 // Handle the special case of: setcc (cast bool to X), <cst>
4841 // This comes up when you have code like
4842 // int X = A < B;
4843 // if (X) ...
4844 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004845 // with a constant or another cast from the same type.
4846 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4847 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4848 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004849 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004850
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004851 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004852 Value *A, *B;
4853 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4854 (A == Op1 || B == Op1)) {
4855 // (A^B) == A -> B == 0
4856 Value *OtherVal = A == Op1 ? B : A;
4857 return BinaryOperator::create(I.getOpcode(), OtherVal,
4858 Constant::getNullValue(A->getType()));
4859 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4860 (A == Op0 || B == Op0)) {
4861 // A == (A^B) -> B == 0
4862 Value *OtherVal = A == Op0 ? B : A;
4863 return BinaryOperator::create(I.getOpcode(), OtherVal,
4864 Constant::getNullValue(A->getType()));
4865 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4866 // (A-B) == A -> B == 0
4867 return BinaryOperator::create(I.getOpcode(), B,
4868 Constant::getNullValue(B->getType()));
4869 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4870 // A == (A-B) -> B == 0
4871 return BinaryOperator::create(I.getOpcode(), B,
4872 Constant::getNullValue(B->getType()));
4873 }
4874 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004875 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004876}
4877
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004878// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4879// We only handle extending casts so far.
4880//
4881Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4882 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4883 const Type *SrcTy = LHSCIOp->getType();
4884 const Type *DestTy = SCI.getOperand(0)->getType();
4885 Value *RHSCIOp;
4886
4887 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004888 return 0;
4889
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004890 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4891 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4892 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4893
4894 // Is this a sign or zero extension?
4895 bool isSignSrc = SrcTy->isSigned();
4896 bool isSignDest = DestTy->isSigned();
4897
4898 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4899 // Not an extension from the same type?
4900 RHSCIOp = CI->getOperand(0);
4901 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4902 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4903 // Compute the constant that would happen if we truncated to SrcTy then
4904 // reextended to DestTy.
4905 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4906
4907 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004908 // Make sure that src sign and dest sign match. For example,
4909 //
4910 // %A = cast short %X to uint
4911 // %B = setgt uint %A, 1330
4912 //
Devang Patel88afd002006-10-19 19:21:36 +00004913 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004914 //
4915 // %B = setgt short %X, 1330
4916 //
4917 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004918 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4919 // OR operation is EQ/NE.
4920 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00004921 RHSCIOp = Res;
4922 else
4923 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004924 } else {
4925 // If the value cannot be represented in the shorter type, we cannot emit
4926 // a simple comparison.
4927 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004928 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004929 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004930 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004931
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004932 // Evaluate the comparison for LT.
4933 Value *Result;
4934 if (DestTy->isSigned()) {
4935 // We're performing a signed comparison.
4936 if (isSignSrc) {
4937 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004938 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004939 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004940 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00004941 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004942 } else {
4943 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004944 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004945 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004946 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004947 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004948 }
4949 } else {
4950 // We're performing an unsigned comparison.
4951 if (!isSignSrc) {
4952 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004953 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004954 } else {
4955 // We're performing an unsigned comp with a sign extended value.
4956 // This is true if the input is >= 0. [aka >s -1]
4957 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4958 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4959 NegOne, SCI.getName()), SCI);
4960 }
Reid Spencer279fa252004-11-28 21:31:15 +00004961 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004962
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004963 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004964 if (SCI.getOpcode() == Instruction::SetLT) {
4965 return ReplaceInstUsesWith(SCI, Result);
4966 } else {
4967 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4968 if (Constant *CI = dyn_cast<Constant>(Result))
4969 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4970 else
4971 return BinaryOperator::createNot(Result);
4972 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004973 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004974 } else {
4975 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004976 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004977
Chris Lattner252a8452005-06-16 03:00:08 +00004978 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004979 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4980}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004981
Chris Lattnere8d6c602003-03-10 19:16:08 +00004982Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004983 assert(I.getOperand(1)->getType() == Type::UByteTy);
4984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004985 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004986
4987 // shl X, 0 == X and shr X, 0 == X
4988 // shl 0, X == 0 and shr 0, X == 0
4989 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004990 Op0 == Constant::getNullValue(Op0->getType()))
4991 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004992
Chris Lattner81a7a232004-10-16 18:11:37 +00004993 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4994 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004995 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004996 else // undef << X -> 0 AND undef >>u X -> 0
4997 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4998 }
4999 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005000 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5002 else
5003 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5004 }
5005
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005006 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
5007 if (!isLeftShift)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005008 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner5dee3b22006-10-20 18:20:21 +00005009 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005010 return ReplaceInstUsesWith(I, CSI);
5011
Chris Lattner183b3362004-04-09 19:05:30 +00005012 // Try to fold constant and into select arguments.
5013 if (isa<Constant>(Op0))
5014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005016 return R;
5017
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005018 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005019 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005020 if (MaskedValueIsZero(Op0,
5021 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005022 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5023 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5024 I.getName()), I);
5025 return new CastInst(V, I.getType());
5026 }
5027 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005028
Reid Spencere0fc4df2006-10-20 07:07:24 +00005029 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5030 if (CUI->getType()->isUnsigned())
5031 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5032 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005033 return 0;
5034}
5035
Reid Spencere0fc4df2006-10-20 07:07:24 +00005036Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005037 ShiftInst &I) {
5038 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00005039 bool isSignedShift = Op0->getType()->isSigned();
5040 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005041
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005042 // See if we can simplify any instructions used by the instruction whose sole
5043 // purpose is to compute bits we don't care about.
5044 uint64_t KnownZero, KnownOne;
5045 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5046 KnownZero, KnownOne))
5047 return &I;
5048
Chris Lattner14553932006-01-06 07:12:35 +00005049 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5050 // of a signed value.
5051 //
5052 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005053 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005054 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005055 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5056 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005057 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005058 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005059 }
Chris Lattner14553932006-01-06 07:12:35 +00005060 }
5061
5062 // ((X*C1) << C2) == (X * (C1 << C2))
5063 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5064 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5065 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5066 return BinaryOperator::createMul(BO->getOperand(0),
5067 ConstantExpr::getShl(BOOp, Op1));
5068
5069 // Try to fold constant and into select arguments.
5070 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5071 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5072 return R;
5073 if (isa<PHINode>(Op0))
5074 if (Instruction *NV = FoldOpIntoPhi(I))
5075 return NV;
5076
5077 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005078 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5079 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5080 Value *V1, *V2;
5081 ConstantInt *CC;
5082 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005083 default: break;
5084 case Instruction::Add:
5085 case Instruction::And:
5086 case Instruction::Or:
5087 case Instruction::Xor:
5088 // These operators commute.
5089 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005090 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5091 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005092 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005093 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005094 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005095 Op0BO->getName());
5096 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005097 Instruction *X =
5098 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5099 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005100 InsertNewInstBefore(X, I); // (X + (Y << C))
5101 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005102 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005103 return BinaryOperator::createAnd(X, C2);
5104 }
Chris Lattner14553932006-01-06 07:12:35 +00005105
Chris Lattner797dee72005-09-18 06:30:59 +00005106 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5107 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5108 match(Op0BO->getOperand(1),
5109 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005110 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005111 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005112 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005113 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005114 Op0BO->getName());
5115 InsertNewInstBefore(YS, I); // (Y << C)
5116 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005117 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005118 V1->getName()+".mask");
5119 InsertNewInstBefore(XM, I); // X & (CC << C)
5120
5121 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5122 }
Chris Lattner14553932006-01-06 07:12:35 +00005123
Chris Lattner797dee72005-09-18 06:30:59 +00005124 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005125 case Instruction::Sub:
5126 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005127 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5128 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005129 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005130 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005131 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005132 Op0BO->getName());
5133 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005134 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005135 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005136 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005137 InsertNewInstBefore(X, I); // (X + (Y << C))
5138 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005139 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005140 return BinaryOperator::createAnd(X, C2);
5141 }
Chris Lattner14553932006-01-06 07:12:35 +00005142
Chris Lattner1df0e982006-05-31 21:14:00 +00005143 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005144 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5145 match(Op0BO->getOperand(0),
5146 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005147 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005148 cast<BinaryOperator>(Op0BO->getOperand(0))
5149 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005150 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005151 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005152 Op0BO->getName());
5153 InsertNewInstBefore(YS, I); // (Y << C)
5154 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005155 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005156 V1->getName()+".mask");
5157 InsertNewInstBefore(XM, I); // X & (CC << C)
5158
Chris Lattner1df0e982006-05-31 21:14:00 +00005159 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005160 }
Chris Lattner14553932006-01-06 07:12:35 +00005161
Chris Lattner27cb9db2005-09-18 05:12:10 +00005162 break;
Chris Lattner14553932006-01-06 07:12:35 +00005163 }
5164
5165
5166 // If the operand is an bitwise operator with a constant RHS, and the
5167 // shift is the only use, we can pull it out of the shift.
5168 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5169 bool isValid = true; // Valid only for And, Or, Xor
5170 bool highBitSet = false; // Transform if high bit of constant set?
5171
5172 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005173 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005174 case Instruction::Add:
5175 isValid = isLeftShift;
5176 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005177 case Instruction::Or:
5178 case Instruction::Xor:
5179 highBitSet = false;
5180 break;
5181 case Instruction::And:
5182 highBitSet = true;
5183 break;
Chris Lattner14553932006-01-06 07:12:35 +00005184 }
5185
5186 // If this is a signed shift right, and the high bit is modified
5187 // by the logical operation, do not perform the transformation.
5188 // The highBitSet boolean indicates the value of the high bit of
5189 // the constant which would cause it to be modified for this
5190 // operation.
5191 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005192 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005193 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005194 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5195 }
5196
5197 if (isValid) {
5198 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5199
5200 Instruction *NewShift =
5201 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5202 Op0BO->getName());
5203 Op0BO->setName("");
5204 InsertNewInstBefore(NewShift, I);
5205
5206 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5207 NewRHS);
5208 }
5209 }
5210 }
5211 }
5212
Chris Lattnereb372a02006-01-06 07:52:12 +00005213 // Find out if this is a shift of a shift by a constant.
5214 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005215 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005216 ShiftOp = Op0SI;
5217 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5218 // If this is a noop-integer case of a shift instruction, use the shift.
5219 if (CI->getOperand(0)->getType()->isInteger() &&
5220 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5221 CI->getType()->getPrimitiveSizeInBits() &&
5222 isa<ShiftInst>(CI->getOperand(0))) {
5223 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5224 }
5225 }
5226
Reid Spencere0fc4df2006-10-20 07:07:24 +00005227 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005228 // Find the operands and properties of the input shift. Note that the
5229 // signedness of the input shift may differ from the current shift if there
5230 // is a noop cast between the two.
5231 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5232 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005233 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005234
Reid Spencere0fc4df2006-10-20 07:07:24 +00005235 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005236
Reid Spencere0fc4df2006-10-20 07:07:24 +00005237 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5238 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005239
5240 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5241 if (isLeftShift == isShiftOfLeftShift) {
5242 // Do not fold these shifts if the first one is signed and the second one
5243 // is unsigned and this is a right shift. Further, don't do any folding
5244 // on them.
5245 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5246 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005247
Chris Lattnereb372a02006-01-06 07:52:12 +00005248 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5249 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5250 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005251
Chris Lattnereb372a02006-01-06 07:52:12 +00005252 Value *Op = ShiftOp->getOperand(0);
5253 if (isShiftOfSignedShift != isSignedShift)
5254 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5255 return new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005256 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnereb372a02006-01-06 07:52:12 +00005257 }
5258
5259 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5260 // signed types, we can only support the (A >> c1) << c2 configuration,
5261 // because it can not turn an arbitrary bit of A into a sign bit.
5262 if (isUnsignedShift || isLeftShift) {
5263 // Calculate bitmask for what gets shifted off the edge.
5264 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5265 if (isLeftShift)
5266 C = ConstantExpr::getShl(C, ShiftAmt1C);
5267 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005268 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005269
5270 Value *Op = ShiftOp->getOperand(0);
5271 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer00c482b2006-10-26 19:19:06 +00005272 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005273
5274 Instruction *Mask =
5275 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5276 InsertNewInstBefore(Mask, I);
5277
5278 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005279 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005280 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005281 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005282 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005283 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005284 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5285 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5286 // Make sure to emit an unsigned shift right, not a signed one.
5287 Mask = InsertNewInstBefore(new CastInst(Mask,
5288 Mask->getType()->getUnsignedVersion(),
5289 Op->getName()), I);
5290 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005291 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005292 InsertNewInstBefore(Mask, I);
5293 return new CastInst(Mask, I.getType());
5294 } else {
5295 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005296 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005297 }
5298 } else {
5299 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005300 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005301 Instruction *Shift =
5302 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005303 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005304 InsertNewInstBefore(Shift, I);
5305
5306 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5307 C = ConstantExpr::getShl(C, Op1);
5308 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5309 InsertNewInstBefore(Mask, I);
5310 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005311 }
5312 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005313 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005314 // this case, C1 == C2 and C1 is 8, 16, or 32.
5315 if (ShiftAmt1 == ShiftAmt2) {
5316 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005317 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005318 case 8 : SExtType = Type::SByteTy; break;
5319 case 16: SExtType = Type::ShortTy; break;
5320 case 32: SExtType = Type::IntTy; break;
5321 }
5322
5323 if (SExtType) {
5324 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5325 SExtType, "sext");
5326 InsertNewInstBefore(NewTrunc, I);
5327 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005328 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005329 }
Chris Lattner86102b82005-01-01 16:22:27 +00005330 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005331 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005332 return 0;
5333}
5334
Chris Lattner48a44f72002-05-02 17:06:02 +00005335
Chris Lattner8f663e82005-10-29 04:36:15 +00005336/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5337/// expression. If so, decompose it, returning some value X, such that Val is
5338/// X*Scale+Offset.
5339///
5340static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5341 unsigned &Offset) {
5342 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005343 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5344 if (CI->getType()->isUnsigned()) {
5345 Offset = CI->getZExtValue();
5346 Scale = 1;
5347 return ConstantInt::get(Type::UIntTy, 0);
5348 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005349 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5350 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005351 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5352 if (CUI->getType()->isUnsigned()) {
5353 if (I->getOpcode() == Instruction::Shl) {
5354 // This is a value scaled by '1 << the shift amt'.
5355 Scale = 1U << CUI->getZExtValue();
5356 Offset = 0;
5357 return I->getOperand(0);
5358 } else if (I->getOpcode() == Instruction::Mul) {
5359 // This value is scaled by 'CUI'.
5360 Scale = CUI->getZExtValue();
5361 Offset = 0;
5362 return I->getOperand(0);
5363 } else if (I->getOpcode() == Instruction::Add) {
5364 // We have X+C. Check to see if we really have (X*C2)+C1,
5365 // where C1 is divisible by C2.
5366 unsigned SubScale;
5367 Value *SubVal =
5368 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5369 Offset += CUI->getZExtValue();
5370 if (SubScale > 1 && (Offset % SubScale == 0)) {
5371 Scale = SubScale;
5372 return SubVal;
5373 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005374 }
5375 }
5376 }
5377 }
5378 }
5379
5380 // Otherwise, we can't look past this.
5381 Scale = 1;
5382 Offset = 0;
5383 return Val;
5384}
5385
5386
Chris Lattner216be912005-10-24 06:03:58 +00005387/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5388/// try to eliminate the cast by moving the type information into the alloc.
5389Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5390 AllocationInst &AI) {
5391 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005392 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005393
Chris Lattnerac87beb2005-10-24 06:22:12 +00005394 // Remove any uses of AI that are dead.
5395 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5396 std::vector<Instruction*> DeadUsers;
5397 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5398 Instruction *User = cast<Instruction>(*UI++);
5399 if (isInstructionTriviallyDead(User)) {
5400 while (UI != E && *UI == User)
5401 ++UI; // If this instruction uses AI more than once, don't break UI.
5402
5403 // Add operands to the worklist.
5404 AddUsesToWorkList(*User);
5405 ++NumDeadInst;
5406 DEBUG(std::cerr << "IC: DCE: " << *User);
5407
5408 User->eraseFromParent();
5409 removeFromWorkList(User);
5410 }
5411 }
5412
Chris Lattner216be912005-10-24 06:03:58 +00005413 // Get the type really allocated and the type casted to.
5414 const Type *AllocElTy = AI.getAllocatedType();
5415 const Type *CastElTy = PTy->getElementType();
5416 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005417
Chris Lattner7d190672006-10-01 19:40:58 +00005418 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5419 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005420 if (CastElTyAlign < AllocElTyAlign) return 0;
5421
Chris Lattner46705b22005-10-24 06:35:18 +00005422 // If the allocation has multiple uses, only promote it if we are strictly
5423 // increasing the alignment of the resultant allocation. If we keep it the
5424 // same, we open the door to infinite loops of various kinds.
5425 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5426
Chris Lattner216be912005-10-24 06:03:58 +00005427 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5428 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005429 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005430
Chris Lattner8270c332005-10-29 03:19:53 +00005431 // See if we can satisfy the modulus by pulling a scale out of the array
5432 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005433 unsigned ArraySizeScale, ArrayOffset;
5434 Value *NumElements = // See if the array size is a decomposable linear expr.
5435 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5436
Chris Lattner8270c332005-10-29 03:19:53 +00005437 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5438 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005439 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5440 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005441
Chris Lattner8270c332005-10-29 03:19:53 +00005442 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5443 Value *Amt = 0;
5444 if (Scale == 1) {
5445 Amt = NumElements;
5446 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005447 // If the allocation size is constant, form a constant mul expression
5448 Amt = ConstantInt::get(Type::UIntTy, Scale);
5449 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5450 Amt = ConstantExpr::getMul(
5451 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5452 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005453 else if (Scale != 1) {
5454 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5455 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005456 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005457 }
5458
Chris Lattner8f663e82005-10-29 04:36:15 +00005459 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005460 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005461 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5462 Amt = InsertNewInstBefore(Tmp, AI);
5463 }
5464
Chris Lattner216be912005-10-24 06:03:58 +00005465 std::string Name = AI.getName(); AI.setName("");
5466 AllocationInst *New;
5467 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005468 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005469 else
Nate Begeman848622f2005-11-05 09:21:28 +00005470 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005471 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005472
5473 // If the allocation has multiple uses, insert a cast and change all things
5474 // that used it to use the new cast. This will also hack on CI, but it will
5475 // die soon.
5476 if (!AI.hasOneUse()) {
5477 AddUsesToWorkList(AI);
5478 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5479 InsertNewInstBefore(NewCast, AI);
5480 AI.replaceAllUsesWith(NewCast);
5481 }
Chris Lattner216be912005-10-24 06:03:58 +00005482 return ReplaceInstUsesWith(CI, New);
5483}
5484
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005485/// CanEvaluateInDifferentType - Return true if we can take the specified value
5486/// and return it without inserting any new casts. This is used by code that
5487/// tries to decide whether promoting or shrinking integer operations to wider
5488/// or smaller types will allow us to eliminate a truncate or extend.
5489static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5490 int &NumCastsRemoved) {
5491 if (isa<Constant>(V)) return true;
5492
5493 Instruction *I = dyn_cast<Instruction>(V);
5494 if (!I || !I->hasOneUse()) return false;
5495
5496 switch (I->getOpcode()) {
5497 case Instruction::And:
5498 case Instruction::Or:
5499 case Instruction::Xor:
5500 // These operators can all arbitrarily be extended or truncated.
5501 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5502 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5503 case Instruction::Cast:
5504 // If this is a cast from the destination type, we can trivially eliminate
5505 // it, and this will remove a cast overall.
5506 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005507 // If the first operand is itself a cast, and is eliminable, do not count
5508 // this as an eliminable cast. We would prefer to eliminate those two
5509 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005510 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005511 return true;
5512
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005513 ++NumCastsRemoved;
5514 return true;
5515 }
5516 // TODO: Can handle more cases here.
5517 break;
5518 }
5519
5520 return false;
5521}
5522
5523/// EvaluateInDifferentType - Given an expression that
5524/// CanEvaluateInDifferentType returns true for, actually insert the code to
5525/// evaluate the expression.
5526Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5527 if (Constant *C = dyn_cast<Constant>(V))
5528 return ConstantExpr::getCast(C, Ty);
5529
5530 // Otherwise, it must be an instruction.
5531 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005532 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005533 switch (I->getOpcode()) {
5534 case Instruction::And:
5535 case Instruction::Or:
5536 case Instruction::Xor: {
5537 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5538 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5539 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5540 LHS, RHS, I->getName());
5541 break;
5542 }
5543 case Instruction::Cast:
5544 // If this is a cast from the destination type, return the input.
5545 if (I->getOperand(0)->getType() == Ty)
5546 return I->getOperand(0);
5547
5548 // TODO: Can handle more cases here.
5549 assert(0 && "Unreachable!");
5550 break;
5551 }
5552
5553 return InsertNewInstBefore(Res, *I);
5554}
5555
Chris Lattner216be912005-10-24 06:03:58 +00005556
Chris Lattner48a44f72002-05-02 17:06:02 +00005557// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005558//
Chris Lattner113f4f42002-06-25 16:13:24 +00005559Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005560 Value *Src = CI.getOperand(0);
5561
Chris Lattner48a44f72002-05-02 17:06:02 +00005562 // If the user is casting a value to the same type, eliminate this cast
5563 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005564 if (CI.getType() == Src->getType())
5565 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005566
Chris Lattner81a7a232004-10-16 18:11:37 +00005567 if (isa<UndefValue>(Src)) // cast undef -> undef
5568 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5569
Chris Lattner48a44f72002-05-02 17:06:02 +00005570 // If casting the result of another cast instruction, try to eliminate this
5571 // one!
5572 //
Chris Lattner86102b82005-01-01 16:22:27 +00005573 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5574 Value *A = CSrc->getOperand(0);
5575 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5576 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005577 // This instruction now refers directly to the cast's src operand. This
5578 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005579 CI.setOperand(0, CSrc->getOperand(0));
5580 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005581 }
5582
Chris Lattner650b6da2002-08-02 20:00:25 +00005583 // If this is an A->B->A cast, and we are dealing with integral types, try
5584 // to convert this into a logical 'and' instruction.
5585 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005586 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005587 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005588 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005589 CSrc->getType()->getPrimitiveSizeInBits() <
5590 CI.getType()->getPrimitiveSizeInBits()&&
5591 A->getType()->getPrimitiveSizeInBits() ==
5592 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005593 assert(CSrc->getType() != Type::ULongTy &&
5594 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005595 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005596 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005597 AndValue);
5598 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5599 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5600 if (And->getType() != CI.getType()) {
5601 And->setName(CSrc->getName()+".mask");
5602 InsertNewInstBefore(And, CI);
5603 And = new CastInst(And, CI.getType());
5604 }
5605 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005606 }
5607 }
Chris Lattner2590e512006-02-07 06:56:34 +00005608
Chris Lattner03841652004-05-25 04:29:21 +00005609 // If this is a cast to bool, turn it into the appropriate setne instruction.
5610 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005611 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005612 Constant::getNullValue(CI.getOperand(0)->getType()));
5613
Chris Lattner2590e512006-02-07 06:56:34 +00005614 // See if we can simplify any instructions used by the LHS whose sole
5615 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005616 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5617 uint64_t KnownZero, KnownOne;
5618 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5619 KnownZero, KnownOne))
5620 return &CI;
5621 }
Chris Lattner2590e512006-02-07 06:56:34 +00005622
Chris Lattnerd0d51602003-06-21 23:12:02 +00005623 // If casting the result of a getelementptr instruction with no offset, turn
5624 // this into a cast of the original pointer!
5625 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005626 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005627 bool AllZeroOperands = true;
5628 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5629 if (!isa<Constant>(GEP->getOperand(i)) ||
5630 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5631 AllZeroOperands = false;
5632 break;
5633 }
5634 if (AllZeroOperands) {
5635 CI.setOperand(0, GEP->getOperand(0));
5636 return &CI;
5637 }
5638 }
5639
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005640 // If we are casting a malloc or alloca to a pointer to a type of the same
5641 // size, rewrite the allocation instruction to allocate the "right" type.
5642 //
5643 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005644 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5645 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005646
Chris Lattner86102b82005-01-01 16:22:27 +00005647 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5648 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5649 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005650 if (isa<PHINode>(Src))
5651 if (Instruction *NV = FoldOpIntoPhi(CI))
5652 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005653
5654 // If the source and destination are pointers, and this cast is equivalent to
5655 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5656 // This can enhance SROA and other transforms that want type-safe pointers.
5657 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5658 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5659 const Type *DstTy = DstPTy->getElementType();
5660 const Type *SrcTy = SrcPTy->getElementType();
5661
5662 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5663 unsigned NumZeros = 0;
5664 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005665 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5666 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005667 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5668 ++NumZeros;
5669 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005670
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005671 // If we found a path from the src to dest, create the getelementptr now.
5672 if (SrcTy == DstTy) {
5673 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5674 return new GetElementPtrInst(Src, Idxs);
5675 }
5676 }
5677
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005678 // If the source value is an instruction with only this use, we can attempt to
5679 // propagate the cast into the instruction. Also, only handle integral types
5680 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005681 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005682 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005683 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005684
5685 int NumCastsRemoved = 0;
5686 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5687 // If this cast is a truncate, evaluting in a different type always
5688 // eliminates the cast, so it is always a win. If this is a noop-cast
5689 // this just removes a noop cast which isn't pointful, but simplifies
5690 // the code. If this is a zero-extension, we need to do an AND to
5691 // maintain the clear top-part of the computation, so we require that
5692 // the input have eliminated at least one cast. If this is a sign
5693 // extension, we insert two new casts (to do the extension) so we
5694 // require that two casts have been eliminated.
5695 bool DoXForm;
5696 switch (getCastType(Src->getType(), CI.getType())) {
5697 default: assert(0 && "Unknown cast type!");
5698 case Noop:
5699 case Truncate:
5700 DoXForm = true;
5701 break;
5702 case Zeroext:
5703 DoXForm = NumCastsRemoved >= 1;
5704 break;
5705 case Signext:
5706 DoXForm = NumCastsRemoved >= 2;
5707 break;
5708 }
5709
5710 if (DoXForm) {
5711 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5712 assert(Res->getType() == CI.getType());
5713 switch (getCastType(Src->getType(), CI.getType())) {
5714 default: assert(0 && "Unknown cast type!");
5715 case Noop:
5716 case Truncate:
5717 // Just replace this cast with the result.
5718 return ReplaceInstUsesWith(CI, Res);
5719 case Zeroext: {
5720 // We need to emit an AND to clear the high bits.
5721 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5722 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5723 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005724 Constant *C =
5725 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005726 C = ConstantExpr::getCast(C, CI.getType());
5727 return BinaryOperator::createAnd(Res, C);
5728 }
5729 case Signext:
5730 // We need to emit a cast to truncate, then a cast to sext.
5731 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5732 CI.getType());
5733 }
5734 }
5735 }
5736
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005737 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005738 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5739 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005740
5741 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5742 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5743
5744 switch (SrcI->getOpcode()) {
5745 case Instruction::Add:
5746 case Instruction::Mul:
5747 case Instruction::And:
5748 case Instruction::Or:
5749 case Instruction::Xor:
5750 // If we are discarding information, or just changing the sign, rewrite.
5751 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5752 // Don't insert two casts if they cannot be eliminated. We allow two
5753 // casts to be inserted if the sizes are the same. This could only be
5754 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005755 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5756 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005757 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5758 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5759 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5760 ->getOpcode(), Op0c, Op1c);
5761 }
5762 }
Chris Lattner72086162005-05-06 02:07:39 +00005763
5764 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5765 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005766 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005767 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5768 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5769 return BinaryOperator::createXor(New,
5770 ConstantInt::get(CI.getType(), 1));
5771 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005772 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005773 case Instruction::SDiv:
5774 case Instruction::UDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00005775 case Instruction::SRem:
5776 case Instruction::URem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005777 // If we are just changing the sign, rewrite.
5778 if (DestBitSize == SrcBitSize) {
5779 // Don't insert two casts if they cannot be eliminated. We allow two
5780 // casts to be inserted if the sizes are the same. This could only be
5781 // converting signedness, which is a noop.
5782 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5783 !ValueRequiresCast(Op0, DestTy, TD)) {
5784 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5785 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5786 return BinaryOperator::create(
5787 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5788 }
5789 }
5790 break;
5791
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005792 case Instruction::Shl:
5793 // Allow changing the sign of the source operand. Do not allow changing
5794 // the size of the shift, UNLESS the shift amount is a constant. We
5795 // mush not change variable sized shifts to a smaller size, because it
5796 // is undefined to shift more bits out than exist in the value.
5797 if (DestBitSize == SrcBitSize ||
5798 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5799 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5800 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5801 }
5802 break;
Chris Lattner87380412005-05-06 04:18:52 +00005803 case Instruction::Shr:
5804 // If this is a signed shr, and if all bits shifted in are about to be
5805 // truncated off, turn it into an unsigned shr to allow greater
5806 // simplifications.
5807 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5808 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005809 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005810 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5811 // Convert to unsigned.
5812 Value *N1 = InsertOperandCastBefore(Op0,
5813 Op0->getType()->getUnsignedVersion(), &CI);
5814 // Insert the new shift, which is now unsigned.
5815 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5816 Op1, Src->getName()), CI);
5817 return new CastInst(N1, CI.getType());
5818 }
5819 }
5820 break;
5821
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005822 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005823 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005824 // We if we are just checking for a seteq of a single bit and casting it
5825 // to an integer. If so, shift the bit to the appropriate place then
5826 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005827 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005828 uint64_t Op1CV = Op1C->getZExtValue();
5829 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5830 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5831 // cast (X == 1) to int --> X iff X has only the low bit set.
5832 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5833 // cast (X != 0) to int --> X iff X has only the low bit set.
5834 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5835 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5836 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5837 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5838 // If Op1C some other power of two, convert:
5839 uint64_t KnownZero, KnownOne;
5840 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5841 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5842
5843 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5844 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5845 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5846 // (X&4) == 2 --> false
5847 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005848 Constant *Res = ConstantBool::get(isSetNE);
5849 Res = ConstantExpr::getCast(Res, CI.getType());
5850 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005851 }
5852
5853 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5854 Value *In = Op0;
5855 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005856 // Perform an unsigned shr by shiftamt. Convert input to
5857 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005858 if (In->getType()->isSigned())
Reid Spencer00c482b2006-10-26 19:19:06 +00005859 In = InsertCastBefore(
5860 In, In->getType()->getUnsignedVersion(), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005861 // Insert the shift to put the result in the low bit.
5862 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005863 ConstantInt::get(Type::UByteTy, ShiftAmt),
5864 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005865 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005866
5867 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5868 Constant *One = ConstantInt::get(In->getType(), 1);
5869 In = BinaryOperator::createXor(In, One, "tmp");
5870 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005871 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005872
5873 if (CI.getType() == In->getType())
5874 return ReplaceInstUsesWith(CI, In);
5875 else
5876 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005877 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005878 }
5879 }
5880 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005881 }
5882 }
Chris Lattner99155be2006-05-25 23:24:33 +00005883
5884 if (SrcI->hasOneUse()) {
5885 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5886 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5887 // because the inputs are known to be a vector. Check to see if this is
5888 // a cast to a vector with the same # elts.
5889 if (isa<PackedType>(CI.getType()) &&
5890 cast<PackedType>(CI.getType())->getNumElements() ==
5891 SVI->getType()->getNumElements()) {
5892 CastInst *Tmp;
5893 // If either of the operands is a cast from CI.getType(), then
5894 // evaluating the shuffle in the casted destination's type will allow
5895 // us to eliminate at least one cast.
5896 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5897 Tmp->getOperand(0)->getType() == CI.getType()) ||
5898 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005899 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005900 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5901 CI.getType(), &CI);
5902 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5903 CI.getType(), &CI);
5904 // Return a new shuffle vector. Use the same element ID's, as we
5905 // know the vector types match #elts.
5906 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5907 }
5908 }
5909 }
5910 }
5911 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005912
Chris Lattner260ab202002-04-18 17:39:14 +00005913 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005914}
5915
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005916/// GetSelectFoldableOperands - We want to turn code that looks like this:
5917/// %C = or %A, %B
5918/// %D = select %cond, %C, %A
5919/// into:
5920/// %C = select %cond, %B, 0
5921/// %D = or %A, %C
5922///
5923/// Assuming that the specified instruction is an operand to the select, return
5924/// a bitmask indicating which operands of this instruction are foldable if they
5925/// equal the other incoming value of the select.
5926///
5927static unsigned GetSelectFoldableOperands(Instruction *I) {
5928 switch (I->getOpcode()) {
5929 case Instruction::Add:
5930 case Instruction::Mul:
5931 case Instruction::And:
5932 case Instruction::Or:
5933 case Instruction::Xor:
5934 return 3; // Can fold through either operand.
5935 case Instruction::Sub: // Can only fold on the amount subtracted.
5936 case Instruction::Shl: // Can only fold on the shift amount.
5937 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005938 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005939 default:
5940 return 0; // Cannot fold
5941 }
5942}
5943
5944/// GetSelectFoldableConstant - For the same transformation as the previous
5945/// function, return the identity constant that goes into the select.
5946static Constant *GetSelectFoldableConstant(Instruction *I) {
5947 switch (I->getOpcode()) {
5948 default: assert(0 && "This cannot happen!"); abort();
5949 case Instruction::Add:
5950 case Instruction::Sub:
5951 case Instruction::Or:
5952 case Instruction::Xor:
5953 return Constant::getNullValue(I->getType());
5954 case Instruction::Shl:
5955 case Instruction::Shr:
5956 return Constant::getNullValue(Type::UByteTy);
5957 case Instruction::And:
5958 return ConstantInt::getAllOnesValue(I->getType());
5959 case Instruction::Mul:
5960 return ConstantInt::get(I->getType(), 1);
5961 }
5962}
5963
Chris Lattner411336f2005-01-19 21:50:18 +00005964/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5965/// have the same opcode and only one use each. Try to simplify this.
5966Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5967 Instruction *FI) {
5968 if (TI->getNumOperands() == 1) {
5969 // If this is a non-volatile load or a cast from the same type,
5970 // merge.
5971 if (TI->getOpcode() == Instruction::Cast) {
5972 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5973 return 0;
5974 } else {
5975 return 0; // unknown unary op.
5976 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005977
Chris Lattner411336f2005-01-19 21:50:18 +00005978 // Fold this by inserting a select from the input values.
5979 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5980 FI->getOperand(0), SI.getName()+".v");
5981 InsertNewInstBefore(NewSI, SI);
5982 return new CastInst(NewSI, TI->getType());
5983 }
5984
5985 // Only handle binary operators here.
5986 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5987 return 0;
5988
5989 // Figure out if the operations have any operands in common.
5990 Value *MatchOp, *OtherOpT, *OtherOpF;
5991 bool MatchIsOpZero;
5992 if (TI->getOperand(0) == FI->getOperand(0)) {
5993 MatchOp = TI->getOperand(0);
5994 OtherOpT = TI->getOperand(1);
5995 OtherOpF = FI->getOperand(1);
5996 MatchIsOpZero = true;
5997 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5998 MatchOp = TI->getOperand(1);
5999 OtherOpT = TI->getOperand(0);
6000 OtherOpF = FI->getOperand(0);
6001 MatchIsOpZero = false;
6002 } else if (!TI->isCommutative()) {
6003 return 0;
6004 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6005 MatchOp = TI->getOperand(0);
6006 OtherOpT = TI->getOperand(1);
6007 OtherOpF = FI->getOperand(0);
6008 MatchIsOpZero = true;
6009 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6010 MatchOp = TI->getOperand(1);
6011 OtherOpT = TI->getOperand(0);
6012 OtherOpF = FI->getOperand(1);
6013 MatchIsOpZero = true;
6014 } else {
6015 return 0;
6016 }
6017
6018 // If we reach here, they do have operations in common.
6019 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6020 OtherOpF, SI.getName()+".v");
6021 InsertNewInstBefore(NewSI, SI);
6022
6023 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6024 if (MatchIsOpZero)
6025 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6026 else
6027 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6028 } else {
6029 if (MatchIsOpZero)
6030 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6031 else
6032 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6033 }
6034}
6035
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006036Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006037 Value *CondVal = SI.getCondition();
6038 Value *TrueVal = SI.getTrueValue();
6039 Value *FalseVal = SI.getFalseValue();
6040
6041 // select true, X, Y -> X
6042 // select false, X, Y -> Y
6043 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006044 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006045
6046 // select C, X, X -> X
6047 if (TrueVal == FalseVal)
6048 return ReplaceInstUsesWith(SI, TrueVal);
6049
Chris Lattner81a7a232004-10-16 18:11:37 +00006050 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6051 return ReplaceInstUsesWith(SI, FalseVal);
6052 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6053 return ReplaceInstUsesWith(SI, TrueVal);
6054 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6055 if (isa<Constant>(TrueVal))
6056 return ReplaceInstUsesWith(SI, TrueVal);
6057 else
6058 return ReplaceInstUsesWith(SI, FalseVal);
6059 }
6060
Chris Lattner1c631e82004-04-08 04:43:23 +00006061 if (SI.getType() == Type::BoolTy)
6062 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006063 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006064 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006065 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006066 } else {
6067 // Change: A = select B, false, C --> A = and !B, C
6068 Value *NotCond =
6069 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6070 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006071 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006072 }
6073 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006074 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006075 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006076 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006077 } else {
6078 // Change: A = select B, C, true --> A = or !B, C
6079 Value *NotCond =
6080 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6081 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006082 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006083 }
6084 }
6085
Chris Lattner183b3362004-04-09 19:05:30 +00006086 // Selecting between two integer constants?
6087 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6088 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6089 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006090 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006091 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006092 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006093 // select C, 0, 1 -> cast !C to int
6094 Value *NotCond =
6095 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006096 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006097 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006098 }
Chris Lattner35167c32004-06-09 07:59:58 +00006099
Chris Lattner380c7e92006-09-20 04:44:59 +00006100 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6101
6102 // (x <s 0) ? -1 : 0 -> sra x, 31
6103 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6104 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6105 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6106 bool CanXForm = false;
6107 if (CmpCst->getType()->isSigned())
6108 CanXForm = CmpCst->isNullValue() &&
6109 IC->getOpcode() == Instruction::SetLT;
6110 else {
6111 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006112 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006113 IC->getOpcode() == Instruction::SetGT;
6114 }
6115
6116 if (CanXForm) {
6117 // The comparison constant and the result are not neccessarily the
6118 // same width. In any case, the first step to do is make sure
6119 // that X is signed.
6120 Value *X = IC->getOperand(0);
6121 if (!X->getType()->isSigned())
6122 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6123
6124 // Now that X is signed, we have to make the all ones value. Do
6125 // this by inserting a new SRA.
6126 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006127 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattner380c7e92006-09-20 04:44:59 +00006128 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6129 ShAmt, "ones");
6130 InsertNewInstBefore(SRA, SI);
6131
6132 // Finally, convert to the type of the select RHS. If this is
6133 // smaller than the compare value, it will truncate the ones to
6134 // fit. If it is larger, it will sext the ones to fit.
6135 return new CastInst(SRA, SI.getType());
6136 }
6137 }
6138
6139
6140 // If one of the constants is zero (we know they can't both be) and we
6141 // have a setcc instruction with zero, and we have an 'and' with the
6142 // non-constant value, eliminate this whole mess. This corresponds to
6143 // cases like this: ((X & 27) ? 27 : 0)
6144 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006145 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006146 cast<Constant>(IC->getOperand(1))->isNullValue())
6147 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6148 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006149 isa<ConstantInt>(ICA->getOperand(1)) &&
6150 (ICA->getOperand(1) == TrueValC ||
6151 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006152 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6153 // Okay, now we know that everything is set up, we just don't
6154 // know whether we have a setne or seteq and whether the true or
6155 // false val is the zero.
6156 bool ShouldNotVal = !TrueValC->isNullValue();
6157 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6158 Value *V = ICA;
6159 if (ShouldNotVal)
6160 V = InsertNewInstBefore(BinaryOperator::create(
6161 Instruction::Xor, V, ICA->getOperand(1)), SI);
6162 return ReplaceInstUsesWith(SI, V);
6163 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006164 }
Chris Lattner533bc492004-03-30 19:37:13 +00006165 }
Chris Lattner623fba12004-04-10 22:21:27 +00006166
6167 // See if we are selecting two values based on a comparison of the two values.
6168 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6169 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6170 // Transform (X == Y) ? X : Y -> Y
6171 if (SCI->getOpcode() == Instruction::SetEQ)
6172 return ReplaceInstUsesWith(SI, FalseVal);
6173 // Transform (X != Y) ? X : Y -> X
6174 if (SCI->getOpcode() == Instruction::SetNE)
6175 return ReplaceInstUsesWith(SI, TrueVal);
6176 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6177
6178 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6179 // Transform (X == Y) ? Y : X -> X
6180 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006181 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006182 // Transform (X != Y) ? Y : X -> Y
6183 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006184 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006185 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6186 }
6187 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006188
Chris Lattnera04c9042005-01-13 22:52:24 +00006189 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6190 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6191 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006192 Instruction *AddOp = 0, *SubOp = 0;
6193
Chris Lattner411336f2005-01-19 21:50:18 +00006194 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6195 if (TI->getOpcode() == FI->getOpcode())
6196 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6197 return IV;
6198
6199 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6200 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006201 if (TI->getOpcode() == Instruction::Sub &&
6202 FI->getOpcode() == Instruction::Add) {
6203 AddOp = FI; SubOp = TI;
6204 } else if (FI->getOpcode() == Instruction::Sub &&
6205 TI->getOpcode() == Instruction::Add) {
6206 AddOp = TI; SubOp = FI;
6207 }
6208
6209 if (AddOp) {
6210 Value *OtherAddOp = 0;
6211 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6212 OtherAddOp = AddOp->getOperand(1);
6213 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6214 OtherAddOp = AddOp->getOperand(0);
6215 }
6216
6217 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006218 // So at this point we know we have (Y -> OtherAddOp):
6219 // select C, (add X, Y), (sub X, Z)
6220 Value *NegVal; // Compute -Z
6221 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6222 NegVal = ConstantExpr::getNeg(C);
6223 } else {
6224 NegVal = InsertNewInstBefore(
6225 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006226 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006227
6228 Value *NewTrueOp = OtherAddOp;
6229 Value *NewFalseOp = NegVal;
6230 if (AddOp != TI)
6231 std::swap(NewTrueOp, NewFalseOp);
6232 Instruction *NewSel =
6233 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6234
6235 NewSel = InsertNewInstBefore(NewSel, SI);
6236 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006237 }
6238 }
6239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006240
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006241 // See if we can fold the select into one of our operands.
6242 if (SI.getType()->isInteger()) {
6243 // See the comment above GetSelectFoldableOperands for a description of the
6244 // transformation we are doing here.
6245 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6246 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6247 !isa<Constant>(FalseVal))
6248 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6249 unsigned OpToFold = 0;
6250 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6251 OpToFold = 1;
6252 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6253 OpToFold = 2;
6254 }
6255
6256 if (OpToFold) {
6257 Constant *C = GetSelectFoldableConstant(TVI);
6258 std::string Name = TVI->getName(); TVI->setName("");
6259 Instruction *NewSel =
6260 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6261 Name);
6262 InsertNewInstBefore(NewSel, SI);
6263 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6264 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6265 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6266 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6267 else {
6268 assert(0 && "Unknown instruction!!");
6269 }
6270 }
6271 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006272
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006273 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6274 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6275 !isa<Constant>(TrueVal))
6276 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6277 unsigned OpToFold = 0;
6278 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6279 OpToFold = 1;
6280 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6281 OpToFold = 2;
6282 }
6283
6284 if (OpToFold) {
6285 Constant *C = GetSelectFoldableConstant(FVI);
6286 std::string Name = FVI->getName(); FVI->setName("");
6287 Instruction *NewSel =
6288 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6289 Name);
6290 InsertNewInstBefore(NewSel, SI);
6291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6292 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6293 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6294 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6295 else {
6296 assert(0 && "Unknown instruction!!");
6297 }
6298 }
6299 }
6300 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006301
6302 if (BinaryOperator::isNot(CondVal)) {
6303 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6304 SI.setOperand(1, FalseVal);
6305 SI.setOperand(2, TrueVal);
6306 return &SI;
6307 }
6308
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006309 return 0;
6310}
6311
Chris Lattner82f2ef22006-03-06 20:18:44 +00006312/// GetKnownAlignment - If the specified pointer has an alignment that we can
6313/// determine, return it, otherwise return 0.
6314static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6315 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6316 unsigned Align = GV->getAlignment();
6317 if (Align == 0 && TD)
6318 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6319 return Align;
6320 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6321 unsigned Align = AI->getAlignment();
6322 if (Align == 0 && TD) {
6323 if (isa<AllocaInst>(AI))
6324 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6325 else if (isa<MallocInst>(AI)) {
6326 // Malloc returns maximally aligned memory.
6327 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6328 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6329 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6330 }
6331 }
6332 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006333 } else if (isa<CastInst>(V) ||
6334 (isa<ConstantExpr>(V) &&
6335 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6336 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006337 if (isa<PointerType>(CI->getOperand(0)->getType()))
6338 return GetKnownAlignment(CI->getOperand(0), TD);
6339 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006340 } else if (isa<GetElementPtrInst>(V) ||
6341 (isa<ConstantExpr>(V) &&
6342 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6343 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006344 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6345 if (BaseAlignment == 0) return 0;
6346
6347 // If all indexes are zero, it is just the alignment of the base pointer.
6348 bool AllZeroOperands = true;
6349 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6350 if (!isa<Constant>(GEPI->getOperand(i)) ||
6351 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6352 AllZeroOperands = false;
6353 break;
6354 }
6355 if (AllZeroOperands)
6356 return BaseAlignment;
6357
6358 // Otherwise, if the base alignment is >= the alignment we expect for the
6359 // base pointer type, then we know that the resultant pointer is aligned at
6360 // least as much as its type requires.
6361 if (!TD) return 0;
6362
6363 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6364 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006365 <= BaseAlignment) {
6366 const Type *GEPTy = GEPI->getType();
6367 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6368 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006369 return 0;
6370 }
6371 return 0;
6372}
6373
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006374
Chris Lattnerc66b2232006-01-13 20:11:04 +00006375/// visitCallInst - CallInst simplification. This mostly only handles folding
6376/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6377/// the heavy lifting.
6378///
Chris Lattner970c33a2003-06-19 17:00:31 +00006379Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006380 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6381 if (!II) return visitCallSite(&CI);
6382
Chris Lattner51ea1272004-02-28 05:22:00 +00006383 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6384 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006385 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006386 bool Changed = false;
6387
6388 // memmove/cpy/set of zero bytes is a noop.
6389 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6390 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6391
Chris Lattner00648e12004-10-12 04:52:52 +00006392 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006393 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006394 // Replace the instruction with just byte operations. We would
6395 // transform other cases to loads/stores, but we don't know if
6396 // alignment is sufficient.
6397 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006398 }
6399
Chris Lattner00648e12004-10-12 04:52:52 +00006400 // If we have a memmove and the source operation is a constant global,
6401 // then the source and dest pointers can't alias, so we can change this
6402 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006403 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006404 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6405 if (GVSrc->isConstant()) {
6406 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006407 const char *Name;
6408 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6409 Type::UIntTy)
6410 Name = "llvm.memcpy.i32";
6411 else
6412 Name = "llvm.memcpy.i64";
6413 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006414 CI.getCalledFunction()->getFunctionType());
6415 CI.setOperand(0, MemCpy);
6416 Changed = true;
6417 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006418 }
Chris Lattner00648e12004-10-12 04:52:52 +00006419
Chris Lattner82f2ef22006-03-06 20:18:44 +00006420 // If we can determine a pointer alignment that is bigger than currently
6421 // set, update the alignment.
6422 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6423 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6424 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6425 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006426 if (MI->getAlignment()->getZExtValue() < Align) {
6427 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006428 Changed = true;
6429 }
6430 } else if (isa<MemSetInst>(MI)) {
6431 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006432 if (MI->getAlignment()->getZExtValue() < Alignment) {
6433 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006434 Changed = true;
6435 }
6436 }
6437
Chris Lattnerc66b2232006-01-13 20:11:04 +00006438 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006439 } else {
6440 switch (II->getIntrinsicID()) {
6441 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006442 case Intrinsic::ppc_altivec_lvx:
6443 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006444 case Intrinsic::x86_sse_loadu_ps:
6445 case Intrinsic::x86_sse2_loadu_pd:
6446 case Intrinsic::x86_sse2_loadu_dq:
6447 // Turn PPC lvx -> load if the pointer is known aligned.
6448 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006449 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006450 Value *Ptr = InsertCastBefore(II->getOperand(1),
6451 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006452 return new LoadInst(Ptr);
6453 }
6454 break;
6455 case Intrinsic::ppc_altivec_stvx:
6456 case Intrinsic::ppc_altivec_stvxl:
6457 // Turn stvx -> store if the pointer is known aligned.
6458 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006459 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6460 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006461 return new StoreInst(II->getOperand(1), Ptr);
6462 }
6463 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006464 case Intrinsic::x86_sse_storeu_ps:
6465 case Intrinsic::x86_sse2_storeu_pd:
6466 case Intrinsic::x86_sse2_storeu_dq:
6467 case Intrinsic::x86_sse2_storel_dq:
6468 // Turn X86 storeu -> store if the pointer is known aligned.
6469 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6470 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6471 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6472 return new StoreInst(II->getOperand(2), Ptr);
6473 }
6474 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006475
6476 case Intrinsic::x86_sse_cvttss2si: {
6477 // These intrinsics only demands the 0th element of its input vector. If
6478 // we can simplify the input based on that, do so now.
6479 uint64_t UndefElts;
6480 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6481 UndefElts)) {
6482 II->setOperand(1, V);
6483 return II;
6484 }
6485 break;
6486 }
6487
Chris Lattnere79d2492006-04-06 19:19:17 +00006488 case Intrinsic::ppc_altivec_vperm:
6489 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6490 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6491 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6492
6493 // Check that all of the elements are integer constants or undefs.
6494 bool AllEltsOk = true;
6495 for (unsigned i = 0; i != 16; ++i) {
6496 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6497 !isa<UndefValue>(Mask->getOperand(i))) {
6498 AllEltsOk = false;
6499 break;
6500 }
6501 }
6502
6503 if (AllEltsOk) {
6504 // Cast the input vectors to byte vectors.
6505 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6506 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6507 Value *Result = UndefValue::get(Op0->getType());
6508
6509 // Only extract each element once.
6510 Value *ExtractedElts[32];
6511 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6512
6513 for (unsigned i = 0; i != 16; ++i) {
6514 if (isa<UndefValue>(Mask->getOperand(i)))
6515 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006516 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006517 Idx &= 31; // Match the hardware behavior.
6518
6519 if (ExtractedElts[Idx] == 0) {
6520 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006521 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006522 InsertNewInstBefore(Elt, CI);
6523 ExtractedElts[Idx] = Elt;
6524 }
6525
6526 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006527 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006528 InsertNewInstBefore(cast<Instruction>(Result), CI);
6529 }
6530 return new CastInst(Result, CI.getType());
6531 }
6532 }
6533 break;
6534
Chris Lattner503221f2006-01-13 21:28:09 +00006535 case Intrinsic::stackrestore: {
6536 // If the save is right next to the restore, remove the restore. This can
6537 // happen when variable allocas are DCE'd.
6538 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6539 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6540 BasicBlock::iterator BI = SS;
6541 if (&*++BI == II)
6542 return EraseInstFromFunction(CI);
6543 }
6544 }
6545
6546 // If the stack restore is in a return/unwind block and if there are no
6547 // allocas or calls between the restore and the return, nuke the restore.
6548 TerminatorInst *TI = II->getParent()->getTerminator();
6549 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6550 BasicBlock::iterator BI = II;
6551 bool CannotRemove = false;
6552 for (++BI; &*BI != TI; ++BI) {
6553 if (isa<AllocaInst>(BI) ||
6554 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6555 CannotRemove = true;
6556 break;
6557 }
6558 }
6559 if (!CannotRemove)
6560 return EraseInstFromFunction(CI);
6561 }
6562 break;
6563 }
6564 }
Chris Lattner00648e12004-10-12 04:52:52 +00006565 }
6566
Chris Lattnerc66b2232006-01-13 20:11:04 +00006567 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006568}
6569
6570// InvokeInst simplification
6571//
6572Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006573 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006574}
6575
Chris Lattneraec3d942003-10-07 22:32:43 +00006576// visitCallSite - Improvements for call and invoke instructions.
6577//
6578Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006579 bool Changed = false;
6580
6581 // If the callee is a constexpr cast of a function, attempt to move the cast
6582 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006583 if (transformConstExprCastCall(CS)) return 0;
6584
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006585 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006586
Chris Lattner61d9d812005-05-13 07:09:09 +00006587 if (Function *CalleeF = dyn_cast<Function>(Callee))
6588 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6589 Instruction *OldCall = CS.getInstruction();
6590 // If the call and callee calling conventions don't match, this call must
6591 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006592 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006593 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6594 if (!OldCall->use_empty())
6595 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6596 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6597 return EraseInstFromFunction(*OldCall);
6598 return 0;
6599 }
6600
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006601 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6602 // This instruction is not reachable, just remove it. We insert a store to
6603 // undef so that we know that this code is not reachable, despite the fact
6604 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006605 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006606 UndefValue::get(PointerType::get(Type::BoolTy)),
6607 CS.getInstruction());
6608
6609 if (!CS.getInstruction()->use_empty())
6610 CS.getInstruction()->
6611 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6612
6613 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6614 // Don't break the CFG, insert a dummy cond branch.
6615 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006616 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006617 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006618 return EraseInstFromFunction(*CS.getInstruction());
6619 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006620
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006621 const PointerType *PTy = cast<PointerType>(Callee->getType());
6622 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6623 if (FTy->isVarArg()) {
6624 // See if we can optimize any arguments passed through the varargs area of
6625 // the call.
6626 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6627 E = CS.arg_end(); I != E; ++I)
6628 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6629 // If this cast does not effect the value passed through the varargs
6630 // area, we can eliminate the use of the cast.
6631 Value *Op = CI->getOperand(0);
6632 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6633 *I = Op;
6634 Changed = true;
6635 }
6636 }
6637 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006638
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006639 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006640}
6641
Chris Lattner970c33a2003-06-19 17:00:31 +00006642// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6643// attempt to move the cast to the arguments of the call/invoke.
6644//
6645bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6646 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6647 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006648 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006649 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006650 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006651 Instruction *Caller = CS.getInstruction();
6652
6653 // Okay, this is a cast from a function to a different type. Unless doing so
6654 // would cause a type conversion of one of our arguments, change this call to
6655 // be a direct call with arguments casted to the appropriate types.
6656 //
6657 const FunctionType *FT = Callee->getFunctionType();
6658 const Type *OldRetTy = Caller->getType();
6659
Chris Lattner1f7942f2004-01-14 06:06:08 +00006660 // Check to see if we are changing the return type...
6661 if (OldRetTy != FT->getReturnType()) {
6662 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006663 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6664 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006665 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006666 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006667 return false; // Cannot transform this return value...
6668
6669 // If the callsite is an invoke instruction, and the return value is used by
6670 // a PHI node in a successor, we cannot change the return type of the call
6671 // because there is no place to put the cast instruction (without breaking
6672 // the critical edge). Bail out in this case.
6673 if (!Caller->use_empty())
6674 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6675 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6676 UI != E; ++UI)
6677 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6678 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006679 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006680 return false;
6681 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006682
6683 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6684 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006685
Chris Lattner970c33a2003-06-19 17:00:31 +00006686 CallSite::arg_iterator AI = CS.arg_begin();
6687 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6688 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006689 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006690 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006691 //Either we can cast directly, or we can upconvert the argument
6692 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6693 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6694 ParamTy->isSigned() == ActTy->isSigned() &&
6695 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6696 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006697 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006698 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006699 }
6700
6701 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6702 Callee->isExternal())
6703 return false; // Do not delete arguments unless we have a function body...
6704
6705 // Okay, we decided that this is a safe thing to do: go ahead and start
6706 // inserting cast instructions as necessary...
6707 std::vector<Value*> Args;
6708 Args.reserve(NumActualArgs);
6709
6710 AI = CS.arg_begin();
6711 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6712 const Type *ParamTy = FT->getParamType(i);
6713 if ((*AI)->getType() == ParamTy) {
6714 Args.push_back(*AI);
6715 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006716 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6717 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006718 }
6719 }
6720
6721 // If the function takes more arguments than the call was taking, add them
6722 // now...
6723 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6724 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6725
6726 // If we are removing arguments to the function, emit an obnoxious warning...
6727 if (FT->getNumParams() < NumActualArgs)
6728 if (!FT->isVarArg()) {
6729 std::cerr << "WARNING: While resolving call to function '"
6730 << Callee->getName() << "' arguments were dropped!\n";
6731 } else {
6732 // Add all of the arguments in their promoted form to the arg list...
6733 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6734 const Type *PTy = getPromotedType((*AI)->getType());
6735 if (PTy != (*AI)->getType()) {
6736 // Must promote to pass through va_arg area!
6737 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6738 InsertNewInstBefore(Cast, *Caller);
6739 Args.push_back(Cast);
6740 } else {
6741 Args.push_back(*AI);
6742 }
6743 }
6744 }
6745
6746 if (FT->getReturnType() == Type::VoidTy)
6747 Caller->setName(""); // Void type should not have a name...
6748
6749 Instruction *NC;
6750 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006751 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006752 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006753 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006754 } else {
6755 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006756 if (cast<CallInst>(Caller)->isTailCall())
6757 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006758 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006759 }
6760
6761 // Insert a cast of the return type as necessary...
6762 Value *NV = NC;
6763 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6764 if (NV->getType() != Type::VoidTy) {
6765 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006766
6767 // If this is an invoke instruction, we should insert it after the first
6768 // non-phi, instruction in the normal successor block.
6769 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6770 BasicBlock::iterator I = II->getNormalDest()->begin();
6771 while (isa<PHINode>(I)) ++I;
6772 InsertNewInstBefore(NC, *I);
6773 } else {
6774 // Otherwise, it's a call, just insert cast right after the call instr
6775 InsertNewInstBefore(NC, *Caller);
6776 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006777 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006778 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006779 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006780 }
6781 }
6782
6783 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6784 Caller->replaceAllUsesWith(NV);
6785 Caller->getParent()->getInstList().erase(Caller);
6786 removeFromWorkList(Caller);
6787 return true;
6788}
6789
Chris Lattnercadac0c2006-11-01 04:51:18 +00006790/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6791/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6792/// and a single binop.
6793Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6794 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006795 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6796 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006797 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006798 const Type *LHSType = FirstInst->getOperand(0)->getType();
Chris Lattnereebea432006-11-01 07:43:41 +00006799 const Type *RHSType = FirstInst->getOperand(1)->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00006800
6801 // Scan to see if all operands are the same opcode, all have one use, and all
6802 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006803 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006804 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006805 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6806 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00006807 // types or GEP's with different index types.
6808 I->getOperand(0)->getType() != LHSType ||
6809 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00006810 return 0;
6811 }
6812
6813 // Otherwise, this is safe and profitable to transform. Create two phi nodes.
6814 PHINode *NewLHS = new PHINode(FirstInst->getOperand(0)->getType(),
6815 FirstInst->getOperand(0)->getName()+".pn");
6816 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6817 PHINode *NewRHS = new PHINode(FirstInst->getOperand(1)->getType(),
6818 FirstInst->getOperand(1)->getName()+".pn");
6819 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6820
6821 Value *InLHS = FirstInst->getOperand(0);
6822 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6823 Value *InRHS = FirstInst->getOperand(1);
6824 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6825
6826 // Add all operands to the new PHsI.
6827 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6828 Value *NewInLHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6829 Value *NewInRHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6830 if (NewInLHS != InLHS) InLHS = 0;
6831 if (NewInRHS != InRHS) InRHS = 0;
6832 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6833 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6834 }
6835
Chris Lattnereebea432006-11-01 07:43:41 +00006836 Value *LHSVal;
6837 if (InLHS) {
6838 // The new PHI unions all of the same values together. This is really
6839 // common, so we handle it intelligently here for compile-time speed.
6840 LHSVal = InLHS;
6841 delete NewLHS;
6842 } else {
6843 InsertNewInstBefore(NewLHS, PN);
6844 LHSVal = NewLHS;
6845 }
6846 Value *RHSVal;
6847 if (InRHS) {
6848 // The new PHI unions all of the same values together. This is really
6849 // common, so we handle it intelligently here for compile-time speed.
6850 RHSVal = InRHS;
6851 delete NewRHS;
6852 } else {
6853 InsertNewInstBefore(NewRHS, PN);
6854 RHSVal = NewRHS;
6855 }
6856
Chris Lattnercadac0c2006-11-01 04:51:18 +00006857 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00006858 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6859 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6860 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6861 else {
6862 assert(isa<GetElementPtrInst>(FirstInst));
6863 return new GetElementPtrInst(LHSVal, RHSVal);
6864 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00006865}
6866
Chris Lattner14f82c72006-11-01 07:13:54 +00006867/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6868/// of the block that defines it. This means that it must be obvious the value
6869/// of the load is not changed from the point of the load to the end of the
6870/// block it is in.
6871static bool isSafeToSinkLoad(LoadInst *L) {
6872 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6873
6874 for (++BBI; BBI != E; ++BBI)
6875 if (BBI->mayWriteToMemory())
6876 return false;
6877 return true;
6878}
6879
Chris Lattner970c33a2003-06-19 17:00:31 +00006880
Chris Lattner7515cab2004-11-14 19:13:23 +00006881// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6882// operator and they all are only used by the PHI, PHI together their
6883// inputs, and do the operation once, to the result of the PHI.
6884Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6885 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6886
6887 // Scan the instruction, looking for input operations that can be folded away.
6888 // If all input operands to the phi are the same instruction (e.g. a cast from
6889 // the same type or "+42") we can pull the operation through the PHI, reducing
6890 // code size and simplifying code.
6891 Constant *ConstantOp = 0;
6892 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00006893 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00006894 if (isa<CastInst>(FirstInst)) {
6895 CastSrcTy = FirstInst->getOperand(0)->getType();
6896 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006897 // Can fold binop or shift here if the RHS is a constant, otherwise call
6898 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00006899 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006900 if (ConstantOp == 0)
6901 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00006902 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6903 isVolatile = LI->isVolatile();
6904 // We can't sink the load if the loaded value could be modified between the
6905 // load and the PHI.
6906 if (LI->getParent() != PN.getIncomingBlock(0) ||
6907 !isSafeToSinkLoad(LI))
6908 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00006909 } else if (isa<GetElementPtrInst>(FirstInst)) {
6910 if (FirstInst->getNumOperands() == 2)
6911 return FoldPHIArgBinOpIntoPHI(PN);
6912 // Can't handle general GEPs yet.
6913 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006914 } else {
6915 return 0; // Cannot fold this operation.
6916 }
6917
6918 // Check to see if all arguments are the same operation.
6919 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6920 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6921 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6922 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6923 return 0;
6924 if (CastSrcTy) {
6925 if (I->getOperand(0)->getType() != CastSrcTy)
6926 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00006927 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6928 // We can't sink the load if the loaded value could be modified between the
6929 // load and the PHI.
6930 if (LI->isVolatile() != isVolatile ||
6931 LI->getParent() != PN.getIncomingBlock(i) ||
6932 !isSafeToSinkLoad(LI))
6933 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006934 } else if (I->getOperand(1) != ConstantOp) {
6935 return 0;
6936 }
6937 }
6938
6939 // Okay, they are all the same operation. Create a new PHI node of the
6940 // correct type, and PHI together all of the LHS's of the instructions.
6941 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6942 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006943 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006944
6945 Value *InVal = FirstInst->getOperand(0);
6946 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006947
6948 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006949 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6950 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6951 if (NewInVal != InVal)
6952 InVal = 0;
6953 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6954 }
6955
6956 Value *PhiVal;
6957 if (InVal) {
6958 // The new PHI unions all of the same values together. This is really
6959 // common, so we handle it intelligently here for compile-time speed.
6960 PhiVal = InVal;
6961 delete NewPN;
6962 } else {
6963 InsertNewInstBefore(NewPN, PN);
6964 PhiVal = NewPN;
6965 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006966
Chris Lattner7515cab2004-11-14 19:13:23 +00006967 // Insert and return the new operation.
6968 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006969 return new CastInst(PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00006970 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00006971 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00006972 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006973 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006974 else
6975 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006976 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006977}
Chris Lattner48a44f72002-05-02 17:06:02 +00006978
Chris Lattner71536432005-01-17 05:10:15 +00006979/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6980/// that is dead.
6981static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6982 if (PN->use_empty()) return true;
6983 if (!PN->hasOneUse()) return false;
6984
6985 // Remember this node, and if we find the cycle, return.
6986 if (!PotentiallyDeadPHIs.insert(PN).second)
6987 return true;
6988
6989 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6990 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006991
Chris Lattner71536432005-01-17 05:10:15 +00006992 return false;
6993}
6994
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006995// PHINode simplification
6996//
Chris Lattner113f4f42002-06-25 16:13:24 +00006997Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006998 // If LCSSA is around, don't mess with Phi nodes
6999 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007000
Owen Andersonae8aa642006-07-10 22:03:18 +00007001 if (Value *V = PN.hasConstantValue())
7002 return ReplaceInstUsesWith(PN, V);
7003
7004 // If the only user of this instruction is a cast instruction, and all of the
7005 // incoming values are constants, change this PHI to merge together the casted
7006 // constants.
7007 if (PN.hasOneUse())
7008 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7009 if (CI->getType() != PN.getType()) { // noop casts will be folded
7010 bool AllConstant = true;
7011 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7012 if (!isa<Constant>(PN.getIncomingValue(i))) {
7013 AllConstant = false;
7014 break;
7015 }
7016 if (AllConstant) {
7017 // Make a new PHI with all casted values.
7018 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7019 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7020 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7021 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7022 PN.getIncomingBlock(i));
7023 }
7024
7025 // Update the cast instruction.
7026 CI->setOperand(0, New);
7027 WorkList.push_back(CI); // revisit the cast instruction to fold.
7028 WorkList.push_back(New); // Make sure to revisit the new Phi
7029 return &PN; // PN is now dead!
7030 }
7031 }
7032
7033 // If all PHI operands are the same operation, pull them through the PHI,
7034 // reducing code size.
7035 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7036 PN.getIncomingValue(0)->hasOneUse())
7037 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7038 return Result;
7039
7040 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7041 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7042 // PHI)... break the cycle.
7043 if (PN.hasOneUse())
7044 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7045 std::set<PHINode*> PotentiallyDeadPHIs;
7046 PotentiallyDeadPHIs.insert(&PN);
7047 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7048 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7049 }
7050
Chris Lattner91daeb52003-12-19 05:58:40 +00007051 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007052}
7053
Chris Lattner69193f92004-04-05 01:30:19 +00007054static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7055 Instruction *InsertPoint,
7056 InstCombiner *IC) {
7057 unsigned PS = IC->getTargetData().getPointerSize();
7058 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007059 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7060 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007061 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7062 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007063}
7064
Chris Lattner48a44f72002-05-02 17:06:02 +00007065
Chris Lattner113f4f42002-06-25 16:13:24 +00007066Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007067 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007068 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007069 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007070 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007071 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007072
Chris Lattner81a7a232004-10-16 18:11:37 +00007073 if (isa<UndefValue>(GEP.getOperand(0)))
7074 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7075
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007076 bool HasZeroPointerIndex = false;
7077 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7078 HasZeroPointerIndex = C->isNullValue();
7079
7080 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007081 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007082
Chris Lattner69193f92004-04-05 01:30:19 +00007083 // Eliminate unneeded casts for indices.
7084 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007085 gep_type_iterator GTI = gep_type_begin(GEP);
7086 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7087 if (isa<SequentialType>(*GTI)) {
7088 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7089 Value *Src = CI->getOperand(0);
7090 const Type *SrcTy = Src->getType();
7091 const Type *DestTy = CI->getType();
7092 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007093 if (SrcTy->getPrimitiveSizeInBits() ==
7094 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007095 // We can always eliminate a cast from ulong or long to the other.
7096 // We can always eliminate a cast from uint to int or the other on
7097 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007098 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007099 MadeChange = true;
7100 GEP.setOperand(i, Src);
7101 }
7102 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7103 SrcTy->getPrimitiveSize() == 4) {
7104 // We can always eliminate a cast from int to [u]long. We can
7105 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7106 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007107 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007108 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007109 MadeChange = true;
7110 GEP.setOperand(i, Src);
7111 }
Chris Lattner69193f92004-04-05 01:30:19 +00007112 }
7113 }
7114 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007115 // If we are using a wider index than needed for this platform, shrink it
7116 // to what we need. If the incoming value needs a cast instruction,
7117 // insert it. This explicit cast can make subsequent optimizations more
7118 // obvious.
7119 Value *Op = GEP.getOperand(i);
7120 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007121 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007122 GEP.setOperand(i, ConstantExpr::getCast(C,
7123 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007124 MadeChange = true;
7125 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007126 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007127 GEP.setOperand(i, Op);
7128 MadeChange = true;
7129 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007130
7131 // If this is a constant idx, make sure to canonicalize it to be a signed
7132 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007133 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7134 if (CUI->getType()->isUnsigned()) {
7135 GEP.setOperand(i,
7136 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7137 MadeChange = true;
7138 }
Chris Lattner69193f92004-04-05 01:30:19 +00007139 }
7140 if (MadeChange) return &GEP;
7141
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007142 // Combine Indices - If the source pointer to this getelementptr instruction
7143 // is a getelementptr instruction, combine the indices of the two
7144 // getelementptr instructions into a single instruction.
7145 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007146 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007147 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007148 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007149
7150 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007151 // Note that if our source is a gep chain itself that we wait for that
7152 // chain to be resolved before we perform this transformation. This
7153 // avoids us creating a TON of code in some cases.
7154 //
7155 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7156 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7157 return 0; // Wait until our source is folded to completion.
7158
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007159 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007160
7161 // Find out whether the last index in the source GEP is a sequential idx.
7162 bool EndsWithSequential = false;
7163 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7164 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007165 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007166
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007167 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007168 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007169 // Replace: gep (gep %P, long B), long A, ...
7170 // With: T = long A+B; gep %P, T, ...
7171 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007172 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007173 if (SO1 == Constant::getNullValue(SO1->getType())) {
7174 Sum = GO1;
7175 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7176 Sum = SO1;
7177 } else {
7178 // If they aren't the same type, convert both to an integer of the
7179 // target's pointer size.
7180 if (SO1->getType() != GO1->getType()) {
7181 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7182 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7183 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7184 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7185 } else {
7186 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007187 if (SO1->getType()->getPrimitiveSize() == PS) {
7188 // Convert GO1 to SO1's type.
7189 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7190
7191 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7192 // Convert SO1 to GO1's type.
7193 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7194 } else {
7195 const Type *PT = TD->getIntPtrType();
7196 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7197 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7198 }
7199 }
7200 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007201 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7202 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7203 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007204 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7205 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007206 }
Chris Lattner69193f92004-04-05 01:30:19 +00007207 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007208
7209 // Recycle the GEP we already have if possible.
7210 if (SrcGEPOperands.size() == 2) {
7211 GEP.setOperand(0, SrcGEPOperands[0]);
7212 GEP.setOperand(1, Sum);
7213 return &GEP;
7214 } else {
7215 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7216 SrcGEPOperands.end()-1);
7217 Indices.push_back(Sum);
7218 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7219 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007220 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007221 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007222 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007223 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007224 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7225 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007226 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7227 }
7228
7229 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007230 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007231
Chris Lattner5f667a62004-05-07 22:09:22 +00007232 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007233 // GEP of global variable. If all of the indices for this GEP are
7234 // constants, we can promote this to a constexpr instead of an instruction.
7235
7236 // Scan for nonconstants...
7237 std::vector<Constant*> Indices;
7238 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7239 for (; I != E && isa<Constant>(*I); ++I)
7240 Indices.push_back(cast<Constant>(*I));
7241
7242 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007243 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007244
7245 // Replace all uses of the GEP with the new constexpr...
7246 return ReplaceInstUsesWith(GEP, CE);
7247 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007248 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7249 if (!isa<PointerType>(X->getType())) {
7250 // Not interesting. Source pointer must be a cast from pointer.
7251 } else if (HasZeroPointerIndex) {
7252 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7253 // into : GEP [10 x ubyte]* X, long 0, ...
7254 //
7255 // This occurs when the program declares an array extern like "int X[];"
7256 //
7257 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7258 const PointerType *XTy = cast<PointerType>(X->getType());
7259 if (const ArrayType *XATy =
7260 dyn_cast<ArrayType>(XTy->getElementType()))
7261 if (const ArrayType *CATy =
7262 dyn_cast<ArrayType>(CPTy->getElementType()))
7263 if (CATy->getElementType() == XATy->getElementType()) {
7264 // At this point, we know that the cast source type is a pointer
7265 // to an array of the same type as the destination pointer
7266 // array. Because the array type is never stepped over (there
7267 // is a leading zero) we can fold the cast into this GEP.
7268 GEP.setOperand(0, X);
7269 return &GEP;
7270 }
7271 } else if (GEP.getNumOperands() == 2) {
7272 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007273 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7274 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007275 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7276 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7277 if (isa<ArrayType>(SrcElTy) &&
7278 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7279 TD->getTypeSize(ResElTy)) {
7280 Value *V = InsertNewInstBefore(
7281 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7282 GEP.getOperand(1), GEP.getName()), GEP);
7283 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007284 }
Chris Lattner2a893292005-09-13 18:36:04 +00007285
7286 // Transform things like:
7287 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7288 // (where tmp = 8*tmp2) into:
7289 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7290
7291 if (isa<ArrayType>(SrcElTy) &&
7292 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7293 uint64_t ArrayEltSize =
7294 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7295
7296 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7297 // allow either a mul, shift, or constant here.
7298 Value *NewIdx = 0;
7299 ConstantInt *Scale = 0;
7300 if (ArrayEltSize == 1) {
7301 NewIdx = GEP.getOperand(1);
7302 Scale = ConstantInt::get(NewIdx->getType(), 1);
7303 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007304 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007305 Scale = CI;
7306 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7307 if (Inst->getOpcode() == Instruction::Shl &&
7308 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007309 unsigned ShAmt =
7310 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007311 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007312 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007313 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007314 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007315 NewIdx = Inst->getOperand(0);
7316 } else if (Inst->getOpcode() == Instruction::Mul &&
7317 isa<ConstantInt>(Inst->getOperand(1))) {
7318 Scale = cast<ConstantInt>(Inst->getOperand(1));
7319 NewIdx = Inst->getOperand(0);
7320 }
7321 }
7322
7323 // If the index will be to exactly the right offset with the scale taken
7324 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007325 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007326 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007327 Scale = ConstantInt::get(Scale->getType(),
7328 Scale->getZExtValue() / ArrayEltSize);
7329 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007330 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7331 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7332 NewIdx = InsertNewInstBefore(Sc, GEP);
7333 }
7334
7335 // Insert the new GEP instruction.
7336 Instruction *Idx =
7337 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7338 NewIdx, GEP.getName());
7339 Idx = InsertNewInstBefore(Idx, GEP);
7340 return new CastInst(Idx, GEP.getType());
7341 }
7342 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007343 }
Chris Lattnerca081252001-12-14 16:52:21 +00007344 }
7345
Chris Lattnerca081252001-12-14 16:52:21 +00007346 return 0;
7347}
7348
Chris Lattner1085bdf2002-11-04 16:18:53 +00007349Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7350 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7351 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007352 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7353 const Type *NewTy =
7354 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007355 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007356
7357 // Create and insert the replacement instruction...
7358 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007359 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007360 else {
7361 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007362 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007363 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007364
7365 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007366
Chris Lattner1085bdf2002-11-04 16:18:53 +00007367 // Scan to the end of the allocation instructions, to skip over a block of
7368 // allocas if possible...
7369 //
7370 BasicBlock::iterator It = New;
7371 while (isa<AllocationInst>(*It)) ++It;
7372
7373 // Now that I is pointing to the first non-allocation-inst in the block,
7374 // insert our getelementptr instruction...
7375 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007376 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7377 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7378 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007379
7380 // Now make everything use the getelementptr instead of the original
7381 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007382 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007383 } else if (isa<UndefValue>(AI.getArraySize())) {
7384 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007385 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007386
7387 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7388 // Note that we only do this for alloca's, because malloc should allocate and
7389 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007390 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007391 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007392 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7393
Chris Lattner1085bdf2002-11-04 16:18:53 +00007394 return 0;
7395}
7396
Chris Lattner8427bff2003-12-07 01:24:23 +00007397Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7398 Value *Op = FI.getOperand(0);
7399
7400 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7401 if (CastInst *CI = dyn_cast<CastInst>(Op))
7402 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7403 FI.setOperand(0, CI->getOperand(0));
7404 return &FI;
7405 }
7406
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007407 // free undef -> unreachable.
7408 if (isa<UndefValue>(Op)) {
7409 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007410 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007411 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7412 return EraseInstFromFunction(FI);
7413 }
7414
Chris Lattnerf3a36602004-02-28 04:57:37 +00007415 // If we have 'free null' delete the instruction. This can happen in stl code
7416 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007417 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007418 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007419
Chris Lattner8427bff2003-12-07 01:24:23 +00007420 return 0;
7421}
7422
7423
Chris Lattner72684fe2005-01-31 05:51:45 +00007424/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007425static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7426 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007427 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007428
7429 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007430 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007431 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007432
Chris Lattnerebca4762006-04-02 05:37:12 +00007433 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7434 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007435 // If the source is an array, the code below will not succeed. Check to
7436 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7437 // constants.
7438 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7439 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7440 if (ASrcTy->getNumElements() != 0) {
7441 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7442 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7443 SrcTy = cast<PointerType>(CastOp->getType());
7444 SrcPTy = SrcTy->getElementType();
7445 }
7446
Chris Lattnerebca4762006-04-02 05:37:12 +00007447 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7448 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007449 // Do not allow turning this into a load of an integer, which is then
7450 // casted to a pointer, this pessimizes pointer analysis a lot.
7451 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007452 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007453 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007454
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007455 // Okay, we are casting from one integer or pointer type to another of
7456 // the same size. Instead of casting the pointer before the load, cast
7457 // the result of the loaded value.
7458 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7459 CI->getName(),
7460 LI.isVolatile()),LI);
7461 // Now cast the result of the load.
7462 return new CastInst(NewLoad, LI.getType());
7463 }
Chris Lattner35e24772004-07-13 01:49:43 +00007464 }
7465 }
7466 return 0;
7467}
7468
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007469/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007470/// from this value cannot trap. If it is not obviously safe to load from the
7471/// specified pointer, we do a quick local scan of the basic block containing
7472/// ScanFrom, to determine if the address is already accessed.
7473static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7474 // If it is an alloca or global variable, it is always safe to load from.
7475 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7476
7477 // Otherwise, be a little bit agressive by scanning the local block where we
7478 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007479 // from/to. If so, the previous load or store would have already trapped,
7480 // so there is no harm doing an extra load (also, CSE will later eliminate
7481 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007482 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7483
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007484 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007485 --BBI;
7486
7487 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7488 if (LI->getOperand(0) == V) return true;
7489 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7490 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007491
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007492 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007493 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007494}
7495
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007496Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7497 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007498
Chris Lattnera9d84e32005-05-01 04:24:53 +00007499 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007500 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007501 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7502 return Res;
7503
7504 // None of the following transforms are legal for volatile loads.
7505 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007506
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007507 if (&LI.getParent()->front() != &LI) {
7508 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007509 // If the instruction immediately before this is a store to the same
7510 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007511 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7512 if (SI->getOperand(1) == LI.getOperand(0))
7513 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007514 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7515 if (LIB->getOperand(0) == LI.getOperand(0))
7516 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007517 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007518
7519 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7520 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7521 isa<UndefValue>(GEPI->getOperand(0))) {
7522 // Insert a new store to null instruction before the load to indicate
7523 // that this code is not reachable. We do this instead of inserting
7524 // an unreachable instruction directly because we cannot modify the
7525 // CFG.
7526 new StoreInst(UndefValue::get(LI.getType()),
7527 Constant::getNullValue(Op->getType()), &LI);
7528 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7529 }
7530
Chris Lattner81a7a232004-10-16 18:11:37 +00007531 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007532 // load null/undef -> undef
7533 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007534 // Insert a new store to null instruction before the load to indicate that
7535 // this code is not reachable. We do this instead of inserting an
7536 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007537 new StoreInst(UndefValue::get(LI.getType()),
7538 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007539 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007540 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007541
Chris Lattner81a7a232004-10-16 18:11:37 +00007542 // Instcombine load (constant global) into the value loaded.
7543 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7544 if (GV->isConstant() && !GV->isExternal())
7545 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007546
Chris Lattner81a7a232004-10-16 18:11:37 +00007547 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7548 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7549 if (CE->getOpcode() == Instruction::GetElementPtr) {
7550 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7551 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007552 if (Constant *V =
7553 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007554 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007555 if (CE->getOperand(0)->isNullValue()) {
7556 // Insert a new store to null instruction before the load to indicate
7557 // that this code is not reachable. We do this instead of inserting
7558 // an unreachable instruction directly because we cannot modify the
7559 // CFG.
7560 new StoreInst(UndefValue::get(LI.getType()),
7561 Constant::getNullValue(Op->getType()), &LI);
7562 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7563 }
7564
Chris Lattner81a7a232004-10-16 18:11:37 +00007565 } else if (CE->getOpcode() == Instruction::Cast) {
7566 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7567 return Res;
7568 }
7569 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007570
Chris Lattnera9d84e32005-05-01 04:24:53 +00007571 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007572 // Change select and PHI nodes to select values instead of addresses: this
7573 // helps alias analysis out a lot, allows many others simplifications, and
7574 // exposes redundancy in the code.
7575 //
7576 // Note that we cannot do the transformation unless we know that the
7577 // introduced loads cannot trap! Something like this is valid as long as
7578 // the condition is always false: load (select bool %C, int* null, int* %G),
7579 // but it would not be valid if we transformed it to load from null
7580 // unconditionally.
7581 //
7582 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7583 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007584 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7585 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007586 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007587 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007588 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007589 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007590 return new SelectInst(SI->getCondition(), V1, V2);
7591 }
7592
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007593 // load (select (cond, null, P)) -> load P
7594 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7595 if (C->isNullValue()) {
7596 LI.setOperand(0, SI->getOperand(2));
7597 return &LI;
7598 }
7599
7600 // load (select (cond, P, null)) -> load P
7601 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7602 if (C->isNullValue()) {
7603 LI.setOperand(0, SI->getOperand(1));
7604 return &LI;
7605 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007606 }
7607 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007608 return 0;
7609}
7610
Chris Lattner72684fe2005-01-31 05:51:45 +00007611/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7612/// when possible.
7613static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7614 User *CI = cast<User>(SI.getOperand(1));
7615 Value *CastOp = CI->getOperand(0);
7616
7617 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7618 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7619 const Type *SrcPTy = SrcTy->getElementType();
7620
7621 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7622 // If the source is an array, the code below will not succeed. Check to
7623 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7624 // constants.
7625 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7626 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7627 if (ASrcTy->getNumElements() != 0) {
7628 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7629 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7630 SrcTy = cast<PointerType>(CastOp->getType());
7631 SrcPTy = SrcTy->getElementType();
7632 }
7633
7634 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007635 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007636 IC.getTargetData().getTypeSize(DestPTy)) {
7637
7638 // Okay, we are casting from one integer or pointer type to another of
7639 // the same size. Instead of casting the pointer before the store, cast
7640 // the value to be stored.
7641 Value *NewCast;
7642 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7643 NewCast = ConstantExpr::getCast(C, SrcPTy);
7644 else
7645 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7646 SrcPTy,
7647 SI.getOperand(0)->getName()+".c"), SI);
7648
7649 return new StoreInst(NewCast, CastOp);
7650 }
7651 }
7652 }
7653 return 0;
7654}
7655
Chris Lattner31f486c2005-01-31 05:36:43 +00007656Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7657 Value *Val = SI.getOperand(0);
7658 Value *Ptr = SI.getOperand(1);
7659
7660 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007661 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007662 ++NumCombined;
7663 return 0;
7664 }
7665
Chris Lattner5997cf92006-02-08 03:25:32 +00007666 // Do really simple DSE, to catch cases where there are several consequtive
7667 // stores to the same location, separated by a few arithmetic operations. This
7668 // situation often occurs with bitfield accesses.
7669 BasicBlock::iterator BBI = &SI;
7670 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7671 --ScanInsts) {
7672 --BBI;
7673
7674 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7675 // Prev store isn't volatile, and stores to the same location?
7676 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7677 ++NumDeadStore;
7678 ++BBI;
7679 EraseInstFromFunction(*PrevSI);
7680 continue;
7681 }
7682 break;
7683 }
7684
Chris Lattnerdab43b22006-05-26 19:19:20 +00007685 // If this is a load, we have to stop. However, if the loaded value is from
7686 // the pointer we're loading and is producing the pointer we're storing,
7687 // then *this* store is dead (X = load P; store X -> P).
7688 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7689 if (LI == Val && LI->getOperand(0) == Ptr) {
7690 EraseInstFromFunction(SI);
7691 ++NumCombined;
7692 return 0;
7693 }
7694 // Otherwise, this is a load from some other location. Stores before it
7695 // may not be dead.
7696 break;
7697 }
7698
Chris Lattner5997cf92006-02-08 03:25:32 +00007699 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007700 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007701 break;
7702 }
7703
7704
7705 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007706
7707 // store X, null -> turns into 'unreachable' in SimplifyCFG
7708 if (isa<ConstantPointerNull>(Ptr)) {
7709 if (!isa<UndefValue>(Val)) {
7710 SI.setOperand(0, UndefValue::get(Val->getType()));
7711 if (Instruction *U = dyn_cast<Instruction>(Val))
7712 WorkList.push_back(U); // Dropped a use.
7713 ++NumCombined;
7714 }
7715 return 0; // Do not modify these!
7716 }
7717
7718 // store undef, Ptr -> noop
7719 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007720 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007721 ++NumCombined;
7722 return 0;
7723 }
7724
Chris Lattner72684fe2005-01-31 05:51:45 +00007725 // If the pointer destination is a cast, see if we can fold the cast into the
7726 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00007727 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00007728 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7729 return Res;
7730 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7731 if (CE->getOpcode() == Instruction::Cast)
7732 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7733 return Res;
7734
Chris Lattner219175c2005-09-12 23:23:25 +00007735
7736 // If this store is the last instruction in the basic block, and if the block
7737 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007738 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007739 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7740 if (BI->isUnconditional()) {
7741 // Check to see if the successor block has exactly two incoming edges. If
7742 // so, see if the other predecessor contains a store to the same location.
7743 // if so, insert a PHI node (if needed) and move the stores down.
7744 BasicBlock *Dest = BI->getSuccessor(0);
7745
7746 pred_iterator PI = pred_begin(Dest);
7747 BasicBlock *Other = 0;
7748 if (*PI != BI->getParent())
7749 Other = *PI;
7750 ++PI;
7751 if (PI != pred_end(Dest)) {
7752 if (*PI != BI->getParent())
7753 if (Other)
7754 Other = 0;
7755 else
7756 Other = *PI;
7757 if (++PI != pred_end(Dest))
7758 Other = 0;
7759 }
7760 if (Other) { // If only one other pred...
7761 BBI = Other->getTerminator();
7762 // Make sure this other block ends in an unconditional branch and that
7763 // there is an instruction before the branch.
7764 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7765 BBI != Other->begin()) {
7766 --BBI;
7767 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7768
7769 // If this instruction is a store to the same location.
7770 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7771 // Okay, we know we can perform this transformation. Insert a PHI
7772 // node now if we need it.
7773 Value *MergedVal = OtherStore->getOperand(0);
7774 if (MergedVal != SI.getOperand(0)) {
7775 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7776 PN->reserveOperandSpace(2);
7777 PN->addIncoming(SI.getOperand(0), SI.getParent());
7778 PN->addIncoming(OtherStore->getOperand(0), Other);
7779 MergedVal = InsertNewInstBefore(PN, Dest->front());
7780 }
7781
7782 // Advance to a place where it is safe to insert the new store and
7783 // insert it.
7784 BBI = Dest->begin();
7785 while (isa<PHINode>(BBI)) ++BBI;
7786 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7787 OtherStore->isVolatile()), *BBI);
7788
7789 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007790 EraseInstFromFunction(SI);
7791 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007792 ++NumCombined;
7793 return 0;
7794 }
7795 }
7796 }
7797 }
7798
Chris Lattner31f486c2005-01-31 05:36:43 +00007799 return 0;
7800}
7801
7802
Chris Lattner9eef8a72003-06-04 04:46:00 +00007803Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7804 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007805 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007806 BasicBlock *TrueDest;
7807 BasicBlock *FalseDest;
7808 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7809 !isa<Constant>(X)) {
7810 // Swap Destinations and condition...
7811 BI.setCondition(X);
7812 BI.setSuccessor(0, FalseDest);
7813 BI.setSuccessor(1, TrueDest);
7814 return &BI;
7815 }
7816
7817 // Cannonicalize setne -> seteq
7818 Instruction::BinaryOps Op; Value *Y;
7819 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7820 TrueDest, FalseDest)))
7821 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7822 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7823 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7824 std::string Name = I->getName(); I->setName("");
7825 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7826 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007827 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007828 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007829 BI.setSuccessor(0, FalseDest);
7830 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007831 removeFromWorkList(I);
7832 I->getParent()->getInstList().erase(I);
7833 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007834 return &BI;
7835 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007836
Chris Lattner9eef8a72003-06-04 04:46:00 +00007837 return 0;
7838}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007839
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007840Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7841 Value *Cond = SI.getCondition();
7842 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7843 if (I->getOpcode() == Instruction::Add)
7844 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7845 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7846 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007847 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007848 AddRHS));
7849 SI.setOperand(0, I->getOperand(0));
7850 WorkList.push_back(I);
7851 return &SI;
7852 }
7853 }
7854 return 0;
7855}
7856
Chris Lattner6bc98652006-03-05 00:22:33 +00007857/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7858/// is to leave as a vector operation.
7859static bool CheapToScalarize(Value *V, bool isConstant) {
7860 if (isa<ConstantAggregateZero>(V))
7861 return true;
7862 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7863 if (isConstant) return true;
7864 // If all elts are the same, we can extract.
7865 Constant *Op0 = C->getOperand(0);
7866 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7867 if (C->getOperand(i) != Op0)
7868 return false;
7869 return true;
7870 }
7871 Instruction *I = dyn_cast<Instruction>(V);
7872 if (!I) return false;
7873
7874 // Insert element gets simplified to the inserted element or is deleted if
7875 // this is constant idx extract element and its a constant idx insertelt.
7876 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7877 isa<ConstantInt>(I->getOperand(2)))
7878 return true;
7879 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7880 return true;
7881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7882 if (BO->hasOneUse() &&
7883 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7884 CheapToScalarize(BO->getOperand(1), isConstant)))
7885 return true;
7886
7887 return false;
7888}
7889
Chris Lattner12249be2006-05-25 23:48:38 +00007890/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7891/// elements into values that are larger than the #elts in the input.
7892static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7893 unsigned NElts = SVI->getType()->getNumElements();
7894 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7895 return std::vector<unsigned>(NElts, 0);
7896 if (isa<UndefValue>(SVI->getOperand(2)))
7897 return std::vector<unsigned>(NElts, 2*NElts);
7898
7899 std::vector<unsigned> Result;
7900 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7901 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7902 if (isa<UndefValue>(CP->getOperand(i)))
7903 Result.push_back(NElts*2); // undef -> 8
7904 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007905 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007906 return Result;
7907}
7908
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007909/// FindScalarElement - Given a vector and an element number, see if the scalar
7910/// value is already around as a register, for example if it were inserted then
7911/// extracted from the vector.
7912static Value *FindScalarElement(Value *V, unsigned EltNo) {
7913 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7914 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007915 unsigned Width = PTy->getNumElements();
7916 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007917 return UndefValue::get(PTy->getElementType());
7918
7919 if (isa<UndefValue>(V))
7920 return UndefValue::get(PTy->getElementType());
7921 else if (isa<ConstantAggregateZero>(V))
7922 return Constant::getNullValue(PTy->getElementType());
7923 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7924 return CP->getOperand(EltNo);
7925 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7926 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007927 if (!isa<ConstantInt>(III->getOperand(2)))
7928 return 0;
7929 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007930
7931 // If this is an insert to the element we are looking for, return the
7932 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007933 if (EltNo == IIElt)
7934 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007935
7936 // Otherwise, the insertelement doesn't modify the value, recurse on its
7937 // vector input.
7938 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007939 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007940 unsigned InEl = getShuffleMask(SVI)[EltNo];
7941 if (InEl < Width)
7942 return FindScalarElement(SVI->getOperand(0), InEl);
7943 else if (InEl < Width*2)
7944 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7945 else
7946 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007947 }
7948
7949 // Otherwise, we don't know.
7950 return 0;
7951}
7952
Robert Bocchinoa8352962006-01-13 22:48:06 +00007953Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007954
Chris Lattner92346c32006-03-31 18:25:14 +00007955 // If packed val is undef, replace extract with scalar undef.
7956 if (isa<UndefValue>(EI.getOperand(0)))
7957 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7958
7959 // If packed val is constant 0, replace extract with scalar 0.
7960 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7961 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7962
Robert Bocchinoa8352962006-01-13 22:48:06 +00007963 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7964 // If packed val is constant with uniform operands, replace EI
7965 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007966 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007967 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007968 if (C->getOperand(i) != op0) {
7969 op0 = 0;
7970 break;
7971 }
7972 if (op0)
7973 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007974 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007975
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007976 // If extracting a specified index from the vector, see if we can recursively
7977 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007978 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007979 // This instruction only demands the single element from the input vector.
7980 // If the input vector has a single use, simplify it based on this use
7981 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007982 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00007983 if (EI.getOperand(0)->hasOneUse()) {
7984 uint64_t UndefElts;
7985 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00007986 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00007987 UndefElts)) {
7988 EI.setOperand(0, V);
7989 return &EI;
7990 }
7991 }
7992
Reid Spencere0fc4df2006-10-20 07:07:24 +00007993 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007994 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007995 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007996
Chris Lattner83f65782006-05-25 22:53:38 +00007997 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007998 if (I->hasOneUse()) {
7999 // Push extractelement into predecessor operation if legal and
8000 // profitable to do so
8001 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008002 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8003 if (CheapToScalarize(BO, isConstantElt)) {
8004 ExtractElementInst *newEI0 =
8005 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8006 EI.getName()+".lhs");
8007 ExtractElementInst *newEI1 =
8008 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8009 EI.getName()+".rhs");
8010 InsertNewInstBefore(newEI0, EI);
8011 InsertNewInstBefore(newEI1, EI);
8012 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8013 }
Reid Spencerde46e482006-11-02 20:25:50 +00008014 } else if (isa<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008015 Value *Ptr = InsertCastBefore(I->getOperand(0),
8016 PointerType::get(EI.getType()), EI);
8017 GetElementPtrInst *GEP =
8018 new GetElementPtrInst(Ptr, EI.getOperand(1),
8019 I->getName() + ".gep");
8020 InsertNewInstBefore(GEP, EI);
8021 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008022 }
8023 }
8024 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8025 // Extracting the inserted element?
8026 if (IE->getOperand(2) == EI.getOperand(1))
8027 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8028 // If the inserted and extracted elements are constants, they must not
8029 // be the same value, extract from the pre-inserted value instead.
8030 if (isa<Constant>(IE->getOperand(2)) &&
8031 isa<Constant>(EI.getOperand(1))) {
8032 AddUsesToWorkList(EI);
8033 EI.setOperand(0, IE->getOperand(0));
8034 return &EI;
8035 }
8036 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8037 // If this is extracting an element from a shufflevector, figure out where
8038 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008039 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8040 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008041 Value *Src;
8042 if (SrcIdx < SVI->getType()->getNumElements())
8043 Src = SVI->getOperand(0);
8044 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8045 SrcIdx -= SVI->getType()->getNumElements();
8046 Src = SVI->getOperand(1);
8047 } else {
8048 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008049 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008050 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008051 }
8052 }
Chris Lattner83f65782006-05-25 22:53:38 +00008053 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008054 return 0;
8055}
8056
Chris Lattner90951862006-04-16 00:51:47 +00008057/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8058/// elements from either LHS or RHS, return the shuffle mask and true.
8059/// Otherwise, return false.
8060static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8061 std::vector<Constant*> &Mask) {
8062 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8063 "Invalid CollectSingleShuffleElements");
8064 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8065
8066 if (isa<UndefValue>(V)) {
8067 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8068 return true;
8069 } else if (V == LHS) {
8070 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008071 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008072 return true;
8073 } else if (V == RHS) {
8074 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008075 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008076 return true;
8077 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8078 // If this is an insert of an extract from some other vector, include it.
8079 Value *VecOp = IEI->getOperand(0);
8080 Value *ScalarOp = IEI->getOperand(1);
8081 Value *IdxOp = IEI->getOperand(2);
8082
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008083 if (!isa<ConstantInt>(IdxOp))
8084 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008085 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008086
8087 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8088 // Okay, we can handle this if the vector we are insertinting into is
8089 // transitively ok.
8090 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8091 // If so, update the mask to reflect the inserted undef.
8092 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8093 return true;
8094 }
8095 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8096 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008097 EI->getOperand(0)->getType() == V->getType()) {
8098 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008099 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008100
8101 // This must be extracting from either LHS or RHS.
8102 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8103 // Okay, we can handle this if the vector we are insertinting into is
8104 // transitively ok.
8105 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8106 // If so, update the mask to reflect the inserted value.
8107 if (EI->getOperand(0) == LHS) {
8108 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008109 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008110 } else {
8111 assert(EI->getOperand(0) == RHS);
8112 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008113 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008114
8115 }
8116 return true;
8117 }
8118 }
8119 }
8120 }
8121 }
8122 // TODO: Handle shufflevector here!
8123
8124 return false;
8125}
8126
8127/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8128/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8129/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008130static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008131 Value *&RHS) {
8132 assert(isa<PackedType>(V->getType()) &&
8133 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008134 "Invalid shuffle!");
8135 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8136
8137 if (isa<UndefValue>(V)) {
8138 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8139 return V;
8140 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008141 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008142 return V;
8143 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8144 // If this is an insert of an extract from some other vector, include it.
8145 Value *VecOp = IEI->getOperand(0);
8146 Value *ScalarOp = IEI->getOperand(1);
8147 Value *IdxOp = IEI->getOperand(2);
8148
8149 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8150 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8151 EI->getOperand(0)->getType() == V->getType()) {
8152 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008153 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8154 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008155
8156 // Either the extracted from or inserted into vector must be RHSVec,
8157 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008158 if (EI->getOperand(0) == RHS || RHS == 0) {
8159 RHS = EI->getOperand(0);
8160 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008161 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008162 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008163 return V;
8164 }
8165
Chris Lattner90951862006-04-16 00:51:47 +00008166 if (VecOp == RHS) {
8167 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008168 // Everything but the extracted element is replaced with the RHS.
8169 for (unsigned i = 0; i != NumElts; ++i) {
8170 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008171 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008172 }
8173 return V;
8174 }
Chris Lattner90951862006-04-16 00:51:47 +00008175
8176 // If this insertelement is a chain that comes from exactly these two
8177 // vectors, return the vector and the effective shuffle.
8178 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8179 return EI->getOperand(0);
8180
Chris Lattner39fac442006-04-15 01:39:45 +00008181 }
8182 }
8183 }
Chris Lattner90951862006-04-16 00:51:47 +00008184 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008185
8186 // Otherwise, can't do anything fancy. Return an identity vector.
8187 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008188 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008189 return V;
8190}
8191
8192Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8193 Value *VecOp = IE.getOperand(0);
8194 Value *ScalarOp = IE.getOperand(1);
8195 Value *IdxOp = IE.getOperand(2);
8196
8197 // If the inserted element was extracted from some other vector, and if the
8198 // indexes are constant, try to turn this into a shufflevector operation.
8199 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8200 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8201 EI->getOperand(0)->getType() == IE.getType()) {
8202 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008203 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8204 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008205
8206 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8207 return ReplaceInstUsesWith(IE, VecOp);
8208
8209 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8210 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8211
8212 // If we are extracting a value from a vector, then inserting it right
8213 // back into the same place, just use the input vector.
8214 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8215 return ReplaceInstUsesWith(IE, VecOp);
8216
8217 // We could theoretically do this for ANY input. However, doing so could
8218 // turn chains of insertelement instructions into a chain of shufflevector
8219 // instructions, and right now we do not merge shufflevectors. As such,
8220 // only do this in a situation where it is clear that there is benefit.
8221 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8222 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8223 // the values of VecOp, except then one read from EIOp0.
8224 // Build a new shuffle mask.
8225 std::vector<Constant*> Mask;
8226 if (isa<UndefValue>(VecOp))
8227 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8228 else {
8229 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008230 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008231 NumVectorElts));
8232 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008233 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008234 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8235 ConstantPacked::get(Mask));
8236 }
8237
8238 // If this insertelement isn't used by some other insertelement, turn it
8239 // (and any insertelements it points to), into one big shuffle.
8240 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8241 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008242 Value *RHS = 0;
8243 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8244 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8245 // We now have a shuffle of LHS, RHS, Mask.
8246 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008247 }
8248 }
8249 }
8250
8251 return 0;
8252}
8253
8254
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008255Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8256 Value *LHS = SVI.getOperand(0);
8257 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008258 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008259
8260 bool MadeChange = false;
8261
Chris Lattner2deeaea2006-10-05 06:55:50 +00008262 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008263 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008264 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8265
Chris Lattner39fac442006-04-15 01:39:45 +00008266 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8267 // the undef, change them to undefs.
8268
Chris Lattner12249be2006-05-25 23:48:38 +00008269 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8270 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8271 if (LHS == RHS || isa<UndefValue>(LHS)) {
8272 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008273 // shuffle(undef,undef,mask) -> undef.
8274 return ReplaceInstUsesWith(SVI, LHS);
8275 }
8276
Chris Lattner12249be2006-05-25 23:48:38 +00008277 // Remap any references to RHS to use LHS.
8278 std::vector<Constant*> Elts;
8279 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008280 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008281 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008282 else {
8283 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8284 (Mask[i] < e && isa<UndefValue>(LHS)))
8285 Mask[i] = 2*e; // Turn into undef.
8286 else
8287 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008288 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008289 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008290 }
Chris Lattner12249be2006-05-25 23:48:38 +00008291 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008292 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008293 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008294 LHS = SVI.getOperand(0);
8295 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008296 MadeChange = true;
8297 }
8298
Chris Lattner0e477162006-05-26 00:29:06 +00008299 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008300 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008301
Chris Lattner12249be2006-05-25 23:48:38 +00008302 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8303 if (Mask[i] >= e*2) continue; // Ignore undef values.
8304 // Is this an identity shuffle of the LHS value?
8305 isLHSID &= (Mask[i] == i);
8306
8307 // Is this an identity shuffle of the RHS value?
8308 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008309 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008310
Chris Lattner12249be2006-05-25 23:48:38 +00008311 // Eliminate identity shuffles.
8312 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8313 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008314
Chris Lattner0e477162006-05-26 00:29:06 +00008315 // If the LHS is a shufflevector itself, see if we can combine it with this
8316 // one without producing an unusual shuffle. Here we are really conservative:
8317 // we are absolutely afraid of producing a shuffle mask not in the input
8318 // program, because the code gen may not be smart enough to turn a merged
8319 // shuffle into two specific shuffles: it may produce worse code. As such,
8320 // we only merge two shuffles if the result is one of the two input shuffle
8321 // masks. In this case, merging the shuffles just removes one instruction,
8322 // which we know is safe. This is good for things like turning:
8323 // (splat(splat)) -> splat.
8324 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8325 if (isa<UndefValue>(RHS)) {
8326 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8327
8328 std::vector<unsigned> NewMask;
8329 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8330 if (Mask[i] >= 2*e)
8331 NewMask.push_back(2*e);
8332 else
8333 NewMask.push_back(LHSMask[Mask[i]]);
8334
8335 // If the result mask is equal to the src shuffle or this shuffle mask, do
8336 // the replacement.
8337 if (NewMask == LHSMask || NewMask == Mask) {
8338 std::vector<Constant*> Elts;
8339 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8340 if (NewMask[i] >= e*2) {
8341 Elts.push_back(UndefValue::get(Type::UIntTy));
8342 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008343 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008344 }
8345 }
8346 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8347 LHSSVI->getOperand(1),
8348 ConstantPacked::get(Elts));
8349 }
8350 }
8351 }
8352
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008353 return MadeChange ? &SVI : 0;
8354}
8355
8356
Robert Bocchinoa8352962006-01-13 22:48:06 +00008357
Chris Lattner99f48c62002-09-02 04:59:56 +00008358void InstCombiner::removeFromWorkList(Instruction *I) {
8359 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8360 WorkList.end());
8361}
8362
Chris Lattner39c98bb2004-12-08 23:43:58 +00008363
8364/// TryToSinkInstruction - Try to move the specified instruction from its
8365/// current block into the beginning of DestBlock, which can only happen if it's
8366/// safe to move the instruction past all of the instructions between it and the
8367/// end of its block.
8368static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8369 assert(I->hasOneUse() && "Invariants didn't hold!");
8370
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008371 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8372 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008373
Chris Lattner39c98bb2004-12-08 23:43:58 +00008374 // Do not sink alloca instructions out of the entry block.
8375 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8376 return false;
8377
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008378 // We can only sink load instructions if there is nothing between the load and
8379 // the end of block that could change the value.
8380 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008381 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8382 Scan != E; ++Scan)
8383 if (Scan->mayWriteToMemory())
8384 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008385 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008386
8387 BasicBlock::iterator InsertPos = DestBlock->begin();
8388 while (isa<PHINode>(InsertPos)) ++InsertPos;
8389
Chris Lattner9f269e42005-08-08 19:11:57 +00008390 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008391 ++NumSunkInst;
8392 return true;
8393}
8394
Chris Lattner1443bc52006-05-11 17:11:52 +00008395/// OptimizeConstantExpr - Given a constant expression and target data layout
8396/// information, symbolically evaluation the constant expr to something simpler
8397/// if possible.
8398static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8399 if (!TD) return CE;
8400
8401 Constant *Ptr = CE->getOperand(0);
8402 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8403 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8404 // If this is a constant expr gep that is effectively computing an
8405 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8406 bool isFoldableGEP = true;
8407 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8408 if (!isa<ConstantInt>(CE->getOperand(i)))
8409 isFoldableGEP = false;
8410 if (isFoldableGEP) {
8411 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8412 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008413 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008414 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8415 return ConstantExpr::getCast(C, CE->getType());
8416 }
8417 }
8418
8419 return CE;
8420}
8421
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008422
8423/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8424/// all reachable code to the worklist.
8425///
8426/// This has a couple of tricks to make the code faster and more powerful. In
8427/// particular, we constant fold and DCE instructions as we go, to avoid adding
8428/// them to the worklist (this significantly speeds up instcombine on code where
8429/// many instructions are dead or constant). Additionally, if we find a branch
8430/// whose condition is a known constant, we only visit the reachable successors.
8431///
8432static void AddReachableCodeToWorklist(BasicBlock *BB,
8433 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008434 std::vector<Instruction*> &WorkList,
8435 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008436 // We have now visited this block! If we've already been here, bail out.
8437 if (!Visited.insert(BB).second) return;
8438
8439 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8440 Instruction *Inst = BBI++;
8441
8442 // DCE instruction if trivially dead.
8443 if (isInstructionTriviallyDead(Inst)) {
8444 ++NumDeadInst;
8445 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8446 Inst->eraseFromParent();
8447 continue;
8448 }
8449
8450 // ConstantProp instruction if trivially constant.
8451 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008452 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8453 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008454 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8455 Inst->replaceAllUsesWith(C);
8456 ++NumConstProp;
8457 Inst->eraseFromParent();
8458 continue;
8459 }
8460
8461 WorkList.push_back(Inst);
8462 }
8463
8464 // Recursively visit successors. If this is a branch or switch on a constant,
8465 // only visit the reachable successor.
8466 TerminatorInst *TI = BB->getTerminator();
8467 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8468 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8469 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008470 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8471 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008472 return;
8473 }
8474 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8475 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8476 // See if this is an explicit destination.
8477 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8478 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008479 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008480 return;
8481 }
8482
8483 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008484 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008485 return;
8486 }
8487 }
8488
8489 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008490 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008491}
8492
Chris Lattner113f4f42002-06-25 16:13:24 +00008493bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008494 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008495 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008496
Chris Lattner4ed40f72005-07-07 20:40:38 +00008497 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008498 // Do a depth-first traversal of the function, populate the worklist with
8499 // the reachable instructions. Ignore blocks that are not reachable. Keep
8500 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008501 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008502 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008503
Chris Lattner4ed40f72005-07-07 20:40:38 +00008504 // Do a quick scan over the function. If we find any blocks that are
8505 // unreachable, remove any instructions inside of them. This prevents
8506 // the instcombine code from having to deal with some bad special cases.
8507 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8508 if (!Visited.count(BB)) {
8509 Instruction *Term = BB->getTerminator();
8510 while (Term != BB->begin()) { // Remove instrs bottom-up
8511 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008512
Chris Lattner4ed40f72005-07-07 20:40:38 +00008513 DEBUG(std::cerr << "IC: DCE: " << *I);
8514 ++NumDeadInst;
8515
8516 if (!I->use_empty())
8517 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8518 I->eraseFromParent();
8519 }
8520 }
8521 }
Chris Lattnerca081252001-12-14 16:52:21 +00008522
8523 while (!WorkList.empty()) {
8524 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8525 WorkList.pop_back();
8526
Chris Lattner1443bc52006-05-11 17:11:52 +00008527 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008528 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008529 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008530 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008531 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008532 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008533
Chris Lattnercd517ff2005-01-28 19:32:01 +00008534 DEBUG(std::cerr << "IC: DCE: " << *I);
8535
8536 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008537 removeFromWorkList(I);
8538 continue;
8539 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008540
Chris Lattner1443bc52006-05-11 17:11:52 +00008541 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008542 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008543 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8544 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008545 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8546
Chris Lattner1443bc52006-05-11 17:11:52 +00008547 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008548 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008549 ReplaceInstUsesWith(*I, C);
8550
Chris Lattner99f48c62002-09-02 04:59:56 +00008551 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008552 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008553 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008554 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008555 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008556
Chris Lattner39c98bb2004-12-08 23:43:58 +00008557 // See if we can trivially sink this instruction to a successor basic block.
8558 if (I->hasOneUse()) {
8559 BasicBlock *BB = I->getParent();
8560 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8561 if (UserParent != BB) {
8562 bool UserIsSuccessor = false;
8563 // See if the user is one of our successors.
8564 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8565 if (*SI == UserParent) {
8566 UserIsSuccessor = true;
8567 break;
8568 }
8569
8570 // If the user is one of our immediate successors, and if that successor
8571 // only has us as a predecessors (we'd have to split the critical edge
8572 // otherwise), we can keep going.
8573 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8574 next(pred_begin(UserParent)) == pred_end(UserParent))
8575 // Okay, the CFG is simple enough, try to sink this instruction.
8576 Changed |= TryToSinkInstruction(I, UserParent);
8577 }
8578 }
8579
Chris Lattnerca081252001-12-14 16:52:21 +00008580 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008581 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008582 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008583 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008584 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008585 DEBUG(std::cerr << "IC: Old = " << *I
8586 << " New = " << *Result);
8587
Chris Lattner396dbfe2004-06-09 05:08:07 +00008588 // Everything uses the new instruction now.
8589 I->replaceAllUsesWith(Result);
8590
8591 // Push the new instruction and any users onto the worklist.
8592 WorkList.push_back(Result);
8593 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008594
8595 // Move the name to the new instruction first...
8596 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008597 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008598
8599 // Insert the new instruction into the basic block...
8600 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008601 BasicBlock::iterator InsertPos = I;
8602
8603 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8604 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8605 ++InsertPos;
8606
8607 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008608
Chris Lattner63d75af2004-05-01 23:27:23 +00008609 // Make sure that we reprocess all operands now that we reduced their
8610 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008611 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8612 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8613 WorkList.push_back(OpI);
8614
Chris Lattner396dbfe2004-06-09 05:08:07 +00008615 // Instructions can end up on the worklist more than once. Make sure
8616 // we do not process an instruction that has been deleted.
8617 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008618
8619 // Erase the old instruction.
8620 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008621 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008622 DEBUG(std::cerr << "IC: MOD = " << *I);
8623
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008624 // If the instruction was modified, it's possible that it is now dead.
8625 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008626 if (isInstructionTriviallyDead(I)) {
8627 // Make sure we process all operands now that we are reducing their
8628 // use counts.
8629 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8630 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8631 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008632
Chris Lattner63d75af2004-05-01 23:27:23 +00008633 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008634 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008635 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008636 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008637 } else {
8638 WorkList.push_back(Result);
8639 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008640 }
Chris Lattner053c0932002-05-14 15:24:07 +00008641 }
Chris Lattner260ab202002-04-18 17:39:14 +00008642 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008643 }
8644 }
8645
Chris Lattner260ab202002-04-18 17:39:14 +00008646 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008647}
8648
Brian Gaeke38b79e82004-07-27 17:43:21 +00008649FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008650 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008651}
Brian Gaeke960707c2003-11-11 22:41:34 +00008652