blob: 2e3f9aaa10985c0ab9888e859503a6d0de783754 [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;
Reid Spencerfdff9382006-11-08 06:47:33 +0000734 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000735 // (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
Reid Spencerfdff9382006-11-08 06:47:33 +0000742 // Unsigned shift right.
743 Mask <<= ShiftAmt;
744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
746 KnownZero >>= ShiftAmt;
747 KnownOne >>= ShiftAmt;
748 KnownZero |= HighBits; // high bits known zero.
749 return;
750 }
751 break;
752 case Instruction::AShr:
753 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
754 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
755 // Compute the new bits that are at the top now.
756 uint64_t ShiftAmt = SA->getZExtValue();
757 uint64_t HighBits = (1ULL << ShiftAmt)-1;
758 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
759
760 // Signed shift right.
761 Mask <<= ShiftAmt;
762 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
763 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
764 KnownZero >>= ShiftAmt;
765 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000766
Reid Spencerfdff9382006-11-08 06:47:33 +0000767 // Handle the sign bits.
768 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
769 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770
Reid Spencerfdff9382006-11-08 06:47:33 +0000771 if (KnownZero & SignBit) { // New bits are known zero.
772 KnownZero |= HighBits;
773 } else if (KnownOne & SignBit) { // New bits are known one.
774 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000775 }
776 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000777 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000778 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000779 }
Chris Lattner92a68652006-02-07 08:05:22 +0000780}
781
782/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
783/// this predicate to simplify operations downstream. Mask is known to be zero
784/// for bits that V cannot have.
785static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000786 uint64_t KnownZero, KnownOne;
787 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
788 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
789 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000790}
791
Chris Lattner0157e7f2006-02-11 09:31:47 +0000792/// ShrinkDemandedConstant - Check to see if the specified operand of the
793/// specified instruction is a constant integer. If so, check to see if there
794/// are any bits set in the constant that are not demanded. If so, shrink the
795/// constant and return true.
796static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
797 uint64_t Demanded) {
798 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
799 if (!OpC) return false;
800
801 // If there are no bits set that aren't demanded, nothing to do.
802 if ((~Demanded & OpC->getZExtValue()) == 0)
803 return false;
804
805 // This is producing any bits that are not needed, shrink the RHS.
806 uint64_t Val = Demanded & OpC->getZExtValue();
807 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
808 return true;
809}
810
Chris Lattneree0f2802006-02-12 02:07:56 +0000811// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
812// set of known zero and one bits, compute the maximum and minimum values that
813// could have the specified known zero and known one bits, returning them in
814// min/max.
815static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
816 uint64_t KnownZero,
817 uint64_t KnownOne,
818 int64_t &Min, int64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821
822 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
823
824 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
825 // bit if it is unknown.
826 Min = KnownOne;
827 Max = KnownOne|UnknownBits;
828
829 if (SignBit & UnknownBits) { // Sign bit is unknown
830 Min |= SignBit;
831 Max &= ~SignBit;
832 }
833
834 // Sign extend the min/max values.
835 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
836 Min = (Min << ShAmt) >> ShAmt;
837 Max = (Max << ShAmt) >> ShAmt;
838}
839
840// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
841// a set of known zero and one bits, compute the maximum and minimum values that
842// could have the specified known zero and known one bits, returning them in
843// min/max.
844static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
845 uint64_t KnownZero,
846 uint64_t KnownOne,
847 uint64_t &Min,
848 uint64_t &Max) {
849 uint64_t TypeBits = Ty->getIntegralTypeMask();
850 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
851
852 // The minimum value is when the unknown bits are all zeros.
853 Min = KnownOne;
854 // The maximum value is when the unknown bits are all ones.
855 Max = KnownOne|UnknownBits;
856}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857
858
859/// SimplifyDemandedBits - Look at V. At this point, we know that only the
860/// DemandedMask bits of the result of V are ever used downstream. If we can
861/// use this information to simplify V, do so and return true. Otherwise,
862/// analyze the expression and return a mask of KnownOne and KnownZero bits for
863/// the expression (used to simplify the caller). The KnownZero/One bits may
864/// only be accurate for those bits in the DemandedMask.
865bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
866 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000867 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
869 // We know all of the bits for a constant!
870 KnownOne = CI->getZExtValue() & DemandedMask;
871 KnownZero = ~KnownOne & DemandedMask;
872 return false;
873 }
874
875 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000876 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000877 if (Depth != 0) { // Not at the root.
878 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
879 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000880 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 }
Chris Lattner2590e512006-02-07 06:56:34 +0000882 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000883 // just set the DemandedMask to all bits.
884 DemandedMask = V->getType()->getIntegralTypeMask();
885 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000886 if (V != UndefValue::get(V->getType()))
887 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
888 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000889 } else if (Depth == 6) { // Limit search depth.
890 return false;
891 }
892
893 Instruction *I = dyn_cast<Instruction>(V);
894 if (!I) return false; // Only analyze instructions.
895
Chris Lattnerfb296922006-05-04 17:33:35 +0000896 DemandedMask &= V->getType()->getIntegralTypeMask();
897
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000899 switch (I->getOpcode()) {
900 default: break;
901 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 // If either the LHS or the RHS are Zero, the result is zero.
903 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
904 KnownZero, KnownOne, Depth+1))
905 return true;
906 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
907
908 // If something is known zero on the RHS, the bits aren't demanded on the
909 // LHS.
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
911 KnownZero2, KnownOne2, Depth+1))
912 return true;
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914
915 // If all of the demanded bits are known one on one side, return the other.
916 // These bits cannot contribute to the result of the 'and'.
917 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
918 return UpdateValueUsesWith(I, I->getOperand(0));
919 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
920 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000921
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
924 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
925
Chris Lattner0157e7f2006-02-11 09:31:47 +0000926 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000927 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000928 return UpdateValueUsesWith(I, I);
929
930 // Output known-1 bits are only known if set in both the LHS & RHS.
931 KnownOne &= KnownOne2;
932 // Output known-0 are known to be clear if zero in either the LHS | RHS.
933 KnownZero |= KnownZero2;
934 break;
935 case Instruction::Or:
936 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
937 KnownZero, KnownOne, Depth+1))
938 return true;
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
941 KnownZero2, KnownOne2, Depth+1))
942 return true;
943 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
944
945 // If all of the demanded bits are known zero on one side, return the other.
946 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000947 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000948 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000949 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000950 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000951
952 // If all of the potentially set bits on one side are known to be set on
953 // the other side, just use the 'other' side.
954 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
955 (DemandedMask & (~KnownZero)))
956 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000957 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
958 (DemandedMask & (~KnownZero2)))
959 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000960
961 // If the RHS is a constant, see if we can simplify it.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
964
965 // Output known-0 bits are only known if clear in both the LHS & RHS.
966 KnownZero &= KnownZero2;
967 // Output known-1 are known to be set if set in either the LHS | RHS.
968 KnownOne |= KnownOne2;
969 break;
970 case Instruction::Xor: {
971 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
972 KnownZero, KnownOne, Depth+1))
973 return true;
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
976 KnownZero2, KnownOne2, Depth+1))
977 return true;
978 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'xor'.
982 if ((DemandedMask & KnownZero) == DemandedMask)
983 return UpdateValueUsesWith(I, I->getOperand(0));
984 if ((DemandedMask & KnownZero2) == DemandedMask)
985 return UpdateValueUsesWith(I, I->getOperand(1));
986
987 // Output known-0 bits are known if clear or set in both the LHS & RHS.
988 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
989 // Output known-1 are known to be set if set in only one of the LHS, RHS.
990 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
991
992 // If all of the unknown bits are known to be zero on one side or the other
993 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000994 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000995 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
996 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
997 Instruction *Or =
998 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
999 I->getName());
1000 InsertNewInstBefore(Or, *I);
1001 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001002 }
1003 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004
Chris Lattner5b2edb12006-02-12 08:02:11 +00001005 // If all of the demanded bits on one side are known, and all of the set
1006 // bits on that side are also known to be set on the other side, turn this
1007 // into an AND, as we know the bits will be cleared.
1008 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1009 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1010 if ((KnownOne & KnownOne2) == KnownOne) {
1011 Constant *AndC = GetConstantInType(I->getType(),
1012 ~KnownOne & DemandedMask);
1013 Instruction *And =
1014 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1015 InsertNewInstBefore(And, *I);
1016 return UpdateValueUsesWith(I, And);
1017 }
1018 }
1019
Chris Lattner0157e7f2006-02-11 09:31:47 +00001020 // If the RHS is a constant, see if we can simplify it.
1021 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024
1025 KnownZero = KnownZeroOut;
1026 KnownOne = KnownOneOut;
1027 break;
1028 }
1029 case Instruction::Select:
1030 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1031 KnownZero, KnownOne, Depth+1))
1032 return true;
1033 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1034 KnownZero2, KnownOne2, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1038
1039 // If the operands are constants, see if we can simplify them.
1040 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1041 return UpdateValueUsesWith(I, I);
1042 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return UpdateValueUsesWith(I, I);
1044
1045 // Only known if known in both the LHS and RHS.
1046 KnownOne &= KnownOne2;
1047 KnownZero &= KnownZero2;
1048 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001049 case Instruction::Cast: {
1050 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001052
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053 // If this is an integer truncate or noop, just look in the input.
1054 if (SrcTy->getPrimitiveSizeInBits() >=
1055 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001056 // Cast to bool is a comparison against 0, which demands all bits. We
1057 // can't propagate anything useful up.
1058 if (I->getType() == Type::BoolTy)
1059 break;
1060
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1062 KnownZero, KnownOne, Depth+1))
1063 return true;
1064 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1065 break;
1066 }
1067
1068 // Sign or Zero extension. Compute the bits in the result that are not
1069 // present in the input.
1070 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1071 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1072
1073 // Handle zero extension.
1074 if (!SrcTy->isSigned()) {
1075 DemandedMask &= SrcTy->getIntegralTypeMask();
1076 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1077 KnownZero, KnownOne, Depth+1))
1078 return true;
1079 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1080 // The top bits are known to be zero.
1081 KnownZero |= NewBits;
1082 } else {
1083 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001084 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1085 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1086
1087 // If any of the sign extended bits are demanded, we know that the sign
1088 // bit is demanded.
1089 if (NewBits & DemandedMask)
1090 InputDemandedBits |= InSignBit;
1091
1092 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001093 KnownZero, KnownOne, Depth+1))
1094 return true;
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1096
1097 // If the sign bit of the input is known set or clear, then we know the
1098 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001099
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100 // If the input sign bit is known zero, or if the NewBits are not demanded
1101 // convert this into a zero extension.
1102 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001103 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001104 Value *NewVal =
1105 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001106 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001108 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001109 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001110 } else if (KnownOne & InSignBit) { // Input sign bit known set
1111 KnownOne |= NewBits;
1112 KnownZero &= ~NewBits;
1113 } else { // Input sign bit unknown
1114 KnownZero &= ~NewBits;
1115 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001116 }
Chris Lattner2590e512006-02-07 06:56:34 +00001117 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001118 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001119 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001120 case Instruction::Add:
1121 // If there is a constant on the RHS, there are a variety of xformations
1122 // we can do.
1123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1124 // If null, this should be simplified elsewhere. Some of the xforms here
1125 // won't work if the RHS is zero.
1126 if (RHS->isNullValue())
1127 break;
1128
1129 // Figure out what the input bits are. If the top bits of the and result
1130 // are not demanded, then the add doesn't demand them from its input
1131 // either.
1132
1133 // Shift the demanded mask up so that it's at the top of the uint64_t.
1134 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1135 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1136
1137 // If the top bit of the output is demanded, demand everything from the
1138 // input. Otherwise, we demand all the input bits except NLZ top bits.
1139 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1140
1141 // Find information about known zero/one bits in the input.
1142 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1143 KnownZero2, KnownOne2, Depth+1))
1144 return true;
1145
1146 // If the RHS of the add has bits set that can't affect the input, reduce
1147 // the constant.
1148 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1149 return UpdateValueUsesWith(I, I);
1150
1151 // Avoid excess work.
1152 if (KnownZero2 == 0 && KnownOne2 == 0)
1153 break;
1154
1155 // Turn it into OR if input bits are zero.
1156 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1157 Instruction *Or =
1158 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1159 I->getName());
1160 InsertNewInstBefore(Or, *I);
1161 return UpdateValueUsesWith(I, Or);
1162 }
1163
1164 // We can say something about the output known-zero and known-one bits,
1165 // depending on potential carries from the input constant and the
1166 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1167 // bits set and the RHS constant is 0x01001, then we know we have a known
1168 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1169
1170 // To compute this, we first compute the potential carry bits. These are
1171 // the bits which may be modified. I'm not aware of a better way to do
1172 // this scan.
1173 uint64_t RHSVal = RHS->getZExtValue();
1174
1175 bool CarryIn = false;
1176 uint64_t CarryBits = 0;
1177 uint64_t CurBit = 1;
1178 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1179 // Record the current carry in.
1180 if (CarryIn) CarryBits |= CurBit;
1181
1182 bool CarryOut;
1183
1184 // This bit has a carry out unless it is "zero + zero" or
1185 // "zero + anything" with no carry in.
1186 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1187 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1188 } else if (!CarryIn &&
1189 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1190 CarryOut = false; // 0 + anything has no carry out if no carry in.
1191 } else {
1192 // Otherwise, we have to assume we have a carry out.
1193 CarryOut = true;
1194 }
1195
1196 // This stage's carry out becomes the next stage's carry-in.
1197 CarryIn = CarryOut;
1198 }
1199
1200 // Now that we know which bits have carries, compute the known-1/0 sets.
1201
1202 // Bits are known one if they are known zero in one operand and one in the
1203 // other, and there is no input carry.
1204 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1205
1206 // Bits are known zero if they are known zero in both operands and there
1207 // is no input carry.
1208 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1209 }
1210 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001211 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001212 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1213 uint64_t ShiftAmt = SA->getZExtValue();
1214 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001215 KnownZero, KnownOne, Depth+1))
1216 return true;
1217 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001218 KnownZero <<= ShiftAmt;
1219 KnownOne <<= ShiftAmt;
1220 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001221 }
Chris Lattner2590e512006-02-07 06:56:34 +00001222 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001223 case Instruction::LShr:
1224 // For a logical shift right
1225 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1226 unsigned ShiftAmt = SA->getZExtValue();
1227
1228 // Compute the new bits that are at the top now.
1229 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1230 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1231 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1232 // Unsigned shift right.
1233 if (SimplifyDemandedBits(I->getOperand(0),
1234 (DemandedMask << ShiftAmt) & TypeMask,
1235 KnownZero, KnownOne, Depth+1))
1236 return true;
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 KnownZero &= TypeMask;
1239 KnownOne &= TypeMask;
1240 KnownZero >>= ShiftAmt;
1241 KnownOne >>= ShiftAmt;
1242 KnownZero |= HighBits; // high bits known zero.
1243 }
1244 break;
1245 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001246 // If this is an arithmetic shift right and only the low-bit is set, we can
1247 // always convert this into a logical shr, even if the shift amount is
1248 // variable. The low bit of the shift cannot be an input sign bit unless
1249 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001250 if (DemandedMask == 1) {
1251 // Perform the logical shift right.
1252 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1253 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001254 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001255 return UpdateValueUsesWith(I, NewVal);
1256 }
1257
Reid Spencere0fc4df2006-10-20 07:07:24 +00001258 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001260
1261 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001262 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1263 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001264 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001265 // Signed shift right.
1266 if (SimplifyDemandedBits(I->getOperand(0),
1267 (DemandedMask << ShiftAmt) & TypeMask,
1268 KnownZero, KnownOne, Depth+1))
1269 return true;
1270 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1271 KnownZero &= TypeMask;
1272 KnownOne &= TypeMask;
1273 KnownZero >>= ShiftAmt;
1274 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001275
Reid Spencerfdff9382006-11-08 06:47:33 +00001276 // Handle the sign bits.
1277 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1278 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001279
Reid Spencerfdff9382006-11-08 06:47:33 +00001280 // If the input sign bit is known to be zero, or if none of the top bits
1281 // are demanded, turn this into an unsigned shift right.
1282 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1283 // Perform the logical shift right.
1284 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1285 SA, I->getName());
1286 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1287 return UpdateValueUsesWith(I, NewVal);
1288 } else if (KnownOne & SignBit) { // New bits are known one.
1289 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001290 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001291 }
Chris Lattner2590e512006-02-07 06:56:34 +00001292 break;
1293 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001294
1295 // If the client is only demanding bits that we know, return the known
1296 // constant.
1297 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1298 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001299 return false;
1300}
1301
Chris Lattner2deeaea2006-10-05 06:55:50 +00001302
1303/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1304/// 64 or fewer elements. DemandedElts contains the set of elements that are
1305/// actually used by the caller. This method analyzes which elements of the
1306/// operand are undef and returns that information in UndefElts.
1307///
1308/// If the information about demanded elements can be used to simplify the
1309/// operation, the operation is simplified, then the resultant value is
1310/// returned. This returns null if no change was made.
1311Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1312 uint64_t &UndefElts,
1313 unsigned Depth) {
1314 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1315 assert(VWidth <= 64 && "Vector too wide to analyze!");
1316 uint64_t EltMask = ~0ULL >> (64-VWidth);
1317 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1318 "Invalid DemandedElts!");
1319
1320 if (isa<UndefValue>(V)) {
1321 // If the entire vector is undefined, just return this info.
1322 UndefElts = EltMask;
1323 return 0;
1324 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1325 UndefElts = EltMask;
1326 return UndefValue::get(V->getType());
1327 }
1328
1329 UndefElts = 0;
1330 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1331 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1332 Constant *Undef = UndefValue::get(EltTy);
1333
1334 std::vector<Constant*> Elts;
1335 for (unsigned i = 0; i != VWidth; ++i)
1336 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1337 Elts.push_back(Undef);
1338 UndefElts |= (1ULL << i);
1339 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1340 Elts.push_back(Undef);
1341 UndefElts |= (1ULL << i);
1342 } else { // Otherwise, defined.
1343 Elts.push_back(CP->getOperand(i));
1344 }
1345
1346 // If we changed the constant, return it.
1347 Constant *NewCP = ConstantPacked::get(Elts);
1348 return NewCP != CP ? NewCP : 0;
1349 } else if (isa<ConstantAggregateZero>(V)) {
1350 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1351 // set to undef.
1352 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1353 Constant *Zero = Constant::getNullValue(EltTy);
1354 Constant *Undef = UndefValue::get(EltTy);
1355 std::vector<Constant*> Elts;
1356 for (unsigned i = 0; i != VWidth; ++i)
1357 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1358 UndefElts = DemandedElts ^ EltMask;
1359 return ConstantPacked::get(Elts);
1360 }
1361
1362 if (!V->hasOneUse()) { // Other users may use these bits.
1363 if (Depth != 0) { // Not at the root.
1364 // TODO: Just compute the UndefElts information recursively.
1365 return false;
1366 }
1367 return false;
1368 } else if (Depth == 10) { // Limit search depth.
1369 return false;
1370 }
1371
1372 Instruction *I = dyn_cast<Instruction>(V);
1373 if (!I) return false; // Only analyze instructions.
1374
1375 bool MadeChange = false;
1376 uint64_t UndefElts2;
1377 Value *TmpV;
1378 switch (I->getOpcode()) {
1379 default: break;
1380
1381 case Instruction::InsertElement: {
1382 // If this is a variable index, we don't know which element it overwrites.
1383 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001384 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001385 if (Idx == 0) {
1386 // Note that we can't propagate undef elt info, because we don't know
1387 // which elt is getting updated.
1388 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1389 UndefElts2, Depth+1);
1390 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1391 break;
1392 }
1393
1394 // If this is inserting an element that isn't demanded, remove this
1395 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001396 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001397 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1398 return AddSoonDeadInstToWorklist(*I, 0);
1399
1400 // Otherwise, the element inserted overwrites whatever was there, so the
1401 // input demanded set is simpler than the output set.
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1403 DemandedElts & ~(1ULL << IdxNo),
1404 UndefElts, Depth+1);
1405 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1406
1407 // The inserted element is defined.
1408 UndefElts |= 1ULL << IdxNo;
1409 break;
1410 }
1411
1412 case Instruction::And:
1413 case Instruction::Or:
1414 case Instruction::Xor:
1415 case Instruction::Add:
1416 case Instruction::Sub:
1417 case Instruction::Mul:
1418 // div/rem demand all inputs, because they don't want divide by zero.
1419 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1420 UndefElts, Depth+1);
1421 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1422 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1423 UndefElts2, Depth+1);
1424 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1425
1426 // Output elements are undefined if both are undefined. Consider things
1427 // like undef&0. The result is known zero, not undef.
1428 UndefElts &= UndefElts2;
1429 break;
1430
1431 case Instruction::Call: {
1432 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1433 if (!II) break;
1434 switch (II->getIntrinsicID()) {
1435 default: break;
1436
1437 // Binary vector operations that work column-wise. A dest element is a
1438 // function of the corresponding input elements from the two inputs.
1439 case Intrinsic::x86_sse_sub_ss:
1440 case Intrinsic::x86_sse_mul_ss:
1441 case Intrinsic::x86_sse_min_ss:
1442 case Intrinsic::x86_sse_max_ss:
1443 case Intrinsic::x86_sse2_sub_sd:
1444 case Intrinsic::x86_sse2_mul_sd:
1445 case Intrinsic::x86_sse2_min_sd:
1446 case Intrinsic::x86_sse2_max_sd:
1447 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1448 UndefElts, Depth+1);
1449 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1450 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1451 UndefElts2, Depth+1);
1452 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1453
1454 // If only the low elt is demanded and this is a scalarizable intrinsic,
1455 // scalarize it now.
1456 if (DemandedElts == 1) {
1457 switch (II->getIntrinsicID()) {
1458 default: break;
1459 case Intrinsic::x86_sse_sub_ss:
1460 case Intrinsic::x86_sse_mul_ss:
1461 case Intrinsic::x86_sse2_sub_sd:
1462 case Intrinsic::x86_sse2_mul_sd:
1463 // TODO: Lower MIN/MAX/ABS/etc
1464 Value *LHS = II->getOperand(1);
1465 Value *RHS = II->getOperand(2);
1466 // Extract the element as scalars.
1467 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1468 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1469
1470 switch (II->getIntrinsicID()) {
1471 default: assert(0 && "Case stmts out of sync!");
1472 case Intrinsic::x86_sse_sub_ss:
1473 case Intrinsic::x86_sse2_sub_sd:
1474 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1475 II->getName()), *II);
1476 break;
1477 case Intrinsic::x86_sse_mul_ss:
1478 case Intrinsic::x86_sse2_mul_sd:
1479 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1480 II->getName()), *II);
1481 break;
1482 }
1483
1484 Instruction *New =
1485 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1486 II->getName());
1487 InsertNewInstBefore(New, *II);
1488 AddSoonDeadInstToWorklist(*II, 0);
1489 return New;
1490 }
1491 }
1492
1493 // Output elements are undefined if both are undefined. Consider things
1494 // like undef&0. The result is known zero, not undef.
1495 UndefElts &= UndefElts2;
1496 break;
1497 }
1498 break;
1499 }
1500 }
1501 return MadeChange ? I : 0;
1502}
1503
Chris Lattner623826c2004-09-28 21:48:02 +00001504// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1505// true when both operands are equal...
1506//
1507static bool isTrueWhenEqual(Instruction &I) {
1508 return I.getOpcode() == Instruction::SetEQ ||
1509 I.getOpcode() == Instruction::SetGE ||
1510 I.getOpcode() == Instruction::SetLE;
1511}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001512
1513/// AssociativeOpt - Perform an optimization on an associative operator. This
1514/// function is designed to check a chain of associative operators for a
1515/// potential to apply a certain optimization. Since the optimization may be
1516/// applicable if the expression was reassociated, this checks the chain, then
1517/// reassociates the expression as necessary to expose the optimization
1518/// opportunity. This makes use of a special Functor, which must define
1519/// 'shouldApply' and 'apply' methods.
1520///
1521template<typename Functor>
1522Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1523 unsigned Opcode = Root.getOpcode();
1524 Value *LHS = Root.getOperand(0);
1525
1526 // Quick check, see if the immediate LHS matches...
1527 if (F.shouldApply(LHS))
1528 return F.apply(Root);
1529
1530 // Otherwise, if the LHS is not of the same opcode as the root, return.
1531 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001532 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001533 // Should we apply this transform to the RHS?
1534 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1535
1536 // If not to the RHS, check to see if we should apply to the LHS...
1537 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1538 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1539 ShouldApply = true;
1540 }
1541
1542 // If the functor wants to apply the optimization to the RHS of LHSI,
1543 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1544 if (ShouldApply) {
1545 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001546
Chris Lattnerb8b97502003-08-13 19:01:45 +00001547 // Now all of the instructions are in the current basic block, go ahead
1548 // and perform the reassociation.
1549 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1550
1551 // First move the selected RHS to the LHS of the root...
1552 Root.setOperand(0, LHSI->getOperand(1));
1553
1554 // Make what used to be the LHS of the root be the user of the root...
1555 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001556 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001557 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1558 return 0;
1559 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001560 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001561 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001562 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1563 BasicBlock::iterator ARI = &Root; ++ARI;
1564 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1565 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001566
1567 // Now propagate the ExtraOperand down the chain of instructions until we
1568 // get to LHSI.
1569 while (TmpLHSI != LHSI) {
1570 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001571 // Move the instruction to immediately before the chain we are
1572 // constructing to avoid breaking dominance properties.
1573 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1574 BB->getInstList().insert(ARI, NextLHSI);
1575 ARI = NextLHSI;
1576
Chris Lattnerb8b97502003-08-13 19:01:45 +00001577 Value *NextOp = NextLHSI->getOperand(1);
1578 NextLHSI->setOperand(1, ExtraOperand);
1579 TmpLHSI = NextLHSI;
1580 ExtraOperand = NextOp;
1581 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583 // Now that the instructions are reassociated, have the functor perform
1584 // the transformation...
1585 return F.apply(Root);
1586 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001587
Chris Lattnerb8b97502003-08-13 19:01:45 +00001588 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1589 }
1590 return 0;
1591}
1592
1593
1594// AddRHS - Implements: X + X --> X << 1
1595struct AddRHS {
1596 Value *RHS;
1597 AddRHS(Value *rhs) : RHS(rhs) {}
1598 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1599 Instruction *apply(BinaryOperator &Add) const {
1600 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1601 ConstantInt::get(Type::UByteTy, 1));
1602 }
1603};
1604
1605// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1606// iff C1&C2 == 0
1607struct AddMaskingAnd {
1608 Constant *C2;
1609 AddMaskingAnd(Constant *c) : C2(c) {}
1610 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001611 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001612 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001613 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001614 }
1615 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001616 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001617 }
1618};
1619
Chris Lattner86102b82005-01-01 16:22:27 +00001620static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001621 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001622 if (isa<CastInst>(I)) {
1623 if (Constant *SOC = dyn_cast<Constant>(SO))
1624 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001625
Chris Lattner86102b82005-01-01 16:22:27 +00001626 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1627 SO->getName() + ".cast"), I);
1628 }
1629
Chris Lattner183b3362004-04-09 19:05:30 +00001630 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001631 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1632 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001633
Chris Lattner183b3362004-04-09 19:05:30 +00001634 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1635 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001636 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1637 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001638 }
1639
1640 Value *Op0 = SO, *Op1 = ConstOperand;
1641 if (!ConstIsRHS)
1642 std::swap(Op0, Op1);
1643 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1645 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1646 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1647 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001648 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001649 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001650 abort();
1651 }
Chris Lattner86102b82005-01-01 16:22:27 +00001652 return IC->InsertNewInstBefore(New, I);
1653}
1654
1655// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1656// constant as the other operand, try to fold the binary operator into the
1657// select arguments. This also works for Cast instructions, which obviously do
1658// not have a second operand.
1659static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1660 InstCombiner *IC) {
1661 // Don't modify shared select instructions
1662 if (!SI->hasOneUse()) return 0;
1663 Value *TV = SI->getOperand(1);
1664 Value *FV = SI->getOperand(2);
1665
1666 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001667 // Bool selects with constant operands can be folded to logical ops.
1668 if (SI->getType() == Type::BoolTy) return 0;
1669
Chris Lattner86102b82005-01-01 16:22:27 +00001670 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1671 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1672
1673 return new SelectInst(SI->getCondition(), SelectTrueVal,
1674 SelectFalseVal);
1675 }
1676 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001677}
1678
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001679
1680/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1681/// node as operand #0, see if we can fold the instruction into the PHI (which
1682/// is only possible if all operands to the PHI are constants).
1683Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1684 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001685 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001686 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001687
Chris Lattner04689872006-09-09 22:02:56 +00001688 // Check to see if all of the operands of the PHI are constants. If there is
1689 // one non-constant value, remember the BB it is. If there is more than one
1690 // bail out.
1691 BasicBlock *NonConstBB = 0;
1692 for (unsigned i = 0; i != NumPHIValues; ++i)
1693 if (!isa<Constant>(PN->getIncomingValue(i))) {
1694 if (NonConstBB) return 0; // More than one non-const value.
1695 NonConstBB = PN->getIncomingBlock(i);
1696
1697 // If the incoming non-constant value is in I's block, we have an infinite
1698 // loop.
1699 if (NonConstBB == I.getParent())
1700 return 0;
1701 }
1702
1703 // If there is exactly one non-constant value, we can insert a copy of the
1704 // operation in that block. However, if this is a critical edge, we would be
1705 // inserting the computation one some other paths (e.g. inside a loop). Only
1706 // do this if the pred block is unconditionally branching into the phi block.
1707 if (NonConstBB) {
1708 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1709 if (!BI || !BI->isUnconditional()) return 0;
1710 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001711
1712 // Okay, we can do the transformation: create the new PHI node.
1713 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1714 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001715 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001716 InsertNewInstBefore(NewPN, *PN);
1717
1718 // Next, add all of the operands to the PHI.
1719 if (I.getNumOperands() == 2) {
1720 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001721 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001722 Value *InV;
1723 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1724 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1725 } else {
1726 assert(PN->getIncomingBlock(i) == NonConstBB);
1727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1728 InV = BinaryOperator::create(BO->getOpcode(),
1729 PN->getIncomingValue(i), C, "phitmp",
1730 NonConstBB->getTerminator());
1731 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1732 InV = new ShiftInst(SI->getOpcode(),
1733 PN->getIncomingValue(i), C, "phitmp",
1734 NonConstBB->getTerminator());
1735 else
1736 assert(0 && "Unknown binop!");
1737
1738 WorkList.push_back(cast<Instruction>(InV));
1739 }
1740 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001741 }
1742 } else {
1743 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1744 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001745 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001746 Value *InV;
1747 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1748 InV = ConstantExpr::getCast(InC, RetTy);
1749 } else {
1750 assert(PN->getIncomingBlock(i) == NonConstBB);
1751 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1752 NonConstBB->getTerminator());
1753 WorkList.push_back(cast<Instruction>(InV));
1754 }
1755 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001756 }
1757 }
1758 return ReplaceInstUsesWith(I, NewPN);
1759}
1760
Chris Lattner113f4f42002-06-25 16:13:24 +00001761Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001762 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001763 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001764
Chris Lattnercf4a9962004-04-10 22:01:55 +00001765 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001766 // X + undef -> undef
1767 if (isa<UndefValue>(RHS))
1768 return ReplaceInstUsesWith(I, RHS);
1769
Chris Lattnercf4a9962004-04-10 22:01:55 +00001770 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001771 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1772 if (RHSC->isNullValue())
1773 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001774 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1775 if (CFP->isExactlyValue(-0.0))
1776 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001777 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001778
Chris Lattnercf4a9962004-04-10 22:01:55 +00001779 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001780 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001781 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001782 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001783 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001784
1785 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1786 // (X & 254)+1 -> (X&254)|1
1787 uint64_t KnownZero, KnownOne;
1788 if (!isa<PackedType>(I.getType()) &&
1789 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1790 KnownZero, KnownOne))
1791 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001792 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001793
1794 if (isa<PHINode>(LHS))
1795 if (Instruction *NV = FoldOpIntoPhi(I))
1796 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001797
Chris Lattner330628a2006-01-06 17:59:59 +00001798 ConstantInt *XorRHS = 0;
1799 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001800 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1801 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1802 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1803 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1804
1805 uint64_t C0080Val = 1ULL << 31;
1806 int64_t CFF80Val = -C0080Val;
1807 unsigned Size = 32;
1808 do {
1809 if (TySizeBits > Size) {
1810 bool Found = false;
1811 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1812 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1813 if (RHSSExt == CFF80Val) {
1814 if (XorRHS->getZExtValue() == C0080Val)
1815 Found = true;
1816 } else if (RHSZExt == C0080Val) {
1817 if (XorRHS->getSExtValue() == CFF80Val)
1818 Found = true;
1819 }
1820 if (Found) {
1821 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001822 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001823 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001824 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001825 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001826 Size = 0; // Not a sign ext, but can't be any others either.
1827 goto FoundSExt;
1828 }
1829 }
1830 Size >>= 1;
1831 C0080Val >>= Size;
1832 CFF80Val >>= Size;
1833 } while (Size >= 8);
1834
1835FoundSExt:
1836 const Type *MiddleType = 0;
1837 switch (Size) {
1838 default: break;
1839 case 32: MiddleType = Type::IntTy; break;
1840 case 16: MiddleType = Type::ShortTy; break;
1841 case 8: MiddleType = Type::SByteTy; break;
1842 }
1843 if (MiddleType) {
1844 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1845 InsertNewInstBefore(NewTrunc, I);
1846 return new CastInst(NewTrunc, I.getType());
1847 }
1848 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001849 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001850
Chris Lattnerb8b97502003-08-13 19:01:45 +00001851 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001852 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001853 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001854
1855 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1856 if (RHSI->getOpcode() == Instruction::Sub)
1857 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1858 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1859 }
1860 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1861 if (LHSI->getOpcode() == Instruction::Sub)
1862 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1863 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1864 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001865 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001866
Chris Lattner147e9752002-05-08 22:46:53 +00001867 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001868 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001869 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001870
1871 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001872 if (!isa<Constant>(RHS))
1873 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001874 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001875
Misha Brukmanb1c93172005-04-21 23:48:37 +00001876
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001877 ConstantInt *C2;
1878 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1879 if (X == RHS) // X*C + X --> X * (C+1)
1880 return BinaryOperator::createMul(RHS, AddOne(C2));
1881
1882 // X*C1 + X*C2 --> X * (C1+C2)
1883 ConstantInt *C1;
1884 if (X == dyn_castFoldableMul(RHS, C1))
1885 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001886 }
1887
1888 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001889 if (dyn_castFoldableMul(RHS, C2) == LHS)
1890 return BinaryOperator::createMul(LHS, AddOne(C2));
1891
Chris Lattner57c8d992003-02-18 19:57:07 +00001892
Chris Lattnerb8b97502003-08-13 19:01:45 +00001893 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001895 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001896
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001898 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1900 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1901 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001902 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001903
Chris Lattnerbff91d92004-10-08 05:07:56 +00001904 // (X & FF00) + xx00 -> (X+xx00) & FF00
1905 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1906 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1907 if (Anded == CRHS) {
1908 // See if all bits from the first bit set in the Add RHS up are included
1909 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001910 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001911
1912 // Form a mask of all bits from the lowest bit added through the top.
1913 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001914 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001915
1916 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001917 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001918
Chris Lattnerbff91d92004-10-08 05:07:56 +00001919 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1920 // Okay, the xform is safe. Insert the new add pronto.
1921 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1922 LHS->getName()), I);
1923 return BinaryOperator::createAnd(NewAdd, C2);
1924 }
1925 }
1926 }
1927
Chris Lattnerd4252a72004-07-30 07:50:03 +00001928 // Try to fold constant add into select arguments.
1929 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001930 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001931 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001932 }
1933
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001934 // add (cast *A to intptrtype) B ->
1935 // cast (GEP (cast *A to sbyte*) B) ->
1936 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001937 {
1938 CastInst* CI = dyn_cast<CastInst>(LHS);
1939 Value* Other = RHS;
1940 if (!CI) {
1941 CI = dyn_cast<CastInst>(RHS);
1942 Other = LHS;
1943 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001944 if (CI && CI->getType()->isSized() &&
1945 (CI->getType()->getPrimitiveSize() ==
1946 TD->getIntPtrType()->getPrimitiveSize())
1947 && isa<PointerType>(CI->getOperand(0)->getType())) {
1948 Value* I2 = InsertCastBefore(CI->getOperand(0),
1949 PointerType::get(Type::SByteTy), I);
1950 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1951 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001952 }
1953 }
1954
Chris Lattner113f4f42002-06-25 16:13:24 +00001955 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001956}
1957
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001958// isSignBit - Return true if the value represented by the constant only has the
1959// highest order bit set.
1960static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001961 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001963}
1964
Chris Lattner022167f2004-03-13 00:11:49 +00001965/// RemoveNoopCast - Strip off nonconverting casts from the value.
1966///
1967static Value *RemoveNoopCast(Value *V) {
1968 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1969 const Type *CTy = CI->getType();
1970 const Type *OpTy = CI->getOperand(0)->getType();
1971 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001972 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001973 return RemoveNoopCast(CI->getOperand(0));
1974 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1975 return RemoveNoopCast(CI->getOperand(0));
1976 }
1977 return V;
1978}
1979
Chris Lattner113f4f42002-06-25 16:13:24 +00001980Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001982
Chris Lattnere6794492002-08-12 21:17:25 +00001983 if (Op0 == Op1) // sub X, X -> 0
1984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001985
Chris Lattnere6794492002-08-12 21:17:25 +00001986 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001987 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001988 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001989
Chris Lattner81a7a232004-10-16 18:11:37 +00001990 if (isa<UndefValue>(Op0))
1991 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1992 if (isa<UndefValue>(Op1))
1993 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1994
Chris Lattner8f2f5982003-11-05 01:06:05 +00001995 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1996 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001997 if (C->isAllOnesValue())
1998 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001999
Chris Lattner8f2f5982003-11-05 01:06:05 +00002000 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002001 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002002 if (match(Op1, m_Not(m_Value(X))))
2003 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002004 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00002005 // -((uint)X >> 31) -> ((int)X >> 31)
2006 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002007 if (C->isNullValue()) {
2008 Value *NoopCastedRHS = RemoveNoopCast(Op1);
2009 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00002010 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002011 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002012 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002013 if (CU->getZExtValue() ==
2014 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002015 // Ok, the transformation is safe. Insert AShr.
2016 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
2017 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002018 }
2019 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002020 }
2021 else if (SI->getOpcode() == Instruction::AShr) {
2022 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2023 // Check to see if we are shifting out everything but the sign bit.
2024 if (CU->getZExtValue() ==
2025 SI->getType()->getPrimitiveSizeInBits()-1) {
2026 // Ok, the transformation is safe. Insert LShr.
2027 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2028 CU, SI->getName());
2029 }
2030 }
2031 }
Chris Lattner022167f2004-03-13 00:11:49 +00002032 }
Chris Lattner183b3362004-04-09 19:05:30 +00002033
2034 // Try to fold constant sub into select arguments.
2035 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002037 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002038
2039 if (isa<PHINode>(Op0))
2040 if (Instruction *NV = FoldOpIntoPhi(I))
2041 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002042 }
2043
Chris Lattnera9be4492005-04-07 16:15:25 +00002044 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2045 if (Op1I->getOpcode() == Instruction::Add &&
2046 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002047 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002048 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002049 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002051 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2052 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2053 // C1-(X+C2) --> (C1-C2)-X
2054 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2055 Op1I->getOperand(0));
2056 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002057 }
2058
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002059 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002060 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2061 // is not used by anyone else...
2062 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002063 if (Op1I->getOpcode() == Instruction::Sub &&
2064 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002065 // Swap the two operands of the subexpr...
2066 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2067 Op1I->setOperand(0, IIOp1);
2068 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002069
Chris Lattner3082c5a2003-02-18 19:28:33 +00002070 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002072 }
2073
2074 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2075 //
2076 if (Op1I->getOpcode() == Instruction::And &&
2077 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2078 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2079
Chris Lattner396dbfe2004-06-09 05:08:07 +00002080 Value *NewNot =
2081 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002082 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002083 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002084
Reid Spencer3c514952006-10-16 23:08:08 +00002085 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002086 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002087 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002088 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002089 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002090 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002091 ConstantExpr::getNeg(DivRHS));
2092
Chris Lattner57c8d992003-02-18 19:57:07 +00002093 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002094 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002095 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002096 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002097 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002098 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002099 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002100 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002101 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002102
Chris Lattner47060462005-04-07 17:14:51 +00002103 if (!Op0->getType()->isFloatingPoint())
2104 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2105 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002106 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2107 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2108 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2109 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002110 } else if (Op0I->getOpcode() == Instruction::Sub) {
2111 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2112 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002113 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002114
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002115 ConstantInt *C1;
2116 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2117 if (X == Op1) { // X*C - X --> X * (C-1)
2118 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2119 return BinaryOperator::createMul(Op1, CP1);
2120 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002121
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002122 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2123 if (X == dyn_castFoldableMul(Op1, C2))
2124 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2125 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002126 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002127}
2128
Chris Lattnere79e8542004-02-23 06:38:22 +00002129/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2130/// really just returns true if the most significant (sign) bit is set.
2131static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2132 if (RHS->getType()->isSigned()) {
2133 // True if source is LHS < 0 or LHS <= -1
2134 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2135 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2136 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002137 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002138 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2139 // the size of the integer type.
2140 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002141 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002142 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002143 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002144 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002145 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002146 }
2147 return false;
2148}
2149
Chris Lattner113f4f42002-06-25 16:13:24 +00002150Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002151 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002152 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002153
Chris Lattner81a7a232004-10-16 18:11:37 +00002154 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2156
Chris Lattnere6794492002-08-12 21:17:25 +00002157 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002158 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2159 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002160
2161 // ((X << C1)*C2) == (X * (C2 << C1))
2162 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2163 if (SI->getOpcode() == Instruction::Shl)
2164 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002165 return BinaryOperator::createMul(SI->getOperand(0),
2166 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002167
Chris Lattnercce81be2003-09-11 22:24:54 +00002168 if (CI->isNullValue())
2169 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2170 if (CI->equalsInt(1)) // X * 1 == X
2171 return ReplaceInstUsesWith(I, Op0);
2172 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002173 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002174
Reid Spencere0fc4df2006-10-20 07:07:24 +00002175 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002176 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2177 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002178 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002179 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002180 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002181 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002182 if (Op1F->isNullValue())
2183 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002184
Chris Lattner3082c5a2003-02-18 19:28:33 +00002185 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2186 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2187 if (Op1F->getValue() == 1.0)
2188 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2189 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002190
2191 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2192 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2193 isa<ConstantInt>(Op0I->getOperand(1))) {
2194 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2195 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2196 Op1, "tmp");
2197 InsertNewInstBefore(Add, I);
2198 Value *C1C2 = ConstantExpr::getMul(Op1,
2199 cast<Constant>(Op0I->getOperand(1)));
2200 return BinaryOperator::createAdd(Add, C1C2);
2201
2202 }
Chris Lattner183b3362004-04-09 19:05:30 +00002203
2204 // Try to fold constant mul into select arguments.
2205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002207 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002208
2209 if (isa<PHINode>(Op0))
2210 if (Instruction *NV = FoldOpIntoPhi(I))
2211 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002212 }
2213
Chris Lattner934a64cf2003-03-10 23:23:04 +00002214 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2215 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002216 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002217
Chris Lattner2635b522004-02-23 05:39:21 +00002218 // If one of the operands of the multiply is a cast from a boolean value, then
2219 // we know the bool is either zero or one, so this is a 'masking' multiply.
2220 // See if we can simplify things based on how the boolean was originally
2221 // formed.
2222 CastInst *BoolCast = 0;
2223 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2224 if (CI->getOperand(0)->getType() == Type::BoolTy)
2225 BoolCast = CI;
2226 if (!BoolCast)
2227 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2228 if (CI->getOperand(0)->getType() == Type::BoolTy)
2229 BoolCast = CI;
2230 if (BoolCast) {
2231 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2232 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2233 const Type *SCOpTy = SCIOp0->getType();
2234
Chris Lattnere79e8542004-02-23 06:38:22 +00002235 // If the setcc is true iff the sign bit of X is set, then convert this
2236 // multiply into a shift/and combination.
2237 if (isa<ConstantInt>(SCIOp1) &&
2238 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002239 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002240 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002241 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002242 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002243 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002244 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002245 }
2246
2247 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002248 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002249 BoolCast->getOperand(0)->getName()+
2250 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002251
2252 // If the multiply type is not the same as the source type, sign extend
2253 // or truncate to the multiply type.
2254 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002255 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002256
Chris Lattner2635b522004-02-23 05:39:21 +00002257 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002258 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002259 }
2260 }
2261 }
2262
Chris Lattner113f4f42002-06-25 16:13:24 +00002263 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002264}
2265
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266/// This function implements the transforms on div instructions that work
2267/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2268/// used by the visitors to those instructions.
2269/// @brief Transforms common to all three div instructions
2270Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002272
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002273 // undef / X -> 0
2274 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002275 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276
2277 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002278 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002280
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002281 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002282 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2283 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002284 // same basic block, then we replace the select with Y, and the condition
2285 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002286 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002287 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002288 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2289 if (ST->isNullValue()) {
2290 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2291 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002292 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002293 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2294 I.setOperand(1, SI->getOperand(2));
2295 else
2296 UpdateValueUsesWith(SI, SI->getOperand(2));
2297 return &I;
2298 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002299
Chris Lattnerd79dc792006-09-09 20:26:32 +00002300 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2301 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2302 if (ST->isNullValue()) {
2303 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2304 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002305 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002306 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2307 I.setOperand(1, SI->getOperand(1));
2308 else
2309 UpdateValueUsesWith(SI, SI->getOperand(1));
2310 return &I;
2311 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002313
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002314 return 0;
2315}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002316
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002317/// This function implements the transforms common to both integer division
2318/// instructions (udiv and sdiv). It is called by the visitors to those integer
2319/// division instructions.
2320/// @brief Common integer divide transforms
2321Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2323
2324 if (Instruction *Common = commonDivTransforms(I))
2325 return Common;
2326
2327 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2328 // div X, 1 == X
2329 if (RHS->equalsInt(1))
2330 return ReplaceInstUsesWith(I, Op0);
2331
2332 // (X / C1) / C2 -> X / (C1*C2)
2333 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2334 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2335 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2336 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2337 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002338 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339
2340 if (!RHS->isNullValue()) { // avoid X udiv 0
2341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2342 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2343 return R;
2344 if (isa<PHINode>(Op0))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2346 return NV;
2347 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002348 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002349
Chris Lattner3082c5a2003-02-18 19:28:33 +00002350 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002351 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002352 if (LHS->equalsInt(0))
2353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2354
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002355 return 0;
2356}
2357
2358Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2360
2361 // Handle the integer div common cases
2362 if (Instruction *Common = commonIDivTransforms(I))
2363 return Common;
2364
2365 // X udiv C^2 -> X >> C
2366 // Check to see if this is an unsigned division with an exact power of 2,
2367 // if so, convert to a right shift.
2368 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2369 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2370 if (isPowerOf2_64(Val)) {
2371 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 return new ShiftInst(Instruction::LShr, Op0,
2373 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002374 }
2375 }
2376
2377 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2378 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2379 if (RHSI->getOpcode() == Instruction::Shl &&
2380 isa<ConstantInt>(RHSI->getOperand(0))) {
2381 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2382 if (isPowerOf2_64(C1)) {
2383 Value *N = RHSI->getOperand(1);
2384 const Type* NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002385 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 Constant *C2V = ConstantInt::get(NTy, C2);
2387 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002388 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002389 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002390 }
2391 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002392 }
2393
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002394 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2395 // where C1&C2 are powers of two.
2396 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2397 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2398 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2399 if (!STO->isNullValue() && !STO->isNullValue()) {
2400 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2401 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2402 // Compute the shift amounts
2403 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404 // Construct the "on true" case of the select
2405 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2406 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002407 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002408 TSI = InsertNewInstBefore(TSI, I);
2409
2410 // Construct the "on false" case of the select
2411 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2412 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002413 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002414 FSI = InsertNewInstBefore(FSI, I);
2415
2416 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002417 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002418 }
2419 }
2420 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002421 return 0;
2422}
2423
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002424Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2426
2427 // Handle the integer div common cases
2428 if (Instruction *Common = commonIDivTransforms(I))
2429 return Common;
2430
2431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2432 // sdiv X, -1 == -X
2433 if (RHS->isAllOnesValue())
2434 return BinaryOperator::createNeg(Op0);
2435
2436 // -X/C -> X/-C
2437 if (Value *LHSNeg = dyn_castNegVal(Op0))
2438 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2439 }
2440
2441 // If the sign bits of both operands are zero (i.e. we can prove they are
2442 // unsigned inputs), turn this into a udiv.
2443 if (I.getType()->isInteger()) {
2444 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2445 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2446 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2447 }
2448 }
2449
2450 return 0;
2451}
2452
2453Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2454 return commonDivTransforms(I);
2455}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002456
Chris Lattner85dda9a2006-03-02 06:50:58 +00002457/// GetFactor - If we can prove that the specified value is at least a multiple
2458/// of some factor, return that factor.
2459static Constant *GetFactor(Value *V) {
2460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2461 return CI;
2462
2463 // Unless we can be tricky, we know this is a multiple of 1.
2464 Constant *Result = ConstantInt::get(V->getType(), 1);
2465
2466 Instruction *I = dyn_cast<Instruction>(V);
2467 if (!I) return Result;
2468
2469 if (I->getOpcode() == Instruction::Mul) {
2470 // Handle multiplies by a constant, etc.
2471 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2472 GetFactor(I->getOperand(1)));
2473 } else if (I->getOpcode() == Instruction::Shl) {
2474 // (X<<C) -> X * (1 << C)
2475 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2476 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2477 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2478 }
2479 } else if (I->getOpcode() == Instruction::And) {
2480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2481 // X & 0xFFF0 is known to be a multiple of 16.
2482 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2483 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2484 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002485 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002486 }
2487 } else if (I->getOpcode() == Instruction::Cast) {
2488 Value *Op = I->getOperand(0);
2489 // Only handle int->int casts.
2490 if (!Op->getType()->isInteger()) return Result;
2491 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2492 }
2493 return Result;
2494}
2495
Reid Spencer7eb55b32006-11-02 01:53:59 +00002496/// This function implements the transforms on rem instructions that work
2497/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2498/// is used by the visitors to those instructions.
2499/// @brief Transforms common to all three rem instructions
2500Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002502
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002503 // 0 % X == 0, we don't need to preserve faults!
2504 if (Constant *LHS = dyn_cast<Constant>(Op0))
2505 if (LHS->isNullValue())
2506 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2507
2508 if (isa<UndefValue>(Op0)) // undef % X -> 0
2509 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2510 if (isa<UndefValue>(Op1))
2511 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002512
2513 // Handle cases involving: rem X, (select Cond, Y, Z)
2514 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2515 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2516 // the same basic block, then we replace the select with Y, and the
2517 // condition of the select with false (if the cond value is in the same
2518 // BB). If the select has uses other than the div, this allows them to be
2519 // simplified also.
2520 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2521 if (ST->isNullValue()) {
2522 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2523 if (CondI && CondI->getParent() == I.getParent())
2524 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2525 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2526 I.setOperand(1, SI->getOperand(2));
2527 else
2528 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002529 return &I;
2530 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002531 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2532 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2533 if (ST->isNullValue()) {
2534 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2535 if (CondI && CondI->getParent() == I.getParent())
2536 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2537 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2538 I.setOperand(1, SI->getOperand(1));
2539 else
2540 UpdateValueUsesWith(SI, SI->getOperand(1));
2541 return &I;
2542 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002543 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002544
Reid Spencer7eb55b32006-11-02 01:53:59 +00002545 return 0;
2546}
2547
2548/// This function implements the transforms common to both integer remainder
2549/// instructions (urem and srem). It is called by the visitors to those integer
2550/// remainder instructions.
2551/// @brief Common integer remainder transforms
2552Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2554
2555 if (Instruction *common = commonRemTransforms(I))
2556 return common;
2557
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002559 // X % 0 == undef, we don't need to preserve faults!
2560 if (RHS->equalsInt(0))
2561 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2562
Chris Lattner3082c5a2003-02-18 19:28:33 +00002563 if (RHS->equalsInt(1)) // X % 1 == 0
2564 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2565
Chris Lattnerb70f1412006-02-28 05:49:21 +00002566 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2568 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2569 return R;
2570 } else if (isa<PHINode>(Op0I)) {
2571 if (Instruction *NV = FoldOpIntoPhi(I))
2572 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002573 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002574 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2575 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002577 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002578 }
2579
Reid Spencer7eb55b32006-11-02 01:53:59 +00002580 return 0;
2581}
2582
2583Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2585
2586 if (Instruction *common = commonIRemTransforms(I))
2587 return common;
2588
2589 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2590 // X urem C^2 -> X and C
2591 // Check to see if this is an unsigned remainder with an exact power of 2,
2592 // if so, convert to a bitwise and.
2593 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2594 if (isPowerOf2_64(C->getZExtValue()))
2595 return BinaryOperator::createAnd(Op0, SubOne(C));
2596 }
2597
Chris Lattner2e90b732006-02-05 07:54:04 +00002598 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002599 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2600 if (RHSI->getOpcode() == Instruction::Shl &&
2601 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002602 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002603 if (isPowerOf2_64(C1)) {
2604 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2605 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2606 "tmp"), I);
2607 return BinaryOperator::createAnd(Op0, Add);
2608 }
2609 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002610 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002611
Reid Spencer7eb55b32006-11-02 01:53:59 +00002612 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2613 // where C1&C2 are powers of two.
2614 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2615 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2616 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2617 // STO == 0 and SFO == 0 handled above.
2618 if (isPowerOf2_64(STO->getZExtValue()) &&
2619 isPowerOf2_64(SFO->getZExtValue())) {
2620 Value *TrueAnd = InsertNewInstBefore(
2621 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2622 Value *FalseAnd = InsertNewInstBefore(
2623 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2624 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2625 }
2626 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002627 }
2628
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002629 return 0;
2630}
2631
Reid Spencer7eb55b32006-11-02 01:53:59 +00002632Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2633 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2634
2635 if (Instruction *common = commonIRemTransforms(I))
2636 return common;
2637
2638 if (Value *RHSNeg = dyn_castNegVal(Op1))
2639 if (!isa<ConstantInt>(RHSNeg) ||
2640 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2641 // X % -Y -> X % Y
2642 AddUsesToWorkList(I);
2643 I.setOperand(1, RHSNeg);
2644 return &I;
2645 }
2646
2647 // If the top bits of both operands are zero (i.e. we can prove they are
2648 // unsigned inputs), turn this into a urem.
2649 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2650 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2651 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2652 return BinaryOperator::createURem(Op0, Op1, I.getName());
2653 }
2654
2655 return 0;
2656}
2657
2658Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002659 return commonRemTransforms(I);
2660}
2661
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002662// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002663static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002664 if (C->getType()->isUnsigned())
2665 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002666
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002667 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002668 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002669 int64_t Val = INT64_MAX; // All ones
2670 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002671 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002672}
2673
2674// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002675static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002676 if (C->getType()->isUnsigned())
2677 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002678
2679 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002680 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002681 int64_t Val = -1; // All ones
2682 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002683 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002684}
2685
Chris Lattner35167c32004-06-09 07:59:58 +00002686// isOneBitSet - Return true if there is exactly one bit set in the specified
2687// constant.
2688static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002689 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002690 return V && (V & (V-1)) == 0;
2691}
2692
Chris Lattner8fc5af42004-09-23 21:46:38 +00002693#if 0 // Currently unused
2694// isLowOnes - Return true if the constant is of the form 0+1+.
2695static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002696 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002697
2698 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002699 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002700
2701 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2702 return U && V && (U & V) == 0;
2703}
2704#endif
2705
2706// isHighOnes - Return true if the constant is of the form 1+0+.
2707// This is the same as lowones(~X).
2708static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002709 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002710 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002711
2712 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002713 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002714
2715 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2716 return U && V && (U & V) == 0;
2717}
2718
2719
Chris Lattner3ac7c262003-08-13 20:16:26 +00002720/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2721/// are carefully arranged to allow folding of expressions such as:
2722///
2723/// (A < B) | (A > B) --> (A != B)
2724///
2725/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2726/// represents that the comparison is true if A == B, and bit value '1' is true
2727/// if A < B.
2728///
2729static unsigned getSetCondCode(const SetCondInst *SCI) {
2730 switch (SCI->getOpcode()) {
2731 // False -> 0
2732 case Instruction::SetGT: return 1;
2733 case Instruction::SetEQ: return 2;
2734 case Instruction::SetGE: return 3;
2735 case Instruction::SetLT: return 4;
2736 case Instruction::SetNE: return 5;
2737 case Instruction::SetLE: return 6;
2738 // True -> 7
2739 default:
2740 assert(0 && "Invalid SetCC opcode!");
2741 return 0;
2742 }
2743}
2744
2745/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2746/// opcode and two operands into either a constant true or false, or a brand new
2747/// SetCC instruction.
2748static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2749 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002750 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002751 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2752 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2753 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2754 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2755 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2756 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002757 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002758 default: assert(0 && "Illegal SetCCCode!"); return 0;
2759 }
2760}
2761
2762// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2763struct FoldSetCCLogical {
2764 InstCombiner &IC;
2765 Value *LHS, *RHS;
2766 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2767 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2768 bool shouldApply(Value *V) const {
2769 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2770 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2771 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2772 return false;
2773 }
2774 Instruction *apply(BinaryOperator &Log) const {
2775 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2776 if (SCI->getOperand(0) != LHS) {
2777 assert(SCI->getOperand(1) == LHS);
2778 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2779 }
2780
2781 unsigned LHSCode = getSetCondCode(SCI);
2782 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2783 unsigned Code;
2784 switch (Log.getOpcode()) {
2785 case Instruction::And: Code = LHSCode & RHSCode; break;
2786 case Instruction::Or: Code = LHSCode | RHSCode; break;
2787 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002788 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002789 }
2790
2791 Value *RV = getSetCCValue(Code, LHS, RHS);
2792 if (Instruction *I = dyn_cast<Instruction>(RV))
2793 return I;
2794 // Otherwise, it's a constant boolean value...
2795 return IC.ReplaceInstUsesWith(Log, RV);
2796 }
2797};
2798
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2800// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2801// guaranteed to be either a shift instruction or a binary operator.
2802Instruction *InstCombiner::OptAndOp(Instruction *Op,
2803 ConstantIntegral *OpRHS,
2804 ConstantIntegral *AndRHS,
2805 BinaryOperator &TheAnd) {
2806 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002807 Constant *Together = 0;
2808 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002809 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002810
Chris Lattnerba1cb382003-09-19 17:17:26 +00002811 switch (Op->getOpcode()) {
2812 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002813 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002814 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002816 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002818 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002819 }
2820 break;
2821 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002822 if (Together == AndRHS) // (X | C) & C --> C
2823 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002824
Chris Lattner86102b82005-01-01 16:22:27 +00002825 if (Op->hasOneUse() && Together != OpRHS) {
2826 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827 std::string Op0Name = Op->getName(); Op->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829 InsertNewInstBefore(Or, TheAnd);
2830 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002831 }
2832 break;
2833 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002834 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002835 // Adding a one to a single bit bit-field should be turned into an XOR
2836 // of the bit. First thing to check is to see if this AND is with a
2837 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002838 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839
2840 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002841 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842
2843 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002844 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // Ok, at this point, we know that we are masking the result of the
2846 // ADD down to exactly one bit. If the constant we are adding has
2847 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002848 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002849
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 // Check to see if any bits below the one bit set in AndRHSV are set.
2851 if ((AddRHS & (AndRHSV-1)) == 0) {
2852 // If not, the only thing that can effect the output of the AND is
2853 // the bit specified by AndRHSV. If that bit is set, the effect of
2854 // the XOR is to toggle the bit. If it is clear, then the ADD has
2855 // no effect.
2856 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857 TheAnd.setOperand(0, X);
2858 return &TheAnd;
2859 } else {
2860 std::string Name = Op->getName(); Op->setName("");
2861 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002862 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002864 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 }
2866 }
2867 }
2868 }
2869 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002870
2871 case Instruction::Shl: {
2872 // We know that the AND will not produce any of the bits shifted in, so if
2873 // the anded constant includes them, clear them now!
2874 //
2875 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002876 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002878
Chris Lattner7e794272004-09-24 15:21:34 +00002879 if (CI == ShlMask) { // Masking out bits that the shift already masks
2880 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2881 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002882 TheAnd.setOperand(1, CI);
2883 return &TheAnd;
2884 }
2885 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002887 case Instruction::LShr:
2888 {
Chris Lattner2da29172003-09-19 19:05:02 +00002889 // We know that the AND will not produce any of the bits shifted in, so if
2890 // the anded constant includes them, clear them now! This only applies to
2891 // unsigned shifts, because a signed shr may bring in set bits!
2892 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002893 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2894 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002896
Reid Spencerfdff9382006-11-08 06:47:33 +00002897 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2898 return ReplaceInstUsesWith(TheAnd, Op);
2899 } else if (CI != AndRHS) {
2900 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2901 return &TheAnd;
2902 }
2903 break;
2904 }
2905 case Instruction::AShr:
2906 // Signed shr.
2907 // See if this is shifting in some sign extension, then masking it out
2908 // with an and.
2909 if (Op->hasOneUse()) {
2910 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2911 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2912 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2913 if (CI == AndRHS) { // Masking out bits shifted in.
2914 // Make the argument unsigned.
2915 Value *ShVal = Op->getOperand(0);
2916 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2917 OpRHS, Op->getName()),
2918 TheAnd);
2919 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2920 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002921 }
Chris Lattner2da29172003-09-19 19:05:02 +00002922 }
2923 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002924 }
2925 return 0;
2926}
2927
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002928
Chris Lattner6862fbd2004-09-29 17:40:11 +00002929/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2930/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2931/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2932/// insert new instructions.
2933Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2934 bool Inside, Instruction &IB) {
2935 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2936 "Lo is not <= Hi in range emission code!");
2937 if (Inside) {
2938 if (Lo == Hi) // Trivially false.
2939 return new SetCondInst(Instruction::SetNE, V, V);
2940 if (cast<ConstantIntegral>(Lo)->isMinValue())
2941 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002942
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 Constant *AddCST = ConstantExpr::getNeg(Lo);
2944 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2945 InsertNewInstBefore(Add, IB);
2946 // Convert to unsigned for the comparison.
2947 const Type *UnsType = Add->getType()->getUnsignedVersion();
2948 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2949 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2950 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2951 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2952 }
2953
2954 if (Lo == Hi) // Trivially true.
2955 return new SetCondInst(Instruction::SetEQ, V, V);
2956
2957 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002958
2959 // V < 0 || V >= Hi ->'V > Hi-1'
2960 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961 return new SetCondInst(Instruction::SetGT, V, Hi);
2962
2963 // Emit X-Lo > Hi-Lo-1
2964 Constant *AddCST = ConstantExpr::getNeg(Lo);
2965 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2966 InsertNewInstBefore(Add, IB);
2967 // Convert to unsigned for the comparison.
2968 const Type *UnsType = Add->getType()->getUnsignedVersion();
2969 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2970 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2971 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2972 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2973}
2974
Chris Lattnerb4b25302005-09-18 07:22:02 +00002975// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2976// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2977// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2978// not, since all 1s are not contiguous.
2979static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002980 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002981 if (!isShiftedMask_64(V)) return false;
2982
2983 // look for the first zero bit after the run of ones
2984 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2985 // look for the first non-zero bit
2986 ME = 64-CountLeadingZeros_64(V);
2987 return true;
2988}
2989
2990
2991
2992/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2993/// where isSub determines whether the operator is a sub. If we can fold one of
2994/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002995///
2996/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2997/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2998/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2999///
3000/// return (A +/- B).
3001///
3002Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3003 ConstantIntegral *Mask, bool isSub,
3004 Instruction &I) {
3005 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3006 if (!LHSI || LHSI->getNumOperands() != 2 ||
3007 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3008
3009 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3010
3011 switch (LHSI->getOpcode()) {
3012 default: return 0;
3013 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003014 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3015 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003016 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017 break;
3018
3019 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3020 // part, we don't need any explicit masks to take them out of A. If that
3021 // is all N is, ignore it.
3022 unsigned MB, ME;
3023 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003024 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3025 Mask >>= 64-MB+1;
3026 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003027 break;
3028 }
3029 }
Chris Lattneraf517572005-09-18 04:24:45 +00003030 return 0;
3031 case Instruction::Or:
3032 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003033 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003034 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003035 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003036 break;
3037 return 0;
3038 }
3039
3040 Instruction *New;
3041 if (isSub)
3042 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3043 else
3044 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3045 return InsertNewInstBefore(New, I);
3046}
3047
Chris Lattner113f4f42002-06-25 16:13:24 +00003048Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003049 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003051
Chris Lattner81a7a232004-10-16 18:11:37 +00003052 if (isa<UndefValue>(Op1)) // X & undef -> 0
3053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3054
Chris Lattner86102b82005-01-01 16:22:27 +00003055 // and X, X = X
3056 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003057 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003058
Chris Lattner5b2edb12006-02-12 08:02:11 +00003059 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003060 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003061 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003062 if (!isa<PackedType>(I.getType()) &&
3063 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003064 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003065 return &I;
3066
Chris Lattner86102b82005-01-01 16:22:27 +00003067 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003068 uint64_t AndRHSMask = AndRHS->getZExtValue();
3069 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003070 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003071
Chris Lattnerba1cb382003-09-19 17:17:26 +00003072 // Optimize a variety of ((val OP C1) & C2) combinations...
3073 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3074 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003075 Value *Op0LHS = Op0I->getOperand(0);
3076 Value *Op0RHS = Op0I->getOperand(1);
3077 switch (Op0I->getOpcode()) {
3078 case Instruction::Xor:
3079 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003080 // If the mask is only needed on one incoming arm, push it up.
3081 if (Op0I->hasOneUse()) {
3082 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3083 // Not masking anything out for the LHS, move to RHS.
3084 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3085 Op0RHS->getName()+".masked");
3086 InsertNewInstBefore(NewRHS, I);
3087 return BinaryOperator::create(
3088 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003089 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003090 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003091 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3092 // Not masking anything out for the RHS, move to LHS.
3093 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3094 Op0LHS->getName()+".masked");
3095 InsertNewInstBefore(NewLHS, I);
3096 return BinaryOperator::create(
3097 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3098 }
3099 }
3100
Chris Lattner86102b82005-01-01 16:22:27 +00003101 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003102 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003103 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3104 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3105 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3106 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3107 return BinaryOperator::createAnd(V, AndRHS);
3108 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3109 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003110 break;
3111
3112 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003113 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3114 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3115 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3116 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3117 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003118 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003119 }
3120
Chris Lattner16464b32003-07-23 19:25:52 +00003121 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003122 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003123 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003124 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3125 const Type *SrcTy = CI->getOperand(0)->getType();
3126
Chris Lattner2c14cf72005-08-07 07:03:10 +00003127 // If this is an integer truncation or change from signed-to-unsigned, and
3128 // if the source is an and/or with immediate, transform it. This
3129 // frequently occurs for bitfield accesses.
3130 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3131 if (SrcTy->getPrimitiveSizeInBits() >=
3132 I.getType()->getPrimitiveSizeInBits() &&
3133 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003134 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003135 if (CastOp->getOpcode() == Instruction::And) {
3136 // Change: and (cast (and X, C1) to T), C2
3137 // into : and (cast X to T), trunc(C1)&C2
3138 // This will folds the two ands together, which may allow other
3139 // simplifications.
3140 Instruction *NewCast =
3141 new CastInst(CastOp->getOperand(0), I.getType(),
3142 CastOp->getName()+".shrunk");
3143 NewCast = InsertNewInstBefore(NewCast, I);
3144
3145 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3146 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3147 return BinaryOperator::createAnd(NewCast, C3);
3148 } else if (CastOp->getOpcode() == Instruction::Or) {
3149 // Change: and (cast (or X, C1) to T), C2
3150 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3151 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3152 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3153 return ReplaceInstUsesWith(I, AndRHS);
3154 }
3155 }
Chris Lattner33217db2003-07-23 19:36:21 +00003156 }
Chris Lattner183b3362004-04-09 19:05:30 +00003157
3158 // Try to fold constant and into select arguments.
3159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003161 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003162 if (isa<PHINode>(Op0))
3163 if (Instruction *NV = FoldOpIntoPhi(I))
3164 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003165 }
3166
Chris Lattnerbb74e222003-03-10 23:06:50 +00003167 Value *Op0NotVal = dyn_castNotVal(Op0);
3168 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003169
Chris Lattner023a4832004-06-18 06:07:51 +00003170 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3171 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3172
Misha Brukman9c003d82004-07-30 12:50:08 +00003173 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003174 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003175 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3176 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003177 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003178 return BinaryOperator::createNot(Or);
3179 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003180
3181 {
3182 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003183 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3184 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3185 return ReplaceInstUsesWith(I, Op1);
3186 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3187 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3188 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003189
3190 if (Op0->hasOneUse() &&
3191 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3192 if (A == Op1) { // (A^B)&A -> A&(A^B)
3193 I.swapOperands(); // Simplify below
3194 std::swap(Op0, Op1);
3195 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3196 cast<BinaryOperator>(Op0)->swapOperands();
3197 I.swapOperands(); // Simplify below
3198 std::swap(Op0, Op1);
3199 }
3200 }
3201 if (Op1->hasOneUse() &&
3202 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3203 if (B == Op0) { // B&(A^B) -> B&(B^A)
3204 cast<BinaryOperator>(Op1)->swapOperands();
3205 std::swap(A, B);
3206 }
3207 if (A == Op0) { // A&(A^B) -> A & ~B
3208 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3209 InsertNewInstBefore(NotB, I);
3210 return BinaryOperator::createAnd(A, NotB);
3211 }
3212 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003213 }
3214
Chris Lattner3082c5a2003-02-18 19:28:33 +00003215
Chris Lattner623826c2004-09-28 21:48:02 +00003216 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3217 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003218 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3219 return R;
3220
Chris Lattner623826c2004-09-28 21:48:02 +00003221 Value *LHSVal, *RHSVal;
3222 ConstantInt *LHSCst, *RHSCst;
3223 Instruction::BinaryOps LHSCC, RHSCC;
3224 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3225 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3226 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3227 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003228 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003229 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3230 // Ensure that the larger constant is on the RHS.
3231 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3232 SetCondInst *LHS = cast<SetCondInst>(Op0);
3233 if (cast<ConstantBool>(Cmp)->getValue()) {
3234 std::swap(LHS, RHS);
3235 std::swap(LHSCst, RHSCst);
3236 std::swap(LHSCC, RHSCC);
3237 }
3238
3239 // At this point, we know we have have two setcc instructions
3240 // comparing a value against two constants and and'ing the result
3241 // together. Because of the above check, we know that we only have
3242 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3243 // FoldSetCCLogical check above), that the two constants are not
3244 // equal.
3245 assert(LHSCst != RHSCst && "Compares not folded above?");
3246
3247 switch (LHSCC) {
3248 default: assert(0 && "Unknown integer condition code!");
3249 case Instruction::SetEQ:
3250 switch (RHSCC) {
3251 default: assert(0 && "Unknown integer condition code!");
3252 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3253 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003254 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003255 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3256 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3257 return ReplaceInstUsesWith(I, LHS);
3258 }
3259 case Instruction::SetNE:
3260 switch (RHSCC) {
3261 default: assert(0 && "Unknown integer condition code!");
3262 case Instruction::SetLT:
3263 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3264 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3265 break; // (X != 13 & X < 15) -> no change
3266 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3267 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3268 return ReplaceInstUsesWith(I, RHS);
3269 case Instruction::SetNE:
3270 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3271 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3272 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3273 LHSVal->getName()+".off");
3274 InsertNewInstBefore(Add, I);
3275 const Type *UnsType = Add->getType()->getUnsignedVersion();
3276 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3277 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3279 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3280 }
3281 break; // (X != 13 & X != 15) -> no change
3282 }
3283 break;
3284 case Instruction::SetLT:
3285 switch (RHSCC) {
3286 default: assert(0 && "Unknown integer condition code!");
3287 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3288 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003289 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003290 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3291 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3292 return ReplaceInstUsesWith(I, LHS);
3293 }
3294 case Instruction::SetGT:
3295 switch (RHSCC) {
3296 default: assert(0 && "Unknown integer condition code!");
3297 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3298 return ReplaceInstUsesWith(I, LHS);
3299 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3300 return ReplaceInstUsesWith(I, RHS);
3301 case Instruction::SetNE:
3302 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3303 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3304 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003305 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3306 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003307 }
3308 }
3309 }
3310 }
3311
Chris Lattner3af10532006-05-05 06:39:07 +00003312 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3313 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003314 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003315 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003316 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003317 // Only do this if the casts both really cause code to be generated.
3318 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3319 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003320 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3321 Op1C->getOperand(0),
3322 I.getName());
3323 InsertNewInstBefore(NewOp, I);
3324 return new CastInst(NewOp, I.getType());
3325 }
3326 }
3327
Chris Lattner113f4f42002-06-25 16:13:24 +00003328 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003329}
3330
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003331/// CollectBSwapParts - Look to see if the specified value defines a single byte
3332/// in the result. If it does, and if the specified byte hasn't been filled in
3333/// yet, fill it in and return false.
3334static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3335 Instruction *I = dyn_cast<Instruction>(V);
3336 if (I == 0) return true;
3337
3338 // If this is an or instruction, it is an inner node of the bswap.
3339 if (I->getOpcode() == Instruction::Or)
3340 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3341 CollectBSwapParts(I->getOperand(1), ByteValues);
3342
3343 // If this is a shift by a constant int, and it is "24", then its operand
3344 // defines a byte. We only handle unsigned types here.
3345 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3346 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003347 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003348 8*(ByteValues.size()-1))
3349 return true;
3350
3351 unsigned DestNo;
3352 if (I->getOpcode() == Instruction::Shl) {
3353 // X << 24 defines the top byte with the lowest of the input bytes.
3354 DestNo = ByteValues.size()-1;
3355 } else {
3356 // X >>u 24 defines the low byte with the highest of the input bytes.
3357 DestNo = 0;
3358 }
3359
3360 // If the destination byte value is already defined, the values are or'd
3361 // together, which isn't a bswap (unless it's an or of the same bits).
3362 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3363 return true;
3364 ByteValues[DestNo] = I->getOperand(0);
3365 return false;
3366 }
3367
3368 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3369 // don't have this.
3370 Value *Shift = 0, *ShiftLHS = 0;
3371 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3372 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3373 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3374 return true;
3375 Instruction *SI = cast<Instruction>(Shift);
3376
3377 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003378 if (ShiftAmt->getZExtValue() & 7 ||
3379 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003380 return true;
3381
3382 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3383 unsigned DestByte;
3384 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003385 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003386 break;
3387 // Unknown mask for bswap.
3388 if (DestByte == ByteValues.size()) return true;
3389
Reid Spencere0fc4df2006-10-20 07:07:24 +00003390 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003391 unsigned SrcByte;
3392 if (SI->getOpcode() == Instruction::Shl)
3393 SrcByte = DestByte - ShiftBytes;
3394 else
3395 SrcByte = DestByte + ShiftBytes;
3396
3397 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3398 if (SrcByte != ByteValues.size()-DestByte-1)
3399 return true;
3400
3401 // If the destination byte value is already defined, the values are or'd
3402 // together, which isn't a bswap (unless it's an or of the same bits).
3403 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3404 return true;
3405 ByteValues[DestByte] = SI->getOperand(0);
3406 return false;
3407}
3408
3409/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3410/// If so, insert the new bswap intrinsic and return it.
3411Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3412 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3413 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3414 return 0;
3415
3416 /// ByteValues - For each byte of the result, we keep track of which value
3417 /// defines each byte.
3418 std::vector<Value*> ByteValues;
3419 ByteValues.resize(I.getType()->getPrimitiveSize());
3420
3421 // Try to find all the pieces corresponding to the bswap.
3422 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3423 CollectBSwapParts(I.getOperand(1), ByteValues))
3424 return 0;
3425
3426 // Check to see if all of the bytes come from the same value.
3427 Value *V = ByteValues[0];
3428 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3429
3430 // Check to make sure that all of the bytes come from the same value.
3431 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3432 if (ByteValues[i] != V)
3433 return 0;
3434
3435 // If they do then *success* we can turn this into a bswap. Figure out what
3436 // bswap to make it into.
3437 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003438 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003439 if (I.getType() == Type::UShortTy)
3440 FnName = "llvm.bswap.i16";
3441 else if (I.getType() == Type::UIntTy)
3442 FnName = "llvm.bswap.i32";
3443 else if (I.getType() == Type::ULongTy)
3444 FnName = "llvm.bswap.i64";
3445 else
3446 assert(0 && "Unknown integer type!");
3447 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3448
3449 return new CallInst(F, V);
3450}
3451
3452
Chris Lattner113f4f42002-06-25 16:13:24 +00003453Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003454 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003456
Chris Lattner81a7a232004-10-16 18:11:37 +00003457 if (isa<UndefValue>(Op1))
3458 return ReplaceInstUsesWith(I, // X | undef -> -1
3459 ConstantIntegral::getAllOnesValue(I.getType()));
3460
Chris Lattner5b2edb12006-02-12 08:02:11 +00003461 // or X, X = X
3462 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003463 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003464
Chris Lattner5b2edb12006-02-12 08:02:11 +00003465 // See if we can simplify any instructions used by the instruction whose sole
3466 // purpose is to compute bits we don't care about.
3467 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003468 if (!isa<PackedType>(I.getType()) &&
3469 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003470 KnownZero, KnownOne))
3471 return &I;
3472
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003473 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003474 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003475 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003476 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3477 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003478 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3479 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003480 InsertNewInstBefore(Or, I);
3481 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3482 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003483
Chris Lattnerd4252a72004-07-30 07:50:03 +00003484 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3485 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3486 std::string Op0Name = Op0->getName(); Op0->setName("");
3487 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3488 InsertNewInstBefore(Or, I);
3489 return BinaryOperator::createXor(Or,
3490 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003491 }
Chris Lattner183b3362004-04-09 19:05:30 +00003492
3493 // Try to fold constant and into select arguments.
3494 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003495 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003496 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003497 if (isa<PHINode>(Op0))
3498 if (Instruction *NV = FoldOpIntoPhi(I))
3499 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003500 }
3501
Chris Lattner330628a2006-01-06 17:59:59 +00003502 Value *A = 0, *B = 0;
3503 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003504
3505 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3506 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3507 return ReplaceInstUsesWith(I, Op1);
3508 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3509 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3510 return ReplaceInstUsesWith(I, Op0);
3511
Chris Lattnerb7845d62006-07-10 20:25:24 +00003512 // (A | B) | C and A | (B | C) -> bswap if possible.
3513 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003514 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003515 match(Op1, m_Or(m_Value(), m_Value())) ||
3516 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3517 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003518 if (Instruction *BSwap = MatchBSwap(I))
3519 return BSwap;
3520 }
3521
Chris Lattnerb62f5082005-05-09 04:58:36 +00003522 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3523 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003524 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003525 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3526 Op0->setName("");
3527 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3528 }
3529
3530 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3531 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003532 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003533 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3534 Op0->setName("");
3535 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3536 }
3537
Chris Lattner15212982005-09-18 03:42:07 +00003538 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003539 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003540 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3541
3542 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3543 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3544
3545
Chris Lattner01f56c62005-09-18 06:02:59 +00003546 // If we have: ((V + N) & C1) | (V & C2)
3547 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3548 // replace with V+N.
3549 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003550 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003551 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003552 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3553 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003554 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003555 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003556 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003557 return ReplaceInstUsesWith(I, A);
3558 }
3559 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003560 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003561 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3562 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003563 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003564 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003565 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003566 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003567 }
3568 }
3569 }
Chris Lattner812aab72003-08-12 19:11:07 +00003570
Chris Lattnerd4252a72004-07-30 07:50:03 +00003571 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3572 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003573 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003574 ConstantIntegral::getAllOnesValue(I.getType()));
3575 } else {
3576 A = 0;
3577 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003578 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003579 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3580 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003581 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003582 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003583
Misha Brukman9c003d82004-07-30 12:50:08 +00003584 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003585 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3586 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3587 I.getName()+".demorgan"), I);
3588 return BinaryOperator::createNot(And);
3589 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003590 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003591
Chris Lattner3ac7c262003-08-13 20:16:26 +00003592 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003593 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003594 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3595 return R;
3596
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003597 Value *LHSVal, *RHSVal;
3598 ConstantInt *LHSCst, *RHSCst;
3599 Instruction::BinaryOps LHSCC, RHSCC;
3600 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3601 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3602 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3603 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003604 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003605 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3606 // Ensure that the larger constant is on the RHS.
3607 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3608 SetCondInst *LHS = cast<SetCondInst>(Op0);
3609 if (cast<ConstantBool>(Cmp)->getValue()) {
3610 std::swap(LHS, RHS);
3611 std::swap(LHSCst, RHSCst);
3612 std::swap(LHSCC, RHSCC);
3613 }
3614
3615 // At this point, we know we have have two setcc instructions
3616 // comparing a value against two constants and or'ing the result
3617 // together. Because of the above check, we know that we only have
3618 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3619 // FoldSetCCLogical check above), that the two constants are not
3620 // equal.
3621 assert(LHSCst != RHSCst && "Compares not folded above?");
3622
3623 switch (LHSCC) {
3624 default: assert(0 && "Unknown integer condition code!");
3625 case Instruction::SetEQ:
3626 switch (RHSCC) {
3627 default: assert(0 && "Unknown integer condition code!");
3628 case Instruction::SetEQ:
3629 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3630 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3631 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3632 LHSVal->getName()+".off");
3633 InsertNewInstBefore(Add, I);
3634 const Type *UnsType = Add->getType()->getUnsignedVersion();
3635 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3636 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3637 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3638 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3639 }
3640 break; // (X == 13 | X == 15) -> no change
3641
Chris Lattner5c219462005-04-19 06:04:18 +00003642 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3643 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003644 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3645 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3646 return ReplaceInstUsesWith(I, RHS);
3647 }
3648 break;
3649 case Instruction::SetNE:
3650 switch (RHSCC) {
3651 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003652 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3653 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3654 return ReplaceInstUsesWith(I, LHS);
3655 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003656 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003657 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003658 }
3659 break;
3660 case Instruction::SetLT:
3661 switch (RHSCC) {
3662 default: assert(0 && "Unknown integer condition code!");
3663 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3664 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003665 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3666 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003667 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3668 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3669 return ReplaceInstUsesWith(I, RHS);
3670 }
3671 break;
3672 case Instruction::SetGT:
3673 switch (RHSCC) {
3674 default: assert(0 && "Unknown integer condition code!");
3675 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3676 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3677 return ReplaceInstUsesWith(I, LHS);
3678 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3679 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003680 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003681 }
3682 }
3683 }
3684 }
Chris Lattner3af10532006-05-05 06:39:07 +00003685
3686 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3687 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003688 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003689 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003690 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003691 // Only do this if the casts both really cause code to be generated.
3692 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3693 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003694 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3695 Op1C->getOperand(0),
3696 I.getName());
3697 InsertNewInstBefore(NewOp, I);
3698 return new CastInst(NewOp, I.getType());
3699 }
3700 }
3701
Chris Lattner15212982005-09-18 03:42:07 +00003702
Chris Lattner113f4f42002-06-25 16:13:24 +00003703 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003704}
3705
Chris Lattnerc2076352004-02-16 01:20:27 +00003706// XorSelf - Implements: X ^ X --> 0
3707struct XorSelf {
3708 Value *RHS;
3709 XorSelf(Value *rhs) : RHS(rhs) {}
3710 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3711 Instruction *apply(BinaryOperator &Xor) const {
3712 return &Xor;
3713 }
3714};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003715
3716
Chris Lattner113f4f42002-06-25 16:13:24 +00003717Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003718 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003720
Chris Lattner81a7a232004-10-16 18:11:37 +00003721 if (isa<UndefValue>(Op1))
3722 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3723
Chris Lattnerc2076352004-02-16 01:20:27 +00003724 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3725 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3726 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003727 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003728 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003729
3730 // See if we can simplify any instructions used by the instruction whose sole
3731 // purpose is to compute bits we don't care about.
3732 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003733 if (!isa<PackedType>(I.getType()) &&
3734 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003735 KnownZero, KnownOne))
3736 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003737
Chris Lattner97638592003-07-23 21:37:07 +00003738 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003739 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003740 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003741 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003742 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003743 return new SetCondInst(SCI->getInverseCondition(),
3744 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003745
Chris Lattner8f2f5982003-11-05 01:06:05 +00003746 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003747 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3748 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003749 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3750 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003751 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003752 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003753 }
Chris Lattner023a4832004-06-18 06:07:51 +00003754
3755 // ~(~X & Y) --> (X | ~Y)
3756 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3757 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3758 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3759 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003760 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003761 Op0I->getOperand(1)->getName()+".not");
3762 InsertNewInstBefore(NotY, I);
3763 return BinaryOperator::createOr(Op0NotVal, NotY);
3764 }
3765 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003766
Chris Lattner97638592003-07-23 21:37:07 +00003767 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003768 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003769 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003770 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003771 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3772 return BinaryOperator::createSub(
3773 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003774 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003775 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003776 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003777 } else if (Op0I->getOpcode() == Instruction::Or) {
3778 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3779 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3780 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3781 // Anything in both C1 and C2 is known to be zero, remove it from
3782 // NewRHS.
3783 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3784 NewRHS = ConstantExpr::getAnd(NewRHS,
3785 ConstantExpr::getNot(CommonBits));
3786 WorkList.push_back(Op0I);
3787 I.setOperand(0, Op0I->getOperand(0));
3788 I.setOperand(1, NewRHS);
3789 return &I;
3790 }
Chris Lattner97638592003-07-23 21:37:07 +00003791 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003792 }
Chris Lattner183b3362004-04-09 19:05:30 +00003793
3794 // Try to fold constant and into select arguments.
3795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003797 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003798 if (isa<PHINode>(Op0))
3799 if (Instruction *NV = FoldOpIntoPhi(I))
3800 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003801 }
3802
Chris Lattnerbb74e222003-03-10 23:06:50 +00003803 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003804 if (X == Op1)
3805 return ReplaceInstUsesWith(I,
3806 ConstantIntegral::getAllOnesValue(I.getType()));
3807
Chris Lattnerbb74e222003-03-10 23:06:50 +00003808 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003809 if (X == Op0)
3810 return ReplaceInstUsesWith(I,
3811 ConstantIntegral::getAllOnesValue(I.getType()));
3812
Chris Lattnerdcd07922006-04-01 08:03:55 +00003813 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003814 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003815 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003816 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003817 I.swapOperands();
3818 std::swap(Op0, Op1);
3819 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003820 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003821 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003822 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003823 } else if (Op1I->getOpcode() == Instruction::Xor) {
3824 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3825 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3826 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3827 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003828 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3829 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3830 Op1I->swapOperands();
3831 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3832 I.swapOperands(); // Simplified below.
3833 std::swap(Op0, Op1);
3834 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003835 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003836
Chris Lattnerdcd07922006-04-01 08:03:55 +00003837 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003838 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003839 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003840 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003841 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003842 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3843 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003844 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003845 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003846 } else if (Op0I->getOpcode() == Instruction::Xor) {
3847 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3848 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3849 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3850 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003851 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3852 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3853 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003854 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3855 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003856 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3857 InsertNewInstBefore(N, I);
3858 return BinaryOperator::createAnd(N, Op1);
3859 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003860 }
3861
Chris Lattner3ac7c262003-08-13 20:16:26 +00003862 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3863 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3864 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3865 return R;
3866
Chris Lattner3af10532006-05-05 06:39:07 +00003867 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3868 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003869 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003870 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003871 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003872 // Only do this if the casts both really cause code to be generated.
3873 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3874 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003875 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3876 Op1C->getOperand(0),
3877 I.getName());
3878 InsertNewInstBefore(NewOp, I);
3879 return new CastInst(NewOp, I.getType());
3880 }
3881 }
3882
Chris Lattner113f4f42002-06-25 16:13:24 +00003883 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003884}
3885
Chris Lattner6862fbd2004-09-29 17:40:11 +00003886static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003887 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003888}
3889
3890/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3891/// overflowed for this type.
3892static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3893 ConstantInt *In2) {
3894 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3895
3896 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003897 return cast<ConstantInt>(Result)->getZExtValue() <
3898 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003899 if (isPositive(In1) != isPositive(In2))
3900 return false;
3901 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003902 return cast<ConstantInt>(Result)->getSExtValue() <
3903 cast<ConstantInt>(In1)->getSExtValue();
3904 return cast<ConstantInt>(Result)->getSExtValue() >
3905 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003906}
3907
Chris Lattner0798af32005-01-13 20:14:25 +00003908/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3909/// code necessary to compute the offset from the base pointer (without adding
3910/// in the base pointer). Return the result as a signed integer of intptr size.
3911static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3912 TargetData &TD = IC.getTargetData();
3913 gep_type_iterator GTI = gep_type_begin(GEP);
3914 const Type *UIntPtrTy = TD.getIntPtrType();
3915 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3916 Value *Result = Constant::getNullValue(SIntPtrTy);
3917
3918 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003919 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003920
Chris Lattner0798af32005-01-13 20:14:25 +00003921 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3922 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003923 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003924 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003925 SIntPtrTy);
3926 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3927 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003928 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003929 Scale = ConstantExpr::getMul(OpC, Scale);
3930 if (Constant *RC = dyn_cast<Constant>(Result))
3931 Result = ConstantExpr::getAdd(RC, Scale);
3932 else {
3933 // Emit an add instruction.
3934 Result = IC.InsertNewInstBefore(
3935 BinaryOperator::createAdd(Result, Scale,
3936 GEP->getName()+".offs"), I);
3937 }
3938 }
3939 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003940 // Convert to correct type.
3941 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3942 Op->getName()+".c"), I);
3943 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003944 // We'll let instcombine(mul) convert this to a shl if possible.
3945 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3946 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003947
3948 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003949 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003950 GEP->getName()+".offs"), I);
3951 }
3952 }
3953 return Result;
3954}
3955
3956/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3957/// else. At this point we know that the GEP is on the LHS of the comparison.
3958Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3959 Instruction::BinaryOps Cond,
3960 Instruction &I) {
3961 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003962
3963 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3964 if (isa<PointerType>(CI->getOperand(0)->getType()))
3965 RHS = CI->getOperand(0);
3966
Chris Lattner0798af32005-01-13 20:14:25 +00003967 Value *PtrBase = GEPLHS->getOperand(0);
3968 if (PtrBase == RHS) {
3969 // As an optimization, we don't actually have to compute the actual value of
3970 // OFFSET if this is a seteq or setne comparison, just return whether each
3971 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003972 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3973 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003974 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3975 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003976 bool EmitIt = true;
3977 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3978 if (isa<UndefValue>(C)) // undef index -> undef.
3979 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3980 if (C->isNullValue())
3981 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003982 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3983 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003984 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003985 return ReplaceInstUsesWith(I, // No comparison is needed here.
3986 ConstantBool::get(Cond == Instruction::SetNE));
3987 }
3988
3989 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003990 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003991 new SetCondInst(Cond, GEPLHS->getOperand(i),
3992 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3993 if (InVal == 0)
3994 InVal = Comp;
3995 else {
3996 InVal = InsertNewInstBefore(InVal, I);
3997 InsertNewInstBefore(Comp, I);
3998 if (Cond == Instruction::SetNE) // True if any are unequal
3999 InVal = BinaryOperator::createOr(InVal, Comp);
4000 else // True if all are equal
4001 InVal = BinaryOperator::createAnd(InVal, Comp);
4002 }
4003 }
4004 }
4005
4006 if (InVal)
4007 return InVal;
4008 else
4009 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4010 ConstantBool::get(Cond == Instruction::SetEQ));
4011 }
Chris Lattner0798af32005-01-13 20:14:25 +00004012
4013 // Only lower this if the setcc is the only user of the GEP or if we expect
4014 // the result to fold to a constant!
4015 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4016 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4017 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4018 return new SetCondInst(Cond, Offset,
4019 Constant::getNullValue(Offset->getType()));
4020 }
4021 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004022 // If the base pointers are different, but the indices are the same, just
4023 // compare the base pointer.
4024 if (PtrBase != GEPRHS->getOperand(0)) {
4025 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004026 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004027 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004028 if (IndicesTheSame)
4029 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4030 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4031 IndicesTheSame = false;
4032 break;
4033 }
4034
4035 // If all indices are the same, just compare the base pointers.
4036 if (IndicesTheSame)
4037 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4038 GEPRHS->getOperand(0));
4039
4040 // Otherwise, the base pointers are different and the indices are
4041 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004042 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004043 }
Chris Lattner0798af32005-01-13 20:14:25 +00004044
Chris Lattner81e84172005-01-13 22:25:21 +00004045 // If one of the GEPs has all zero indices, recurse.
4046 bool AllZeros = true;
4047 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4048 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4049 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4050 AllZeros = false;
4051 break;
4052 }
4053 if (AllZeros)
4054 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4055 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004056
4057 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004058 AllZeros = true;
4059 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4060 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4061 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4062 AllZeros = false;
4063 break;
4064 }
4065 if (AllZeros)
4066 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4067
Chris Lattner4fa89822005-01-14 00:20:05 +00004068 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4069 // If the GEPs only differ by one index, compare it.
4070 unsigned NumDifferences = 0; // Keep track of # differences.
4071 unsigned DiffOperand = 0; // The operand that differs.
4072 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4073 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004074 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4075 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004076 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004077 NumDifferences = 2;
4078 break;
4079 } else {
4080 if (NumDifferences++) break;
4081 DiffOperand = i;
4082 }
4083 }
4084
4085 if (NumDifferences == 0) // SAME GEP?
4086 return ReplaceInstUsesWith(I, // No comparison is needed here.
4087 ConstantBool::get(Cond == Instruction::SetEQ));
4088 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004089 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4090 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004091
4092 // Convert the operands to signed values to make sure to perform a
4093 // signed comparison.
4094 const Type *NewTy = LHSV->getType()->getSignedVersion();
4095 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004096 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004097 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004098 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004099 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004100 }
4101 }
4102
Chris Lattner0798af32005-01-13 20:14:25 +00004103 // Only lower this if the setcc is the only user of the GEP or if we expect
4104 // the result to fold to a constant!
4105 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4106 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4107 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4108 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4109 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4110 return new SetCondInst(Cond, L, R);
4111 }
4112 }
4113 return 0;
4114}
4115
4116
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004117Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004118 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4120 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004121
4122 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004123 if (Op0 == Op1)
4124 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004125
Chris Lattner81a7a232004-10-16 18:11:37 +00004126 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4127 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4128
Chris Lattner15ff1e12004-11-14 07:33:16 +00004129 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4130 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004131 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4132 isa<ConstantPointerNull>(Op0)) &&
4133 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004134 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004135 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4136
4137 // setcc's with boolean values can always be turned into bitwise operations
4138 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004139 switch (I.getOpcode()) {
4140 default: assert(0 && "Invalid setcc instruction!");
4141 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004142 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004143 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004144 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004145 }
Chris Lattner4456da62004-08-11 00:50:51 +00004146 case Instruction::SetNE:
4147 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004148
Chris Lattner4456da62004-08-11 00:50:51 +00004149 case Instruction::SetGT:
4150 std::swap(Op0, Op1); // Change setgt -> setlt
4151 // FALL THROUGH
4152 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4153 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4154 InsertNewInstBefore(Not, I);
4155 return BinaryOperator::createAnd(Not, Op1);
4156 }
4157 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004158 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004159 // FALL THROUGH
4160 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4161 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4162 InsertNewInstBefore(Not, I);
4163 return BinaryOperator::createOr(Not, Op1);
4164 }
4165 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004166 }
4167
Chris Lattner2dd01742004-06-09 04:24:29 +00004168 // See if we are doing a comparison between a constant and an instruction that
4169 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004171 // Check to see if we are comparing against the minimum or maximum value...
4172 if (CI->isMinValue()) {
4173 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004174 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004175 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004176 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004177 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4178 return BinaryOperator::createSetEQ(Op0, Op1);
4179 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4180 return BinaryOperator::createSetNE(Op0, Op1);
4181
4182 } else if (CI->isMaxValue()) {
4183 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004184 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004185 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004186 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004187 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4188 return BinaryOperator::createSetEQ(Op0, Op1);
4189 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4190 return BinaryOperator::createSetNE(Op0, Op1);
4191
4192 // Comparing against a value really close to min or max?
4193 } else if (isMinValuePlusOne(CI)) {
4194 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4195 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4196 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4197 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4198
4199 } else if (isMaxValueMinusOne(CI)) {
4200 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4201 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4202 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4203 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4204 }
4205
4206 // If we still have a setle or setge instruction, turn it into the
4207 // appropriate setlt or setgt instruction. Since the border cases have
4208 // already been handled above, this requires little checking.
4209 //
4210 if (I.getOpcode() == Instruction::SetLE)
4211 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4212 if (I.getOpcode() == Instruction::SetGE)
4213 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4214
Chris Lattneree0f2802006-02-12 02:07:56 +00004215
4216 // See if we can fold the comparison based on bits known to be zero or one
4217 // in the input.
4218 uint64_t KnownZero, KnownOne;
4219 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4220 KnownZero, KnownOne, 0))
4221 return &I;
4222
4223 // Given the known and unknown bits, compute a range that the LHS could be
4224 // in.
4225 if (KnownOne | KnownZero) {
4226 if (Ty->isUnsigned()) { // Unsigned comparison.
4227 uint64_t Min, Max;
4228 uint64_t RHSVal = CI->getZExtValue();
4229 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4230 Min, Max);
4231 switch (I.getOpcode()) { // LE/GE have been folded already.
4232 default: assert(0 && "Unknown setcc opcode!");
4233 case Instruction::SetEQ:
4234 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004235 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004236 break;
4237 case Instruction::SetNE:
4238 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004239 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004240 break;
4241 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004242 if (Max < RHSVal)
4243 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4244 if (Min > RHSVal)
4245 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004246 break;
4247 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004248 if (Min > RHSVal)
4249 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4250 if (Max < RHSVal)
4251 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004252 break;
4253 }
4254 } else { // Signed comparison.
4255 int64_t Min, Max;
4256 int64_t RHSVal = CI->getSExtValue();
4257 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4258 Min, Max);
4259 switch (I.getOpcode()) { // LE/GE have been folded already.
4260 default: assert(0 && "Unknown setcc opcode!");
4261 case Instruction::SetEQ:
4262 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004263 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004264 break;
4265 case Instruction::SetNE:
4266 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004267 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004268 break;
4269 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004270 if (Max < RHSVal)
4271 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4272 if (Min > RHSVal)
4273 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004274 break;
4275 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004276 if (Min > RHSVal)
4277 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4278 if (Max < RHSVal)
4279 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004280 break;
4281 }
4282 }
4283 }
4284
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004285 // Since the RHS is a constantInt (CI), if the left hand side is an
4286 // instruction, see if that instruction also has constants so that the
4287 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004288 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004289 switch (LHSI->getOpcode()) {
4290 case Instruction::And:
4291 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4292 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004293 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4294
4295 // If an operand is an AND of a truncating cast, we can widen the
4296 // and/compare to be the input width without changing the value
4297 // produced, eliminating a cast.
4298 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4299 // We can do this transformation if either the AND constant does not
4300 // have its sign bit set or if it is an equality comparison.
4301 // Extending a relational comparison when we're checking the sign
4302 // bit would not work.
4303 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4304 (I.isEquality() ||
4305 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4306 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4307 ConstantInt *NewCST;
4308 ConstantInt *NewCI;
4309 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004310 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004311 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004312 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004313 CI->getZExtValue());
4314 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004315 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004316 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004317 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004318 CI->getZExtValue());
4319 }
4320 Instruction *NewAnd =
4321 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4322 LHSI->getName());
4323 InsertNewInstBefore(NewAnd, I);
4324 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4325 }
4326 }
4327
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004328 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4329 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4330 // happens a LOT in code produced by the C front-end, for bitfield
4331 // access.
4332 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004333
4334 // Check to see if there is a noop-cast between the shift and the and.
4335 if (!Shift) {
4336 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4337 if (CI->getOperand(0)->getType()->isIntegral() &&
4338 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4339 CI->getType()->getPrimitiveSizeInBits())
4340 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4341 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004342
Reid Spencere0fc4df2006-10-20 07:07:24 +00004343 ConstantInt *ShAmt;
4344 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004345 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4346 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004347
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004348 // We can fold this as long as we can't shift unknown bits
4349 // into the mask. This can only happen with signed shift
4350 // rights, as they sign-extend.
4351 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004352 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004353 if (!CanFold) {
4354 // To test for the bad case of the signed shr, see if any
4355 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004356 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004357 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4358
Reid Spencere0fc4df2006-10-20 07:07:24 +00004359 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004360 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004361 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4362 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004363 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4364 CanFold = true;
4365 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004366
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004367 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004368 Constant *NewCst;
4369 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004370 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004371 else
4372 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004373
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004374 // Check to see if we are shifting out any of the bits being
4375 // compared.
4376 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4377 // If we shifted bits out, the fold is not going to work out.
4378 // As a special case, check to see if this means that the
4379 // result is always true or false now.
4380 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004381 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004382 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004383 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004384 } else {
4385 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004386 Constant *NewAndCST;
4387 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004388 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004389 else
4390 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4391 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004392 if (AndTy == Ty)
4393 LHSI->setOperand(0, Shift->getOperand(0));
4394 else {
4395 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4396 *Shift);
4397 LHSI->setOperand(0, NewCast);
4398 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004399 WorkList.push_back(Shift); // Shift is dead.
4400 AddUsesToWorkList(I);
4401 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004402 }
4403 }
Chris Lattner35167c32004-06-09 07:59:58 +00004404 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004405
4406 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4407 // preferable because it allows the C<<Y expression to be hoisted out
4408 // of a loop if Y is invariant and X is not.
4409 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004410 I.isEquality() && !Shift->isArithmeticShift() &&
4411 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004412 // Compute C << Y.
4413 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004414 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004415 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4416 "tmp");
4417 } else {
4418 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004419 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004420 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004421 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004422 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004423 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004424 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004425 }
4426 InsertNewInstBefore(cast<Instruction>(NS), I);
4427
4428 // If C's sign doesn't agree with the and, insert a cast now.
4429 if (NS->getType() != LHSI->getType())
4430 NS = InsertCastBefore(NS, LHSI->getType(), I);
4431
4432 Value *ShiftOp = Shift->getOperand(0);
4433 if (ShiftOp->getType() != LHSI->getType())
4434 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4435
4436 // Compute X & (C << Y).
4437 Instruction *NewAnd =
4438 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4439 InsertNewInstBefore(NewAnd, I);
4440
4441 I.setOperand(0, NewAnd);
4442 return &I;
4443 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004444 }
4445 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004446
Chris Lattner272d5ca2004-09-28 18:22:15 +00004447 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004448 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004449 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004450 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4451
4452 // Check that the shift amount is in range. If not, don't perform
4453 // undefined shifts. When the shift is visited it will be
4454 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004455 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004456 break;
4457
Chris Lattner272d5ca2004-09-28 18:22:15 +00004458 // If we are comparing against bits always shifted out, the
4459 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004460 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004461 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004462 if (Comp != CI) {// Comparing against a bit that we know is zero.
4463 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4464 Constant *Cst = ConstantBool::get(IsSetNE);
4465 return ReplaceInstUsesWith(I, Cst);
4466 }
4467
4468 if (LHSI->hasOneUse()) {
4469 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004470 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004471 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4472
4473 Constant *Mask;
4474 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004475 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004476 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004477 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004478 } else {
4479 Mask = ConstantInt::getAllOnesValue(CI->getType());
4480 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004481
Chris Lattner272d5ca2004-09-28 18:22:15 +00004482 Instruction *AndI =
4483 BinaryOperator::createAnd(LHSI->getOperand(0),
4484 Mask, LHSI->getName()+".mask");
4485 Value *And = InsertNewInstBefore(AndI, I);
4486 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004487 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004488 }
4489 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004490 }
4491 break;
4492
Reid Spencerfdff9382006-11-08 06:47:33 +00004493 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4494 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004495 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004496 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004497 // Check that the shift amount is in range. If not, don't perform
4498 // undefined shifts. When the shift is visited it will be
4499 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004500 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004501 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004502 break;
4503
Chris Lattner1023b872004-09-27 16:18:50 +00004504 // If we are comparing against bits always shifted out, the
4505 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004506 Constant *Comp;
4507 if (CI->getType()->isUnsigned())
4508 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4509 ShAmt);
4510 else
4511 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4512 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004513
Chris Lattner1023b872004-09-27 16:18:50 +00004514 if (Comp != CI) {// Comparing against a bit that we know is zero.
4515 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4516 Constant *Cst = ConstantBool::get(IsSetNE);
4517 return ReplaceInstUsesWith(I, Cst);
4518 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004519
Chris Lattner1023b872004-09-27 16:18:50 +00004520 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004521 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004522
Chris Lattner1023b872004-09-27 16:18:50 +00004523 // Otherwise strength reduce the shift into an and.
4524 uint64_t Val = ~0ULL; // All ones.
4525 Val <<= ShAmtVal; // Shift over to the right spot.
4526
4527 Constant *Mask;
4528 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004529 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004530 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004531 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004532 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004534
Chris Lattner1023b872004-09-27 16:18:50 +00004535 Instruction *AndI =
4536 BinaryOperator::createAnd(LHSI->getOperand(0),
4537 Mask, LHSI->getName()+".mask");
4538 Value *And = InsertNewInstBefore(AndI, I);
4539 return new SetCondInst(I.getOpcode(), And,
4540 ConstantExpr::getShl(CI, ShAmt));
4541 }
Chris Lattner1023b872004-09-27 16:18:50 +00004542 }
4543 }
4544 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004545
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004546 case Instruction::SDiv:
4547 case Instruction::UDiv:
4548 // Fold: setcc ([us]div X, C1), C2 -> range test
4549 // Fold this div into the comparison, producing a range check.
4550 // Determine, based on the divide type, what the range is being
4551 // checked. If there is an overflow on the low or high side, remember
4552 // it, otherwise compute the range [low, hi) bounding the new value.
4553 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004554 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004555 // FIXME: If the operand types don't match the type of the divide
4556 // then don't attempt this transform. The code below doesn't have the
4557 // logic to deal with a signed divide and an unsigned compare (and
4558 // vice versa). This is because (x /s C1) <s C2 produces different
4559 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4560 // (x /u C1) <u C2. Simply casting the operands and result won't
4561 // work. :( The if statement below tests that condition and bails
4562 // if it finds it.
4563 const Type* DivRHSTy = DivRHS->getType();
4564 unsigned DivOpCode = LHSI->getOpcode();
4565 if (I.isEquality() &&
4566 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4567 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4568 break;
4569
4570 // Initialize the variables that will indicate the nature of the
4571 // range check.
4572 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004573 ConstantInt *LoBound = 0, *HiBound = 0;
4574
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004575 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4576 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4577 // C2 (CI). By solving for X we can turn this into a range check
4578 // instead of computing a divide.
4579 ConstantInt *Prod =
4580 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004581
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004582 // Determine if the product overflows by seeing if the product is
4583 // not equal to the divide. Make sure we do the same kind of divide
4584 // as in the LHS instruction that we're folding.
4585 bool ProdOV = !DivRHS->isNullValue() &&
4586 (DivOpCode == Instruction::SDiv ?
4587 ConstantExpr::getSDiv(Prod, DivRHS) :
4588 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4589
4590 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004591 Instruction::BinaryOps Opcode = I.getOpcode();
4592
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004593 if (DivRHS->isNullValue()) {
4594 // Don't hack on divide by zeros!
4595 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004596 LoBound = Prod;
4597 LoOverflow = ProdOV;
4598 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004599 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004600 if (CI->isNullValue()) { // (X / pos) op 0
4601 // Can't overflow.
4602 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4603 HiBound = DivRHS;
4604 } else if (isPositive(CI)) { // (X / pos) op pos
4605 LoBound = Prod;
4606 LoOverflow = ProdOV;
4607 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4608 } else { // (X / pos) op neg
4609 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4610 LoOverflow = AddWithOverflow(LoBound, Prod,
4611 cast<ConstantInt>(DivRHSH));
4612 HiBound = Prod;
4613 HiOverflow = ProdOV;
4614 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004615 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004616 if (CI->isNullValue()) { // (X / neg) op 0
4617 LoBound = AddOne(DivRHS);
4618 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004619 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004620 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004621 } else if (isPositive(CI)) { // (X / neg) op pos
4622 HiOverflow = LoOverflow = ProdOV;
4623 if (!LoOverflow)
4624 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4625 HiBound = AddOne(Prod);
4626 } else { // (X / neg) op neg
4627 LoBound = Prod;
4628 LoOverflow = HiOverflow = ProdOV;
4629 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4630 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004631
Chris Lattnera92af962004-10-11 19:40:04 +00004632 // Dividing by a negate swaps the condition.
4633 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004634 }
4635
4636 if (LoBound) {
4637 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004638 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004639 default: assert(0 && "Unhandled setcc opcode!");
4640 case Instruction::SetEQ:
4641 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004642 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004643 else if (HiOverflow)
4644 return new SetCondInst(Instruction::SetGE, X, LoBound);
4645 else if (LoOverflow)
4646 return new SetCondInst(Instruction::SetLT, X, HiBound);
4647 else
4648 return InsertRangeTest(X, LoBound, HiBound, true, I);
4649 case Instruction::SetNE:
4650 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004651 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004652 else if (HiOverflow)
4653 return new SetCondInst(Instruction::SetLT, X, LoBound);
4654 else if (LoOverflow)
4655 return new SetCondInst(Instruction::SetGE, X, HiBound);
4656 else
4657 return InsertRangeTest(X, LoBound, HiBound, false, I);
4658 case Instruction::SetLT:
4659 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004660 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004661 return new SetCondInst(Instruction::SetLT, X, LoBound);
4662 case Instruction::SetGT:
4663 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004664 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004665 return new SetCondInst(Instruction::SetGE, X, HiBound);
4666 }
4667 }
4668 }
4669 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004670 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004671
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004672 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004673 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004674 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4675
Reid Spencere0fc4df2006-10-20 07:07:24 +00004676 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4677 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004678 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4679 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004680 case Instruction::SRem:
4681 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4682 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4683 BO->hasOneUse()) {
4684 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4685 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004686 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4687 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004688 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004689 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004690 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004691 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004692 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004693 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004694 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4695 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004696 if (BO->hasOneUse())
4697 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4698 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004699 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004700 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4701 // efficiently invertible, or if the add has just this one use.
4702 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004703
Chris Lattnerc992add2003-08-13 05:33:12 +00004704 if (Value *NegVal = dyn_castNegVal(BOp1))
4705 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4706 else if (Value *NegVal = dyn_castNegVal(BOp0))
4707 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004708 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004709 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4710 BO->setName("");
4711 InsertNewInstBefore(Neg, I);
4712 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4713 }
4714 }
4715 break;
4716 case Instruction::Xor:
4717 // For the xor case, we can xor two constants together, eliminating
4718 // the explicit xor.
4719 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4720 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004721 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004722
4723 // FALLTHROUGH
4724 case Instruction::Sub:
4725 // Replace (([sub|xor] A, B) != 0) with (A != B)
4726 if (CI->isNullValue())
4727 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4728 BO->getOperand(1));
4729 break;
4730
4731 case Instruction::Or:
4732 // If bits are being or'd in that are not present in the constant we
4733 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004734 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004735 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004736 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004737 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004738 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004739 break;
4740
4741 case Instruction::And:
4742 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004743 // If bits are being compared against that are and'd out, then the
4744 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004745 if (!ConstantExpr::getAnd(CI,
4746 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004747 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004748
Chris Lattner35167c32004-06-09 07:59:58 +00004749 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004750 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004751 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4752 Instruction::SetNE, Op0,
4753 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004754
Chris Lattnerc992add2003-08-13 05:33:12 +00004755 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4756 // to be a signed value as appropriate.
4757 if (isSignBit(BOC)) {
4758 Value *X = BO->getOperand(0);
4759 // If 'X' is not signed, insert a cast now...
4760 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004761 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004762 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004763 }
4764 return new SetCondInst(isSetNE ? Instruction::SetLT :
4765 Instruction::SetGE, X,
4766 Constant::getNullValue(X->getType()));
4767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004768
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004769 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004770 if (CI->isNullValue() && isHighOnes(BOC)) {
4771 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004772 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004773
4774 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004775 if (NegX->getType()->isSigned()) {
4776 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4777 X = InsertCastBefore(X, DestTy, I);
4778 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004779 }
4780
4781 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004782 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004783 }
4784
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004785 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004786 default: break;
4787 }
4788 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004789 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004790 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004791 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4792 Value *CastOp = Cast->getOperand(0);
4793 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004794 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004795 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004796 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004798 "Source and destination signednesses should differ!");
4799 if (Cast->getType()->isSigned()) {
4800 // If this is a signed comparison, check for comparisons in the
4801 // vicinity of zero.
4802 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4803 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004804 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004805 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004806 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004807 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004808 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004809 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004810 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004811 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004812 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004813 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004814 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004815 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004816 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004817 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004818 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004819 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004820 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004821 return BinaryOperator::createSetLT(CastOp,
4822 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004823 }
4824 }
4825 }
Chris Lattnere967b342003-06-04 05:10:11 +00004826 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004827 }
4828
Chris Lattner77c32c32005-04-23 15:31:55 +00004829 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4830 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4831 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4832 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004833 case Instruction::GetElementPtr:
4834 if (RHSC->isNullValue()) {
4835 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4836 bool isAllZeros = true;
4837 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4838 if (!isa<Constant>(LHSI->getOperand(i)) ||
4839 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4840 isAllZeros = false;
4841 break;
4842 }
4843 if (isAllZeros)
4844 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4845 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4846 }
4847 break;
4848
Chris Lattner77c32c32005-04-23 15:31:55 +00004849 case Instruction::PHI:
4850 if (Instruction *NV = FoldOpIntoPhi(I))
4851 return NV;
4852 break;
4853 case Instruction::Select:
4854 // If either operand of the select is a constant, we can fold the
4855 // comparison into the select arms, which will cause one to be
4856 // constant folded and the select turned into a bitwise or.
4857 Value *Op1 = 0, *Op2 = 0;
4858 if (LHSI->hasOneUse()) {
4859 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4860 // Fold the known value into the constant operand.
4861 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4862 // Insert a new SetCC of the other select operand.
4863 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4864 LHSI->getOperand(2), RHSC,
4865 I.getName()), I);
4866 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4867 // Fold the known value into the constant operand.
4868 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4869 // Insert a new SetCC of the other select operand.
4870 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4871 LHSI->getOperand(1), RHSC,
4872 I.getName()), I);
4873 }
4874 }
Jeff Cohen82639852005-04-23 21:38:35 +00004875
Chris Lattner77c32c32005-04-23 15:31:55 +00004876 if (Op1)
4877 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4878 break;
4879 }
4880 }
4881
Chris Lattner0798af32005-01-13 20:14:25 +00004882 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4883 if (User *GEP = dyn_castGetElementPtr(Op0))
4884 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4885 return NI;
4886 if (User *GEP = dyn_castGetElementPtr(Op1))
4887 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4888 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4889 return NI;
4890
Chris Lattner16930792003-11-03 04:25:02 +00004891 // Test to see if the operands of the setcc are casted versions of other
4892 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004893 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4894 Value *CastOp0 = CI->getOperand(0);
4895 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004896 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004897 // We keep moving the cast from the left operand over to the right
4898 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004899 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004900
Chris Lattner16930792003-11-03 04:25:02 +00004901 // If operand #1 is a cast instruction, see if we can eliminate it as
4902 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004903 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4904 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004905 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004906 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004907
Chris Lattner16930792003-11-03 04:25:02 +00004908 // If Op1 is a constant, we can fold the cast into the constant.
4909 if (Op1->getType() != Op0->getType())
4910 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4911 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4912 } else {
4913 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004914 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004915 }
4916 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4917 }
4918
Chris Lattner6444c372003-11-03 05:17:03 +00004919 // Handle the special case of: setcc (cast bool to X), <cst>
4920 // This comes up when you have code like
4921 // int X = A < B;
4922 // if (X) ...
4923 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004924 // with a constant or another cast from the same type.
4925 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4926 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4927 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004928 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004929
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004930 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004931 Value *A, *B;
4932 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4933 (A == Op1 || B == Op1)) {
4934 // (A^B) == A -> B == 0
4935 Value *OtherVal = A == Op1 ? B : A;
4936 return BinaryOperator::create(I.getOpcode(), OtherVal,
4937 Constant::getNullValue(A->getType()));
4938 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4939 (A == Op0 || B == Op0)) {
4940 // A == (A^B) -> B == 0
4941 Value *OtherVal = A == Op0 ? B : A;
4942 return BinaryOperator::create(I.getOpcode(), OtherVal,
4943 Constant::getNullValue(A->getType()));
4944 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4945 // (A-B) == A -> B == 0
4946 return BinaryOperator::create(I.getOpcode(), B,
4947 Constant::getNullValue(B->getType()));
4948 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4949 // A == (A-B) -> B == 0
4950 return BinaryOperator::create(I.getOpcode(), B,
4951 Constant::getNullValue(B->getType()));
4952 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004953
4954 Value *C, *D;
4955 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4956 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4957 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4958 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4959 Value *X = 0, *Y = 0, *Z = 0;
4960
4961 if (A == C) {
4962 X = B; Y = D; Z = A;
4963 } else if (A == D) {
4964 X = B; Y = C; Z = A;
4965 } else if (B == C) {
4966 X = A; Y = D; Z = B;
4967 } else if (B == D) {
4968 X = A; Y = C; Z = B;
4969 }
4970
4971 if (X) { // Build (X^Y) & Z
4972 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4973 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4974 I.setOperand(0, Op1);
4975 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4976 return &I;
4977 }
4978 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004979 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004980 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004981}
4982
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004983// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4984// We only handle extending casts so far.
4985//
4986Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4987 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4988 const Type *SrcTy = LHSCIOp->getType();
4989 const Type *DestTy = SCI.getOperand(0)->getType();
4990 Value *RHSCIOp;
4991
4992 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004993 return 0;
4994
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004995 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4996 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4997 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4998
4999 // Is this a sign or zero extension?
5000 bool isSignSrc = SrcTy->isSigned();
5001 bool isSignDest = DestTy->isSigned();
5002
5003 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5004 // Not an extension from the same type?
5005 RHSCIOp = CI->getOperand(0);
5006 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5007 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5008 // Compute the constant that would happen if we truncated to SrcTy then
5009 // reextended to DestTy.
5010 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
5011
5012 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005013 // Make sure that src sign and dest sign match. For example,
5014 //
5015 // %A = cast short %X to uint
5016 // %B = setgt uint %A, 1330
5017 //
Devang Patel88afd002006-10-19 19:21:36 +00005018 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005019 //
5020 // %B = setgt short %X, 1330
5021 //
5022 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005023 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5024 // OR operation is EQ/NE.
5025 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00005026 RHSCIOp = Res;
5027 else
5028 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005029 } else {
5030 // If the value cannot be represented in the shorter type, we cannot emit
5031 // a simple comparison.
5032 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005033 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005034 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005035 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005036
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005037 // Evaluate the comparison for LT.
5038 Value *Result;
5039 if (DestTy->isSigned()) {
5040 // We're performing a signed comparison.
5041 if (isSignSrc) {
5042 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005043 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005044 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005045 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005046 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005047 } else {
5048 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005049 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005050 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005051 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005052 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005053 }
5054 } else {
5055 // We're performing an unsigned comparison.
5056 if (!isSignSrc) {
5057 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005058 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005059 } else {
5060 // We're performing an unsigned comp with a sign extended value.
5061 // This is true if the input is >= 0. [aka >s -1]
5062 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5063 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5064 NegOne, SCI.getName()), SCI);
5065 }
Reid Spencer279fa252004-11-28 21:31:15 +00005066 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005067
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005068 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005069 if (SCI.getOpcode() == Instruction::SetLT) {
5070 return ReplaceInstUsesWith(SCI, Result);
5071 } else {
5072 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5073 if (Constant *CI = dyn_cast<Constant>(Result))
5074 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5075 else
5076 return BinaryOperator::createNot(Result);
5077 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005078 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005079 } else {
5080 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005081 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005082
Chris Lattner252a8452005-06-16 03:00:08 +00005083 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005084 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5085}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005086
Chris Lattnere8d6c602003-03-10 19:16:08 +00005087Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005088 assert(I.getOperand(1)->getType() == Type::UByteTy);
5089 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005090 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005091
5092 // shl X, 0 == X and shr X, 0 == X
5093 // shl 0, X == 0 and shr 0, X == 0
5094 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005095 Op0 == Constant::getNullValue(Op0->getType()))
5096 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005097
Chris Lattner81a7a232004-10-16 18:11:37 +00005098 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5099 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005100 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005101 else // undef << X -> 0 AND undef >>u X -> 0
5102 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5103 }
5104 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005105 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5107 else
5108 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5109 }
5110
Chris Lattnerd4dee402006-11-10 23:38:52 +00005111 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5112 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005113 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005114 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005115 return ReplaceInstUsesWith(I, CSI);
5116
Chris Lattner183b3362004-04-09 19:05:30 +00005117 // Try to fold constant and into select arguments.
5118 if (isa<Constant>(Op0))
5119 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005120 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005121 return R;
5122
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005123 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005124 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005125 if (MaskedValueIsZero(Op0,
5126 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005127 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005128 }
5129 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005130
Reid Spencere0fc4df2006-10-20 07:07:24 +00005131 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5132 if (CUI->getType()->isUnsigned())
5133 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5134 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005135 return 0;
5136}
5137
Reid Spencere0fc4df2006-10-20 07:07:24 +00005138Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005139 ShiftInst &I) {
5140 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005141 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5142 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005143 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005144
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005145 // See if we can simplify any instructions used by the instruction whose sole
5146 // purpose is to compute bits we don't care about.
5147 uint64_t KnownZero, KnownOne;
5148 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5149 KnownZero, KnownOne))
5150 return &I;
5151
Chris Lattner14553932006-01-06 07:12:35 +00005152 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5153 // of a signed value.
5154 //
5155 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005156 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005157 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005158 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5159 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005160 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005161 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005162 }
Chris Lattner14553932006-01-06 07:12:35 +00005163 }
5164
5165 // ((X*C1) << C2) == (X * (C1 << C2))
5166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5167 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5168 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5169 return BinaryOperator::createMul(BO->getOperand(0),
5170 ConstantExpr::getShl(BOOp, Op1));
5171
5172 // Try to fold constant and into select arguments.
5173 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5174 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5175 return R;
5176 if (isa<PHINode>(Op0))
5177 if (Instruction *NV = FoldOpIntoPhi(I))
5178 return NV;
5179
5180 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005181 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5182 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5183 Value *V1, *V2;
5184 ConstantInt *CC;
5185 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005186 default: break;
5187 case Instruction::Add:
5188 case Instruction::And:
5189 case Instruction::Or:
5190 case Instruction::Xor:
5191 // These operators commute.
5192 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005193 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5194 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005195 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005196 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005197 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005198 Op0BO->getName());
5199 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005200 Instruction *X =
5201 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5202 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005203 InsertNewInstBefore(X, I); // (X + (Y << C))
5204 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005205 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005206 return BinaryOperator::createAnd(X, C2);
5207 }
Chris Lattner14553932006-01-06 07:12:35 +00005208
Chris Lattner797dee72005-09-18 06:30:59 +00005209 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5210 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5211 match(Op0BO->getOperand(1),
5212 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005213 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005214 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005215 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005216 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005217 Op0BO->getName());
5218 InsertNewInstBefore(YS, I); // (Y << C)
5219 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005220 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005221 V1->getName()+".mask");
5222 InsertNewInstBefore(XM, I); // X & (CC << C)
5223
5224 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5225 }
Chris Lattner14553932006-01-06 07:12:35 +00005226
Chris Lattner797dee72005-09-18 06:30:59 +00005227 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005228 case Instruction::Sub:
5229 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005230 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5231 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005232 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005233 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005234 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005235 Op0BO->getName());
5236 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005237 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005238 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005239 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005240 InsertNewInstBefore(X, I); // (X + (Y << C))
5241 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005242 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005243 return BinaryOperator::createAnd(X, C2);
5244 }
Chris Lattner14553932006-01-06 07:12:35 +00005245
Chris Lattner1df0e982006-05-31 21:14:00 +00005246 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005247 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5248 match(Op0BO->getOperand(0),
5249 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005250 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005251 cast<BinaryOperator>(Op0BO->getOperand(0))
5252 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005253 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005254 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005255 Op0BO->getName());
5256 InsertNewInstBefore(YS, I); // (Y << C)
5257 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005258 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005259 V1->getName()+".mask");
5260 InsertNewInstBefore(XM, I); // X & (CC << C)
5261
Chris Lattner1df0e982006-05-31 21:14:00 +00005262 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005263 }
Chris Lattner14553932006-01-06 07:12:35 +00005264
Chris Lattner27cb9db2005-09-18 05:12:10 +00005265 break;
Chris Lattner14553932006-01-06 07:12:35 +00005266 }
5267
5268
5269 // If the operand is an bitwise operator with a constant RHS, and the
5270 // shift is the only use, we can pull it out of the shift.
5271 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5272 bool isValid = true; // Valid only for And, Or, Xor
5273 bool highBitSet = false; // Transform if high bit of constant set?
5274
5275 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005276 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005277 case Instruction::Add:
5278 isValid = isLeftShift;
5279 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005280 case Instruction::Or:
5281 case Instruction::Xor:
5282 highBitSet = false;
5283 break;
5284 case Instruction::And:
5285 highBitSet = true;
5286 break;
Chris Lattner14553932006-01-06 07:12:35 +00005287 }
5288
5289 // If this is a signed shift right, and the high bit is modified
5290 // by the logical operation, do not perform the transformation.
5291 // The highBitSet boolean indicates the value of the high bit of
5292 // the constant which would cause it to be modified for this
5293 // operation.
5294 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005295 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005296 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005297 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5298 }
5299
5300 if (isValid) {
5301 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5302
5303 Instruction *NewShift =
5304 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5305 Op0BO->getName());
5306 Op0BO->setName("");
5307 InsertNewInstBefore(NewShift, I);
5308
5309 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5310 NewRHS);
5311 }
5312 }
5313 }
5314 }
5315
Chris Lattnereb372a02006-01-06 07:52:12 +00005316 // Find out if this is a shift of a shift by a constant.
5317 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005318 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005319 ShiftOp = Op0SI;
5320 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5321 // If this is a noop-integer case of a shift instruction, use the shift.
5322 if (CI->getOperand(0)->getType()->isInteger() &&
5323 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5324 CI->getType()->getPrimitiveSizeInBits() &&
5325 isa<ShiftInst>(CI->getOperand(0))) {
5326 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5327 }
5328 }
5329
Reid Spencere0fc4df2006-10-20 07:07:24 +00005330 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005331 // Find the operands and properties of the input shift. Note that the
5332 // signedness of the input shift may differ from the current shift if there
5333 // is a noop cast between the two.
5334 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005335 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5336 ShiftOp->getType()->isSigned() :
5337 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005338 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005339
Reid Spencere0fc4df2006-10-20 07:07:24 +00005340 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005341
Reid Spencere0fc4df2006-10-20 07:07:24 +00005342 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5343 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005344
5345 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5346 if (isLeftShift == isShiftOfLeftShift) {
5347 // Do not fold these shifts if the first one is signed and the second one
5348 // is unsigned and this is a right shift. Further, don't do any folding
5349 // on them.
5350 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5351 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005352
Chris Lattnereb372a02006-01-06 07:52:12 +00005353 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5354 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5355 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005356
Chris Lattnereb372a02006-01-06 07:52:12 +00005357 Value *Op = ShiftOp->getOperand(0);
5358 if (isShiftOfSignedShift != isSignedShift)
5359 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
Reid Spencerfdff9382006-11-08 06:47:33 +00005360 ShiftInst* ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005361 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005362 if (I.getType() == ShiftResult->getType())
5363 return ShiftResult;
5364 InsertNewInstBefore(ShiftResult, I);
5365 return new CastInst(ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005366 }
5367
5368 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5369 // signed types, we can only support the (A >> c1) << c2 configuration,
5370 // because it can not turn an arbitrary bit of A into a sign bit.
5371 if (isUnsignedShift || isLeftShift) {
5372 // Calculate bitmask for what gets shifted off the edge.
5373 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5374 if (isLeftShift)
5375 C = ConstantExpr::getShl(C, ShiftAmt1C);
5376 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005377 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005378
5379 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005380 if (Op->getType() != C->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00005381 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005382
5383 Instruction *Mask =
5384 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5385 InsertNewInstBefore(Mask, I);
5386
5387 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005388 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005389 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005390 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005391 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005392 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005393 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5394 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005395 return new ShiftInst(Instruction::LShr, Mask,
5396 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005397 } else {
5398 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005399 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005400 }
5401 } else {
5402 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005403 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005404 Instruction *Shift =
5405 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005406 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005407 InsertNewInstBefore(Shift, I);
5408
5409 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5410 C = ConstantExpr::getShl(C, Op1);
5411 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5412 InsertNewInstBefore(Mask, I);
5413 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005414 }
5415 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005416 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005417 // this case, C1 == C2 and C1 is 8, 16, or 32.
5418 if (ShiftAmt1 == ShiftAmt2) {
5419 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005420 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005421 case 8 : SExtType = Type::SByteTy; break;
5422 case 16: SExtType = Type::ShortTy; break;
5423 case 32: SExtType = Type::IntTy; break;
5424 }
5425
5426 if (SExtType) {
5427 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5428 SExtType, "sext");
5429 InsertNewInstBefore(NewTrunc, I);
5430 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005431 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005432 }
Chris Lattner86102b82005-01-01 16:22:27 +00005433 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005434 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005435 return 0;
5436}
5437
Chris Lattner48a44f72002-05-02 17:06:02 +00005438
Chris Lattner8f663e82005-10-29 04:36:15 +00005439/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5440/// expression. If so, decompose it, returning some value X, such that Val is
5441/// X*Scale+Offset.
5442///
5443static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5444 unsigned &Offset) {
5445 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005446 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5447 if (CI->getType()->isUnsigned()) {
5448 Offset = CI->getZExtValue();
5449 Scale = 1;
5450 return ConstantInt::get(Type::UIntTy, 0);
5451 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005452 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5453 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005454 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5455 if (CUI->getType()->isUnsigned()) {
5456 if (I->getOpcode() == Instruction::Shl) {
5457 // This is a value scaled by '1 << the shift amt'.
5458 Scale = 1U << CUI->getZExtValue();
5459 Offset = 0;
5460 return I->getOperand(0);
5461 } else if (I->getOpcode() == Instruction::Mul) {
5462 // This value is scaled by 'CUI'.
5463 Scale = CUI->getZExtValue();
5464 Offset = 0;
5465 return I->getOperand(0);
5466 } else if (I->getOpcode() == Instruction::Add) {
5467 // We have X+C. Check to see if we really have (X*C2)+C1,
5468 // where C1 is divisible by C2.
5469 unsigned SubScale;
5470 Value *SubVal =
5471 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5472 Offset += CUI->getZExtValue();
5473 if (SubScale > 1 && (Offset % SubScale == 0)) {
5474 Scale = SubScale;
5475 return SubVal;
5476 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005477 }
5478 }
5479 }
5480 }
5481 }
5482
5483 // Otherwise, we can't look past this.
5484 Scale = 1;
5485 Offset = 0;
5486 return Val;
5487}
5488
5489
Chris Lattner216be912005-10-24 06:03:58 +00005490/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5491/// try to eliminate the cast by moving the type information into the alloc.
5492Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5493 AllocationInst &AI) {
5494 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005495 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005496
Chris Lattnerac87beb2005-10-24 06:22:12 +00005497 // Remove any uses of AI that are dead.
5498 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5499 std::vector<Instruction*> DeadUsers;
5500 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5501 Instruction *User = cast<Instruction>(*UI++);
5502 if (isInstructionTriviallyDead(User)) {
5503 while (UI != E && *UI == User)
5504 ++UI; // If this instruction uses AI more than once, don't break UI.
5505
5506 // Add operands to the worklist.
5507 AddUsesToWorkList(*User);
5508 ++NumDeadInst;
5509 DEBUG(std::cerr << "IC: DCE: " << *User);
5510
5511 User->eraseFromParent();
5512 removeFromWorkList(User);
5513 }
5514 }
5515
Chris Lattner216be912005-10-24 06:03:58 +00005516 // Get the type really allocated and the type casted to.
5517 const Type *AllocElTy = AI.getAllocatedType();
5518 const Type *CastElTy = PTy->getElementType();
5519 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005520
Chris Lattner7d190672006-10-01 19:40:58 +00005521 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5522 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005523 if (CastElTyAlign < AllocElTyAlign) return 0;
5524
Chris Lattner46705b22005-10-24 06:35:18 +00005525 // If the allocation has multiple uses, only promote it if we are strictly
5526 // increasing the alignment of the resultant allocation. If we keep it the
5527 // same, we open the door to infinite loops of various kinds.
5528 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5529
Chris Lattner216be912005-10-24 06:03:58 +00005530 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5531 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005532 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005533
Chris Lattner8270c332005-10-29 03:19:53 +00005534 // See if we can satisfy the modulus by pulling a scale out of the array
5535 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005536 unsigned ArraySizeScale, ArrayOffset;
5537 Value *NumElements = // See if the array size is a decomposable linear expr.
5538 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5539
Chris Lattner8270c332005-10-29 03:19:53 +00005540 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5541 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005542 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5543 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005544
Chris Lattner8270c332005-10-29 03:19:53 +00005545 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5546 Value *Amt = 0;
5547 if (Scale == 1) {
5548 Amt = NumElements;
5549 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005550 // If the allocation size is constant, form a constant mul expression
5551 Amt = ConstantInt::get(Type::UIntTy, Scale);
5552 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5553 Amt = ConstantExpr::getMul(
5554 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5555 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005556 else if (Scale != 1) {
5557 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5558 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005559 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005560 }
5561
Chris Lattner8f663e82005-10-29 04:36:15 +00005562 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005563 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005564 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5565 Amt = InsertNewInstBefore(Tmp, AI);
5566 }
5567
Chris Lattner216be912005-10-24 06:03:58 +00005568 std::string Name = AI.getName(); AI.setName("");
5569 AllocationInst *New;
5570 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005571 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005572 else
Nate Begeman848622f2005-11-05 09:21:28 +00005573 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005574 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005575
5576 // If the allocation has multiple uses, insert a cast and change all things
5577 // that used it to use the new cast. This will also hack on CI, but it will
5578 // die soon.
5579 if (!AI.hasOneUse()) {
5580 AddUsesToWorkList(AI);
5581 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5582 InsertNewInstBefore(NewCast, AI);
5583 AI.replaceAllUsesWith(NewCast);
5584 }
Chris Lattner216be912005-10-24 06:03:58 +00005585 return ReplaceInstUsesWith(CI, New);
5586}
5587
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005588/// CanEvaluateInDifferentType - Return true if we can take the specified value
5589/// and return it without inserting any new casts. This is used by code that
5590/// tries to decide whether promoting or shrinking integer operations to wider
5591/// or smaller types will allow us to eliminate a truncate or extend.
5592static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5593 int &NumCastsRemoved) {
5594 if (isa<Constant>(V)) return true;
5595
5596 Instruction *I = dyn_cast<Instruction>(V);
5597 if (!I || !I->hasOneUse()) return false;
5598
5599 switch (I->getOpcode()) {
5600 case Instruction::And:
5601 case Instruction::Or:
5602 case Instruction::Xor:
5603 // These operators can all arbitrarily be extended or truncated.
5604 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5605 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5606 case Instruction::Cast:
5607 // If this is a cast from the destination type, we can trivially eliminate
5608 // it, and this will remove a cast overall.
5609 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005610 // If the first operand is itself a cast, and is eliminable, do not count
5611 // this as an eliminable cast. We would prefer to eliminate those two
5612 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005613 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005614 return true;
5615
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005616 ++NumCastsRemoved;
5617 return true;
5618 }
5619 // TODO: Can handle more cases here.
5620 break;
5621 }
5622
5623 return false;
5624}
5625
5626/// EvaluateInDifferentType - Given an expression that
5627/// CanEvaluateInDifferentType returns true for, actually insert the code to
5628/// evaluate the expression.
5629Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5630 if (Constant *C = dyn_cast<Constant>(V))
5631 return ConstantExpr::getCast(C, Ty);
5632
5633 // Otherwise, it must be an instruction.
5634 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005635 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005636 switch (I->getOpcode()) {
5637 case Instruction::And:
5638 case Instruction::Or:
5639 case Instruction::Xor: {
5640 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5641 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5642 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5643 LHS, RHS, I->getName());
5644 break;
5645 }
5646 case Instruction::Cast:
5647 // If this is a cast from the destination type, return the input.
5648 if (I->getOperand(0)->getType() == Ty)
5649 return I->getOperand(0);
5650
5651 // TODO: Can handle more cases here.
5652 assert(0 && "Unreachable!");
5653 break;
5654 }
5655
5656 return InsertNewInstBefore(Res, *I);
5657}
5658
Chris Lattner216be912005-10-24 06:03:58 +00005659
Chris Lattner48a44f72002-05-02 17:06:02 +00005660// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005661//
Chris Lattner113f4f42002-06-25 16:13:24 +00005662Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005663 Value *Src = CI.getOperand(0);
5664
Chris Lattner48a44f72002-05-02 17:06:02 +00005665 // If the user is casting a value to the same type, eliminate this cast
5666 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005667 if (CI.getType() == Src->getType())
5668 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005669
Chris Lattner81a7a232004-10-16 18:11:37 +00005670 if (isa<UndefValue>(Src)) // cast undef -> undef
5671 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5672
Chris Lattner48a44f72002-05-02 17:06:02 +00005673 // If casting the result of another cast instruction, try to eliminate this
5674 // one!
5675 //
Chris Lattner86102b82005-01-01 16:22:27 +00005676 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5677 Value *A = CSrc->getOperand(0);
5678 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5679 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005680 // This instruction now refers directly to the cast's src operand. This
5681 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005682 CI.setOperand(0, CSrc->getOperand(0));
5683 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005684 }
5685
Chris Lattner650b6da2002-08-02 20:00:25 +00005686 // If this is an A->B->A cast, and we are dealing with integral types, try
5687 // to convert this into a logical 'and' instruction.
5688 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005689 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005690 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005691 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005692 CSrc->getType()->getPrimitiveSizeInBits() <
5693 CI.getType()->getPrimitiveSizeInBits()&&
5694 A->getType()->getPrimitiveSizeInBits() ==
5695 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005696 assert(CSrc->getType() != Type::ULongTy &&
5697 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005698 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005699 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005700 AndValue);
5701 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5702 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5703 if (And->getType() != CI.getType()) {
5704 And->setName(CSrc->getName()+".mask");
5705 InsertNewInstBefore(And, CI);
5706 And = new CastInst(And, CI.getType());
5707 }
5708 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005709 }
5710 }
Chris Lattner2590e512006-02-07 06:56:34 +00005711
Chris Lattner03841652004-05-25 04:29:21 +00005712 // If this is a cast to bool, turn it into the appropriate setne instruction.
5713 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005714 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005715 Constant::getNullValue(CI.getOperand(0)->getType()));
5716
Chris Lattner2590e512006-02-07 06:56:34 +00005717 // See if we can simplify any instructions used by the LHS whose sole
5718 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005719 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5720 uint64_t KnownZero, KnownOne;
5721 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5722 KnownZero, KnownOne))
5723 return &CI;
5724 }
Chris Lattner2590e512006-02-07 06:56:34 +00005725
Chris Lattnerd0d51602003-06-21 23:12:02 +00005726 // If casting the result of a getelementptr instruction with no offset, turn
5727 // this into a cast of the original pointer!
5728 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005730 bool AllZeroOperands = true;
5731 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5732 if (!isa<Constant>(GEP->getOperand(i)) ||
5733 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5734 AllZeroOperands = false;
5735 break;
5736 }
5737 if (AllZeroOperands) {
5738 CI.setOperand(0, GEP->getOperand(0));
5739 return &CI;
5740 }
5741 }
5742
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005743 // If we are casting a malloc or alloca to a pointer to a type of the same
5744 // size, rewrite the allocation instruction to allocate the "right" type.
5745 //
5746 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005747 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5748 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005749
Chris Lattner86102b82005-01-01 16:22:27 +00005750 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5751 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5752 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005753 if (isa<PHINode>(Src))
5754 if (Instruction *NV = FoldOpIntoPhi(CI))
5755 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005756
5757 // If the source and destination are pointers, and this cast is equivalent to
5758 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5759 // This can enhance SROA and other transforms that want type-safe pointers.
5760 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5761 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5762 const Type *DstTy = DstPTy->getElementType();
5763 const Type *SrcTy = SrcPTy->getElementType();
5764
5765 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5766 unsigned NumZeros = 0;
5767 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005768 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5769 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005770 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5771 ++NumZeros;
5772 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005773
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005774 // If we found a path from the src to dest, create the getelementptr now.
5775 if (SrcTy == DstTy) {
5776 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5777 return new GetElementPtrInst(Src, Idxs);
5778 }
5779 }
5780
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005781 // If the source value is an instruction with only this use, we can attempt to
5782 // propagate the cast into the instruction. Also, only handle integral types
5783 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005784 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005785 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005786 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005787
5788 int NumCastsRemoved = 0;
5789 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5790 // If this cast is a truncate, evaluting in a different type always
5791 // eliminates the cast, so it is always a win. If this is a noop-cast
5792 // this just removes a noop cast which isn't pointful, but simplifies
5793 // the code. If this is a zero-extension, we need to do an AND to
5794 // maintain the clear top-part of the computation, so we require that
5795 // the input have eliminated at least one cast. If this is a sign
5796 // extension, we insert two new casts (to do the extension) so we
5797 // require that two casts have been eliminated.
5798 bool DoXForm;
5799 switch (getCastType(Src->getType(), CI.getType())) {
5800 default: assert(0 && "Unknown cast type!");
5801 case Noop:
5802 case Truncate:
5803 DoXForm = true;
5804 break;
5805 case Zeroext:
5806 DoXForm = NumCastsRemoved >= 1;
5807 break;
5808 case Signext:
5809 DoXForm = NumCastsRemoved >= 2;
5810 break;
5811 }
5812
5813 if (DoXForm) {
5814 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5815 assert(Res->getType() == CI.getType());
5816 switch (getCastType(Src->getType(), CI.getType())) {
5817 default: assert(0 && "Unknown cast type!");
5818 case Noop:
5819 case Truncate:
5820 // Just replace this cast with the result.
5821 return ReplaceInstUsesWith(CI, Res);
5822 case Zeroext: {
5823 // We need to emit an AND to clear the high bits.
5824 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5825 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5826 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005827 Constant *C =
5828 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005829 C = ConstantExpr::getCast(C, CI.getType());
5830 return BinaryOperator::createAnd(Res, C);
5831 }
5832 case Signext:
5833 // We need to emit a cast to truncate, then a cast to sext.
5834 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5835 CI.getType());
5836 }
5837 }
5838 }
5839
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005840 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005841 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5842 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005843
5844 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5845 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5846
5847 switch (SrcI->getOpcode()) {
5848 case Instruction::Add:
5849 case Instruction::Mul:
5850 case Instruction::And:
5851 case Instruction::Or:
5852 case Instruction::Xor:
5853 // If we are discarding information, or just changing the sign, rewrite.
5854 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5855 // Don't insert two casts if they cannot be eliminated. We allow two
5856 // casts to be inserted if the sizes are the same. This could only be
5857 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005858 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5859 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005860 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5861 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5862 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5863 ->getOpcode(), Op0c, Op1c);
5864 }
5865 }
Chris Lattner72086162005-05-06 02:07:39 +00005866
5867 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5868 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005869 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005870 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5871 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5872 return BinaryOperator::createXor(New,
5873 ConstantInt::get(CI.getType(), 1));
5874 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005875 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005876 case Instruction::SDiv:
5877 case Instruction::UDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +00005878 case Instruction::SRem:
5879 case Instruction::URem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005880 // If we are just changing the sign, rewrite.
5881 if (DestBitSize == SrcBitSize) {
5882 // Don't insert two casts if they cannot be eliminated. We allow two
5883 // casts to be inserted if the sizes are the same. This could only be
5884 // converting signedness, which is a noop.
5885 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5886 !ValueRequiresCast(Op0, DestTy, TD)) {
5887 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5888 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5889 return BinaryOperator::create(
5890 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5891 }
5892 }
5893 break;
5894
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005895 case Instruction::Shl:
5896 // Allow changing the sign of the source operand. Do not allow changing
5897 // the size of the shift, UNLESS the shift amount is a constant. We
Reid Spencerfdff9382006-11-08 06:47:33 +00005898 // must not change variable sized shifts to a smaller size, because it
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005899 // is undefined to shift more bits out than exist in the value.
5900 if (DestBitSize == SrcBitSize ||
5901 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5902 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5903 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5904 }
5905 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00005906 case Instruction::AShr:
Chris Lattner87380412005-05-06 04:18:52 +00005907 // If this is a signed shr, and if all bits shifted in are about to be
5908 // truncated off, turn it into an unsigned shr to allow greater
5909 // simplifications.
Reid Spencerfdff9382006-11-08 06:47:33 +00005910 if (DestBitSize < SrcBitSize &&
Chris Lattner87380412005-05-06 04:18:52 +00005911 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005912 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005913 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005914 // Insert the new logical shift right.
5915 return new ShiftInst(Instruction::LShr, Op0, Op1);
Chris Lattner87380412005-05-06 04:18:52 +00005916 }
5917 }
5918 break;
5919
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005920 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005921 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005922 // We if we are just checking for a seteq of a single bit and casting it
5923 // to an integer. If so, shift the bit to the appropriate place then
5924 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005925 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005926 uint64_t Op1CV = Op1C->getZExtValue();
5927 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5928 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5929 // cast (X == 1) to int --> X iff X has only the low bit set.
5930 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5931 // cast (X != 0) to int --> X iff X has only the low bit set.
5932 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5933 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5934 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5935 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5936 // If Op1C some other power of two, convert:
5937 uint64_t KnownZero, KnownOne;
5938 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5939 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5940
5941 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5942 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5943 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5944 // (X&4) == 2 --> false
5945 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005946 Constant *Res = ConstantBool::get(isSetNE);
5947 Res = ConstantExpr::getCast(Res, CI.getType());
5948 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005949 }
5950
5951 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5952 Value *In = Op0;
5953 if (ShiftAmt) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005954 // Perform a logical shr by shiftamt.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005955 // Insert the shift to put the result in the low bit.
Reid Spencerfdff9382006-11-08 06:47:33 +00005956 In = InsertNewInstBefore(new ShiftInst(Instruction::LShr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005957 ConstantInt::get(Type::UByteTy, ShiftAmt),
5958 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005959 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005960
5961 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5962 Constant *One = ConstantInt::get(In->getType(), 1);
5963 In = BinaryOperator::createXor(In, One, "tmp");
5964 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005965 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005966
5967 if (CI.getType() == In->getType())
5968 return ReplaceInstUsesWith(CI, In);
5969 else
5970 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005971 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005972 }
5973 }
5974 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005975 }
5976 }
Chris Lattner99155be2006-05-25 23:24:33 +00005977
5978 if (SrcI->hasOneUse()) {
5979 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5980 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5981 // because the inputs are known to be a vector. Check to see if this is
5982 // a cast to a vector with the same # elts.
5983 if (isa<PackedType>(CI.getType()) &&
5984 cast<PackedType>(CI.getType())->getNumElements() ==
5985 SVI->getType()->getNumElements()) {
5986 CastInst *Tmp;
5987 // If either of the operands is a cast from CI.getType(), then
5988 // evaluating the shuffle in the casted destination's type will allow
5989 // us to eliminate at least one cast.
5990 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5991 Tmp->getOperand(0)->getType() == CI.getType()) ||
5992 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005993 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005994 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5995 CI.getType(), &CI);
5996 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5997 CI.getType(), &CI);
5998 // Return a new shuffle vector. Use the same element ID's, as we
5999 // know the vector types match #elts.
6000 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6001 }
6002 }
6003 }
6004 }
6005 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006006
Chris Lattner260ab202002-04-18 17:39:14 +00006007 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006008}
6009
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006010/// GetSelectFoldableOperands - We want to turn code that looks like this:
6011/// %C = or %A, %B
6012/// %D = select %cond, %C, %A
6013/// into:
6014/// %C = select %cond, %B, 0
6015/// %D = or %A, %C
6016///
6017/// Assuming that the specified instruction is an operand to the select, return
6018/// a bitmask indicating which operands of this instruction are foldable if they
6019/// equal the other incoming value of the select.
6020///
6021static unsigned GetSelectFoldableOperands(Instruction *I) {
6022 switch (I->getOpcode()) {
6023 case Instruction::Add:
6024 case Instruction::Mul:
6025 case Instruction::And:
6026 case Instruction::Or:
6027 case Instruction::Xor:
6028 return 3; // Can fold through either operand.
6029 case Instruction::Sub: // Can only fold on the amount subtracted.
6030 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006031 case Instruction::LShr:
6032 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006033 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006034 default:
6035 return 0; // Cannot fold
6036 }
6037}
6038
6039/// GetSelectFoldableConstant - For the same transformation as the previous
6040/// function, return the identity constant that goes into the select.
6041static Constant *GetSelectFoldableConstant(Instruction *I) {
6042 switch (I->getOpcode()) {
6043 default: assert(0 && "This cannot happen!"); abort();
6044 case Instruction::Add:
6045 case Instruction::Sub:
6046 case Instruction::Or:
6047 case Instruction::Xor:
6048 return Constant::getNullValue(I->getType());
6049 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006050 case Instruction::LShr:
6051 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006052 return Constant::getNullValue(Type::UByteTy);
6053 case Instruction::And:
6054 return ConstantInt::getAllOnesValue(I->getType());
6055 case Instruction::Mul:
6056 return ConstantInt::get(I->getType(), 1);
6057 }
6058}
6059
Chris Lattner411336f2005-01-19 21:50:18 +00006060/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6061/// have the same opcode and only one use each. Try to simplify this.
6062Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6063 Instruction *FI) {
6064 if (TI->getNumOperands() == 1) {
6065 // If this is a non-volatile load or a cast from the same type,
6066 // merge.
6067 if (TI->getOpcode() == Instruction::Cast) {
6068 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6069 return 0;
6070 } else {
6071 return 0; // unknown unary op.
6072 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006073
Chris Lattner411336f2005-01-19 21:50:18 +00006074 // Fold this by inserting a select from the input values.
6075 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6076 FI->getOperand(0), SI.getName()+".v");
6077 InsertNewInstBefore(NewSI, SI);
6078 return new CastInst(NewSI, TI->getType());
6079 }
6080
6081 // Only handle binary operators here.
6082 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6083 return 0;
6084
6085 // Figure out if the operations have any operands in common.
6086 Value *MatchOp, *OtherOpT, *OtherOpF;
6087 bool MatchIsOpZero;
6088 if (TI->getOperand(0) == FI->getOperand(0)) {
6089 MatchOp = TI->getOperand(0);
6090 OtherOpT = TI->getOperand(1);
6091 OtherOpF = FI->getOperand(1);
6092 MatchIsOpZero = true;
6093 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6094 MatchOp = TI->getOperand(1);
6095 OtherOpT = TI->getOperand(0);
6096 OtherOpF = FI->getOperand(0);
6097 MatchIsOpZero = false;
6098 } else if (!TI->isCommutative()) {
6099 return 0;
6100 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6101 MatchOp = TI->getOperand(0);
6102 OtherOpT = TI->getOperand(1);
6103 OtherOpF = FI->getOperand(0);
6104 MatchIsOpZero = true;
6105 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6106 MatchOp = TI->getOperand(1);
6107 OtherOpT = TI->getOperand(0);
6108 OtherOpF = FI->getOperand(1);
6109 MatchIsOpZero = true;
6110 } else {
6111 return 0;
6112 }
6113
6114 // If we reach here, they do have operations in common.
6115 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6116 OtherOpF, SI.getName()+".v");
6117 InsertNewInstBefore(NewSI, SI);
6118
6119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6120 if (MatchIsOpZero)
6121 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6122 else
6123 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6124 } else {
6125 if (MatchIsOpZero)
6126 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6127 else
6128 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6129 }
6130}
6131
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006132Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006133 Value *CondVal = SI.getCondition();
6134 Value *TrueVal = SI.getTrueValue();
6135 Value *FalseVal = SI.getFalseValue();
6136
6137 // select true, X, Y -> X
6138 // select false, X, Y -> Y
6139 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006140 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006141
6142 // select C, X, X -> X
6143 if (TrueVal == FalseVal)
6144 return ReplaceInstUsesWith(SI, TrueVal);
6145
Chris Lattner81a7a232004-10-16 18:11:37 +00006146 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6147 return ReplaceInstUsesWith(SI, FalseVal);
6148 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6149 return ReplaceInstUsesWith(SI, TrueVal);
6150 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6151 if (isa<Constant>(TrueVal))
6152 return ReplaceInstUsesWith(SI, TrueVal);
6153 else
6154 return ReplaceInstUsesWith(SI, FalseVal);
6155 }
6156
Chris Lattner1c631e82004-04-08 04:43:23 +00006157 if (SI.getType() == Type::BoolTy)
6158 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006159 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006160 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006161 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006162 } else {
6163 // Change: A = select B, false, C --> A = and !B, C
6164 Value *NotCond =
6165 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6166 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006167 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006168 }
6169 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006170 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006171 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006172 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006173 } else {
6174 // Change: A = select B, C, true --> A = or !B, C
6175 Value *NotCond =
6176 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6177 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006178 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006179 }
6180 }
6181
Chris Lattner183b3362004-04-09 19:05:30 +00006182 // Selecting between two integer constants?
6183 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6184 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6185 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006186 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006187 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006188 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006189 // select C, 0, 1 -> cast !C to int
6190 Value *NotCond =
6191 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006192 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006193 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006194 }
Chris Lattner35167c32004-06-09 07:59:58 +00006195
Chris Lattner380c7e92006-09-20 04:44:59 +00006196 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6197
6198 // (x <s 0) ? -1 : 0 -> sra x, 31
6199 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6200 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6201 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6202 bool CanXForm = false;
6203 if (CmpCst->getType()->isSigned())
6204 CanXForm = CmpCst->isNullValue() &&
6205 IC->getOpcode() == Instruction::SetLT;
6206 else {
6207 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006208 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006209 IC->getOpcode() == Instruction::SetGT;
6210 }
6211
6212 if (CanXForm) {
6213 // The comparison constant and the result are not neccessarily the
6214 // same width. In any case, the first step to do is make sure
6215 // that X is signed.
6216 Value *X = IC->getOperand(0);
6217 if (!X->getType()->isSigned())
6218 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6219
6220 // Now that X is signed, we have to make the all ones value. Do
6221 // this by inserting a new SRA.
6222 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006223 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006224 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006225 ShAmt, "ones");
6226 InsertNewInstBefore(SRA, SI);
6227
6228 // Finally, convert to the type of the select RHS. If this is
6229 // smaller than the compare value, it will truncate the ones to
6230 // fit. If it is larger, it will sext the ones to fit.
6231 return new CastInst(SRA, SI.getType());
6232 }
6233 }
6234
6235
6236 // If one of the constants is zero (we know they can't both be) and we
6237 // have a setcc instruction with zero, and we have an 'and' with the
6238 // non-constant value, eliminate this whole mess. This corresponds to
6239 // cases like this: ((X & 27) ? 27 : 0)
6240 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006241 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006242 cast<Constant>(IC->getOperand(1))->isNullValue())
6243 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6244 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006245 isa<ConstantInt>(ICA->getOperand(1)) &&
6246 (ICA->getOperand(1) == TrueValC ||
6247 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006248 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6249 // Okay, now we know that everything is set up, we just don't
6250 // know whether we have a setne or seteq and whether the true or
6251 // false val is the zero.
6252 bool ShouldNotVal = !TrueValC->isNullValue();
6253 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6254 Value *V = ICA;
6255 if (ShouldNotVal)
6256 V = InsertNewInstBefore(BinaryOperator::create(
6257 Instruction::Xor, V, ICA->getOperand(1)), SI);
6258 return ReplaceInstUsesWith(SI, V);
6259 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006260 }
Chris Lattner533bc492004-03-30 19:37:13 +00006261 }
Chris Lattner623fba12004-04-10 22:21:27 +00006262
6263 // See if we are selecting two values based on a comparison of the two values.
6264 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6265 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6266 // Transform (X == Y) ? X : Y -> Y
6267 if (SCI->getOpcode() == Instruction::SetEQ)
6268 return ReplaceInstUsesWith(SI, FalseVal);
6269 // Transform (X != Y) ? X : Y -> X
6270 if (SCI->getOpcode() == Instruction::SetNE)
6271 return ReplaceInstUsesWith(SI, TrueVal);
6272 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6273
6274 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6275 // Transform (X == Y) ? Y : X -> X
6276 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006277 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006278 // Transform (X != Y) ? Y : X -> Y
6279 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006280 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006281 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6282 }
6283 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006284
Chris Lattnera04c9042005-01-13 22:52:24 +00006285 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6286 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6287 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006288 Instruction *AddOp = 0, *SubOp = 0;
6289
Chris Lattner411336f2005-01-19 21:50:18 +00006290 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6291 if (TI->getOpcode() == FI->getOpcode())
6292 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6293 return IV;
6294
6295 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6296 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006297 if (TI->getOpcode() == Instruction::Sub &&
6298 FI->getOpcode() == Instruction::Add) {
6299 AddOp = FI; SubOp = TI;
6300 } else if (FI->getOpcode() == Instruction::Sub &&
6301 TI->getOpcode() == Instruction::Add) {
6302 AddOp = TI; SubOp = FI;
6303 }
6304
6305 if (AddOp) {
6306 Value *OtherAddOp = 0;
6307 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6308 OtherAddOp = AddOp->getOperand(1);
6309 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6310 OtherAddOp = AddOp->getOperand(0);
6311 }
6312
6313 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006314 // So at this point we know we have (Y -> OtherAddOp):
6315 // select C, (add X, Y), (sub X, Z)
6316 Value *NegVal; // Compute -Z
6317 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6318 NegVal = ConstantExpr::getNeg(C);
6319 } else {
6320 NegVal = InsertNewInstBefore(
6321 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006322 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006323
6324 Value *NewTrueOp = OtherAddOp;
6325 Value *NewFalseOp = NegVal;
6326 if (AddOp != TI)
6327 std::swap(NewTrueOp, NewFalseOp);
6328 Instruction *NewSel =
6329 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6330
6331 NewSel = InsertNewInstBefore(NewSel, SI);
6332 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006333 }
6334 }
6335 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006336
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006337 // See if we can fold the select into one of our operands.
6338 if (SI.getType()->isInteger()) {
6339 // See the comment above GetSelectFoldableOperands for a description of the
6340 // transformation we are doing here.
6341 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6342 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6343 !isa<Constant>(FalseVal))
6344 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6345 unsigned OpToFold = 0;
6346 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6347 OpToFold = 1;
6348 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6349 OpToFold = 2;
6350 }
6351
6352 if (OpToFold) {
6353 Constant *C = GetSelectFoldableConstant(TVI);
6354 std::string Name = TVI->getName(); TVI->setName("");
6355 Instruction *NewSel =
6356 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6357 Name);
6358 InsertNewInstBefore(NewSel, SI);
6359 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6360 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6361 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6362 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6363 else {
6364 assert(0 && "Unknown instruction!!");
6365 }
6366 }
6367 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006368
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006369 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6370 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6371 !isa<Constant>(TrueVal))
6372 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6373 unsigned OpToFold = 0;
6374 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6375 OpToFold = 1;
6376 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6377 OpToFold = 2;
6378 }
6379
6380 if (OpToFold) {
6381 Constant *C = GetSelectFoldableConstant(FVI);
6382 std::string Name = FVI->getName(); FVI->setName("");
6383 Instruction *NewSel =
6384 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6385 Name);
6386 InsertNewInstBefore(NewSel, SI);
6387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6388 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6389 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6390 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6391 else {
6392 assert(0 && "Unknown instruction!!");
6393 }
6394 }
6395 }
6396 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006397
6398 if (BinaryOperator::isNot(CondVal)) {
6399 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6400 SI.setOperand(1, FalseVal);
6401 SI.setOperand(2, TrueVal);
6402 return &SI;
6403 }
6404
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006405 return 0;
6406}
6407
Chris Lattner82f2ef22006-03-06 20:18:44 +00006408/// GetKnownAlignment - If the specified pointer has an alignment that we can
6409/// determine, return it, otherwise return 0.
6410static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6411 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6412 unsigned Align = GV->getAlignment();
6413 if (Align == 0 && TD)
6414 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6415 return Align;
6416 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6417 unsigned Align = AI->getAlignment();
6418 if (Align == 0 && TD) {
6419 if (isa<AllocaInst>(AI))
6420 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6421 else if (isa<MallocInst>(AI)) {
6422 // Malloc returns maximally aligned memory.
6423 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6424 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6425 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6426 }
6427 }
6428 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006429 } else if (isa<CastInst>(V) ||
6430 (isa<ConstantExpr>(V) &&
6431 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6432 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006433 if (isa<PointerType>(CI->getOperand(0)->getType()))
6434 return GetKnownAlignment(CI->getOperand(0), TD);
6435 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006436 } else if (isa<GetElementPtrInst>(V) ||
6437 (isa<ConstantExpr>(V) &&
6438 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6439 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006440 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6441 if (BaseAlignment == 0) return 0;
6442
6443 // If all indexes are zero, it is just the alignment of the base pointer.
6444 bool AllZeroOperands = true;
6445 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6446 if (!isa<Constant>(GEPI->getOperand(i)) ||
6447 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6448 AllZeroOperands = false;
6449 break;
6450 }
6451 if (AllZeroOperands)
6452 return BaseAlignment;
6453
6454 // Otherwise, if the base alignment is >= the alignment we expect for the
6455 // base pointer type, then we know that the resultant pointer is aligned at
6456 // least as much as its type requires.
6457 if (!TD) return 0;
6458
6459 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6460 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006461 <= BaseAlignment) {
6462 const Type *GEPTy = GEPI->getType();
6463 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6464 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006465 return 0;
6466 }
6467 return 0;
6468}
6469
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006470
Chris Lattnerc66b2232006-01-13 20:11:04 +00006471/// visitCallInst - CallInst simplification. This mostly only handles folding
6472/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6473/// the heavy lifting.
6474///
Chris Lattner970c33a2003-06-19 17:00:31 +00006475Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006476 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6477 if (!II) return visitCallSite(&CI);
6478
Chris Lattner51ea1272004-02-28 05:22:00 +00006479 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6480 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006481 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006482 bool Changed = false;
6483
6484 // memmove/cpy/set of zero bytes is a noop.
6485 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6486 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6487
Chris Lattner00648e12004-10-12 04:52:52 +00006488 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006489 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006490 // Replace the instruction with just byte operations. We would
6491 // transform other cases to loads/stores, but we don't know if
6492 // alignment is sufficient.
6493 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006494 }
6495
Chris Lattner00648e12004-10-12 04:52:52 +00006496 // If we have a memmove and the source operation is a constant global,
6497 // then the source and dest pointers can't alias, so we can change this
6498 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006499 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006500 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6501 if (GVSrc->isConstant()) {
6502 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006503 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006504 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006505 Type::UIntTy)
6506 Name = "llvm.memcpy.i32";
6507 else
6508 Name = "llvm.memcpy.i64";
6509 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006510 CI.getCalledFunction()->getFunctionType());
6511 CI.setOperand(0, MemCpy);
6512 Changed = true;
6513 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006514 }
Chris Lattner00648e12004-10-12 04:52:52 +00006515
Chris Lattner82f2ef22006-03-06 20:18:44 +00006516 // If we can determine a pointer alignment that is bigger than currently
6517 // set, update the alignment.
6518 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6519 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6520 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6521 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006522 if (MI->getAlignment()->getZExtValue() < Align) {
6523 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006524 Changed = true;
6525 }
6526 } else if (isa<MemSetInst>(MI)) {
6527 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006528 if (MI->getAlignment()->getZExtValue() < Alignment) {
6529 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006530 Changed = true;
6531 }
6532 }
6533
Chris Lattnerc66b2232006-01-13 20:11:04 +00006534 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006535 } else {
6536 switch (II->getIntrinsicID()) {
6537 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006538 case Intrinsic::ppc_altivec_lvx:
6539 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006540 case Intrinsic::x86_sse_loadu_ps:
6541 case Intrinsic::x86_sse2_loadu_pd:
6542 case Intrinsic::x86_sse2_loadu_dq:
6543 // Turn PPC lvx -> load if the pointer is known aligned.
6544 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006545 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006546 Value *Ptr = InsertCastBefore(II->getOperand(1),
6547 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006548 return new LoadInst(Ptr);
6549 }
6550 break;
6551 case Intrinsic::ppc_altivec_stvx:
6552 case Intrinsic::ppc_altivec_stvxl:
6553 // Turn stvx -> store if the pointer is known aligned.
6554 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006555 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6556 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006557 return new StoreInst(II->getOperand(1), Ptr);
6558 }
6559 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006560 case Intrinsic::x86_sse_storeu_ps:
6561 case Intrinsic::x86_sse2_storeu_pd:
6562 case Intrinsic::x86_sse2_storeu_dq:
6563 case Intrinsic::x86_sse2_storel_dq:
6564 // Turn X86 storeu -> store if the pointer is known aligned.
6565 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6566 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6567 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6568 return new StoreInst(II->getOperand(2), Ptr);
6569 }
6570 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006571
6572 case Intrinsic::x86_sse_cvttss2si: {
6573 // These intrinsics only demands the 0th element of its input vector. If
6574 // we can simplify the input based on that, do so now.
6575 uint64_t UndefElts;
6576 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6577 UndefElts)) {
6578 II->setOperand(1, V);
6579 return II;
6580 }
6581 break;
6582 }
6583
Chris Lattnere79d2492006-04-06 19:19:17 +00006584 case Intrinsic::ppc_altivec_vperm:
6585 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6586 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6587 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6588
6589 // Check that all of the elements are integer constants or undefs.
6590 bool AllEltsOk = true;
6591 for (unsigned i = 0; i != 16; ++i) {
6592 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6593 !isa<UndefValue>(Mask->getOperand(i))) {
6594 AllEltsOk = false;
6595 break;
6596 }
6597 }
6598
6599 if (AllEltsOk) {
6600 // Cast the input vectors to byte vectors.
6601 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6602 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6603 Value *Result = UndefValue::get(Op0->getType());
6604
6605 // Only extract each element once.
6606 Value *ExtractedElts[32];
6607 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6608
6609 for (unsigned i = 0; i != 16; ++i) {
6610 if (isa<UndefValue>(Mask->getOperand(i)))
6611 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006612 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006613 Idx &= 31; // Match the hardware behavior.
6614
6615 if (ExtractedElts[Idx] == 0) {
6616 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006617 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006618 InsertNewInstBefore(Elt, CI);
6619 ExtractedElts[Idx] = Elt;
6620 }
6621
6622 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006623 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006624 InsertNewInstBefore(cast<Instruction>(Result), CI);
6625 }
6626 return new CastInst(Result, CI.getType());
6627 }
6628 }
6629 break;
6630
Chris Lattner503221f2006-01-13 21:28:09 +00006631 case Intrinsic::stackrestore: {
6632 // If the save is right next to the restore, remove the restore. This can
6633 // happen when variable allocas are DCE'd.
6634 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6635 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6636 BasicBlock::iterator BI = SS;
6637 if (&*++BI == II)
6638 return EraseInstFromFunction(CI);
6639 }
6640 }
6641
6642 // If the stack restore is in a return/unwind block and if there are no
6643 // allocas or calls between the restore and the return, nuke the restore.
6644 TerminatorInst *TI = II->getParent()->getTerminator();
6645 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6646 BasicBlock::iterator BI = II;
6647 bool CannotRemove = false;
6648 for (++BI; &*BI != TI; ++BI) {
6649 if (isa<AllocaInst>(BI) ||
6650 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6651 CannotRemove = true;
6652 break;
6653 }
6654 }
6655 if (!CannotRemove)
6656 return EraseInstFromFunction(CI);
6657 }
6658 break;
6659 }
6660 }
Chris Lattner00648e12004-10-12 04:52:52 +00006661 }
6662
Chris Lattnerc66b2232006-01-13 20:11:04 +00006663 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006664}
6665
6666// InvokeInst simplification
6667//
6668Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006669 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006670}
6671
Chris Lattneraec3d942003-10-07 22:32:43 +00006672// visitCallSite - Improvements for call and invoke instructions.
6673//
6674Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006675 bool Changed = false;
6676
6677 // If the callee is a constexpr cast of a function, attempt to move the cast
6678 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006679 if (transformConstExprCastCall(CS)) return 0;
6680
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006681 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006682
Chris Lattner61d9d812005-05-13 07:09:09 +00006683 if (Function *CalleeF = dyn_cast<Function>(Callee))
6684 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6685 Instruction *OldCall = CS.getInstruction();
6686 // If the call and callee calling conventions don't match, this call must
6687 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006688 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006689 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6690 if (!OldCall->use_empty())
6691 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6692 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6693 return EraseInstFromFunction(*OldCall);
6694 return 0;
6695 }
6696
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006697 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6698 // This instruction is not reachable, just remove it. We insert a store to
6699 // undef so that we know that this code is not reachable, despite the fact
6700 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006701 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006702 UndefValue::get(PointerType::get(Type::BoolTy)),
6703 CS.getInstruction());
6704
6705 if (!CS.getInstruction()->use_empty())
6706 CS.getInstruction()->
6707 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6708
6709 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6710 // Don't break the CFG, insert a dummy cond branch.
6711 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006712 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006713 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006714 return EraseInstFromFunction(*CS.getInstruction());
6715 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006716
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006717 const PointerType *PTy = cast<PointerType>(Callee->getType());
6718 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6719 if (FTy->isVarArg()) {
6720 // See if we can optimize any arguments passed through the varargs area of
6721 // the call.
6722 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6723 E = CS.arg_end(); I != E; ++I)
6724 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6725 // If this cast does not effect the value passed through the varargs
6726 // area, we can eliminate the use of the cast.
6727 Value *Op = CI->getOperand(0);
6728 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6729 *I = Op;
6730 Changed = true;
6731 }
6732 }
6733 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006734
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006735 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006736}
6737
Chris Lattner970c33a2003-06-19 17:00:31 +00006738// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6739// attempt to move the cast to the arguments of the call/invoke.
6740//
6741bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6742 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6743 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006744 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006745 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006746 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006747 Instruction *Caller = CS.getInstruction();
6748
6749 // Okay, this is a cast from a function to a different type. Unless doing so
6750 // would cause a type conversion of one of our arguments, change this call to
6751 // be a direct call with arguments casted to the appropriate types.
6752 //
6753 const FunctionType *FT = Callee->getFunctionType();
6754 const Type *OldRetTy = Caller->getType();
6755
Chris Lattner1f7942f2004-01-14 06:06:08 +00006756 // Check to see if we are changing the return type...
6757 if (OldRetTy != FT->getReturnType()) {
6758 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006759 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6760 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006761 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006762 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006763 return false; // Cannot transform this return value...
6764
6765 // If the callsite is an invoke instruction, and the return value is used by
6766 // a PHI node in a successor, we cannot change the return type of the call
6767 // because there is no place to put the cast instruction (without breaking
6768 // the critical edge). Bail out in this case.
6769 if (!Caller->use_empty())
6770 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6771 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6772 UI != E; ++UI)
6773 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6774 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006775 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006776 return false;
6777 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006778
6779 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6780 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006781
Chris Lattner970c33a2003-06-19 17:00:31 +00006782 CallSite::arg_iterator AI = CS.arg_begin();
6783 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6784 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006785 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006786 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006787 //Either we can cast directly, or we can upconvert the argument
6788 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6789 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6790 ParamTy->isSigned() == ActTy->isSigned() &&
6791 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6792 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006793 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006794 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006795 }
6796
6797 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6798 Callee->isExternal())
6799 return false; // Do not delete arguments unless we have a function body...
6800
6801 // Okay, we decided that this is a safe thing to do: go ahead and start
6802 // inserting cast instructions as necessary...
6803 std::vector<Value*> Args;
6804 Args.reserve(NumActualArgs);
6805
6806 AI = CS.arg_begin();
6807 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6808 const Type *ParamTy = FT->getParamType(i);
6809 if ((*AI)->getType() == ParamTy) {
6810 Args.push_back(*AI);
6811 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006812 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6813 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006814 }
6815 }
6816
6817 // If the function takes more arguments than the call was taking, add them
6818 // now...
6819 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6820 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6821
6822 // If we are removing arguments to the function, emit an obnoxious warning...
6823 if (FT->getNumParams() < NumActualArgs)
6824 if (!FT->isVarArg()) {
6825 std::cerr << "WARNING: While resolving call to function '"
6826 << Callee->getName() << "' arguments were dropped!\n";
6827 } else {
6828 // Add all of the arguments in their promoted form to the arg list...
6829 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6830 const Type *PTy = getPromotedType((*AI)->getType());
6831 if (PTy != (*AI)->getType()) {
6832 // Must promote to pass through va_arg area!
6833 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6834 InsertNewInstBefore(Cast, *Caller);
6835 Args.push_back(Cast);
6836 } else {
6837 Args.push_back(*AI);
6838 }
6839 }
6840 }
6841
6842 if (FT->getReturnType() == Type::VoidTy)
6843 Caller->setName(""); // Void type should not have a name...
6844
6845 Instruction *NC;
6846 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006847 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006848 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006849 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006850 } else {
6851 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006852 if (cast<CallInst>(Caller)->isTailCall())
6853 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006854 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006855 }
6856
6857 // Insert a cast of the return type as necessary...
6858 Value *NV = NC;
6859 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6860 if (NV->getType() != Type::VoidTy) {
6861 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006862
6863 // If this is an invoke instruction, we should insert it after the first
6864 // non-phi, instruction in the normal successor block.
6865 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6866 BasicBlock::iterator I = II->getNormalDest()->begin();
6867 while (isa<PHINode>(I)) ++I;
6868 InsertNewInstBefore(NC, *I);
6869 } else {
6870 // Otherwise, it's a call, just insert cast right after the call instr
6871 InsertNewInstBefore(NC, *Caller);
6872 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006873 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006874 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006875 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006876 }
6877 }
6878
6879 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6880 Caller->replaceAllUsesWith(NV);
6881 Caller->getParent()->getInstList().erase(Caller);
6882 removeFromWorkList(Caller);
6883 return true;
6884}
6885
Chris Lattnercadac0c2006-11-01 04:51:18 +00006886/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6887/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6888/// and a single binop.
6889Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6890 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006891 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6892 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006893 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00006894 Value *LHSVal = FirstInst->getOperand(0);
6895 Value *RHSVal = FirstInst->getOperand(1);
6896
6897 const Type *LHSType = LHSVal->getType();
6898 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00006899
6900 // Scan to see if all operands are the same opcode, all have one use, and all
6901 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006902 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006903 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006904 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6905 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00006906 // types or GEP's with different index types.
6907 I->getOperand(0)->getType() != LHSType ||
6908 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00006909 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00006910
6911 // Keep track of which operand needs a phi node.
6912 if (I->getOperand(0) != LHSVal) LHSVal = 0;
6913 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00006914 }
6915
Chris Lattner4f218d52006-11-08 19:42:28 +00006916 // Otherwise, this is safe to transform, determine if it is profitable.
6917
6918 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
6919 // Indexes are often folded into load/store instructions, so we don't want to
6920 // hide them behind a phi.
6921 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
6922 return 0;
6923
Chris Lattnercadac0c2006-11-01 04:51:18 +00006924 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00006925 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00006926 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00006927 if (LHSVal == 0) {
6928 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
6929 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6930 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006931 InsertNewInstBefore(NewLHS, PN);
6932 LHSVal = NewLHS;
6933 }
Chris Lattnercd62f112006-11-08 19:29:23 +00006934
6935 if (RHSVal == 0) {
6936 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
6937 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6938 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00006939 InsertNewInstBefore(NewRHS, PN);
6940 RHSVal = NewRHS;
6941 }
6942
Chris Lattnercd62f112006-11-08 19:29:23 +00006943 // Add all operands to the new PHIs.
6944 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6945 if (NewLHS) {
6946 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6947 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6948 }
6949 if (NewRHS) {
6950 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6951 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6952 }
6953 }
6954
Chris Lattnercadac0c2006-11-01 04:51:18 +00006955 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00006956 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6957 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6958 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6959 else {
6960 assert(isa<GetElementPtrInst>(FirstInst));
6961 return new GetElementPtrInst(LHSVal, RHSVal);
6962 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00006963}
6964
Chris Lattner14f82c72006-11-01 07:13:54 +00006965/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6966/// of the block that defines it. This means that it must be obvious the value
6967/// of the load is not changed from the point of the load to the end of the
6968/// block it is in.
6969static bool isSafeToSinkLoad(LoadInst *L) {
6970 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6971
6972 for (++BBI; BBI != E; ++BBI)
6973 if (BBI->mayWriteToMemory())
6974 return false;
6975 return true;
6976}
6977
Chris Lattner970c33a2003-06-19 17:00:31 +00006978
Chris Lattner7515cab2004-11-14 19:13:23 +00006979// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6980// operator and they all are only used by the PHI, PHI together their
6981// inputs, and do the operation once, to the result of the PHI.
6982Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6983 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6984
6985 // Scan the instruction, looking for input operations that can be folded away.
6986 // If all input operands to the phi are the same instruction (e.g. a cast from
6987 // the same type or "+42") we can pull the operation through the PHI, reducing
6988 // code size and simplifying code.
6989 Constant *ConstantOp = 0;
6990 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00006991 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00006992 if (isa<CastInst>(FirstInst)) {
6993 CastSrcTy = FirstInst->getOperand(0)->getType();
6994 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006995 // Can fold binop or shift here if the RHS is a constant, otherwise call
6996 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00006997 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006998 if (ConstantOp == 0)
6999 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007000 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7001 isVolatile = LI->isVolatile();
7002 // We can't sink the load if the loaded value could be modified between the
7003 // load and the PHI.
7004 if (LI->getParent() != PN.getIncomingBlock(0) ||
7005 !isSafeToSinkLoad(LI))
7006 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007007 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007008 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007009 return FoldPHIArgBinOpIntoPHI(PN);
7010 // Can't handle general GEPs yet.
7011 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007012 } else {
7013 return 0; // Cannot fold this operation.
7014 }
7015
7016 // Check to see if all arguments are the same operation.
7017 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7018 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7019 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7020 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7021 return 0;
7022 if (CastSrcTy) {
7023 if (I->getOperand(0)->getType() != CastSrcTy)
7024 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007025 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7026 // We can't sink the load if the loaded value could be modified between the
7027 // load and the PHI.
7028 if (LI->isVolatile() != isVolatile ||
7029 LI->getParent() != PN.getIncomingBlock(i) ||
7030 !isSafeToSinkLoad(LI))
7031 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007032 } else if (I->getOperand(1) != ConstantOp) {
7033 return 0;
7034 }
7035 }
7036
7037 // Okay, they are all the same operation. Create a new PHI node of the
7038 // correct type, and PHI together all of the LHS's of the instructions.
7039 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7040 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007041 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007042
7043 Value *InVal = FirstInst->getOperand(0);
7044 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007045
7046 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007047 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7048 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7049 if (NewInVal != InVal)
7050 InVal = 0;
7051 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7052 }
7053
7054 Value *PhiVal;
7055 if (InVal) {
7056 // The new PHI unions all of the same values together. This is really
7057 // common, so we handle it intelligently here for compile-time speed.
7058 PhiVal = InVal;
7059 delete NewPN;
7060 } else {
7061 InsertNewInstBefore(NewPN, PN);
7062 PhiVal = NewPN;
7063 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007064
Chris Lattner7515cab2004-11-14 19:13:23 +00007065 // Insert and return the new operation.
7066 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007067 return new CastInst(PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007068 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007069 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007070 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007071 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007072 else
7073 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007074 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007075}
Chris Lattner48a44f72002-05-02 17:06:02 +00007076
Chris Lattner71536432005-01-17 05:10:15 +00007077/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7078/// that is dead.
7079static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7080 if (PN->use_empty()) return true;
7081 if (!PN->hasOneUse()) return false;
7082
7083 // Remember this node, and if we find the cycle, return.
7084 if (!PotentiallyDeadPHIs.insert(PN).second)
7085 return true;
7086
7087 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7088 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007089
Chris Lattner71536432005-01-17 05:10:15 +00007090 return false;
7091}
7092
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007093// PHINode simplification
7094//
Chris Lattner113f4f42002-06-25 16:13:24 +00007095Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007096 // If LCSSA is around, don't mess with Phi nodes
7097 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007098
Owen Andersonae8aa642006-07-10 22:03:18 +00007099 if (Value *V = PN.hasConstantValue())
7100 return ReplaceInstUsesWith(PN, V);
7101
7102 // If the only user of this instruction is a cast instruction, and all of the
7103 // incoming values are constants, change this PHI to merge together the casted
7104 // constants.
7105 if (PN.hasOneUse())
7106 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7107 if (CI->getType() != PN.getType()) { // noop casts will be folded
7108 bool AllConstant = true;
7109 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7110 if (!isa<Constant>(PN.getIncomingValue(i))) {
7111 AllConstant = false;
7112 break;
7113 }
7114 if (AllConstant) {
7115 // Make a new PHI with all casted values.
7116 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7117 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7118 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7119 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7120 PN.getIncomingBlock(i));
7121 }
7122
7123 // Update the cast instruction.
7124 CI->setOperand(0, New);
7125 WorkList.push_back(CI); // revisit the cast instruction to fold.
7126 WorkList.push_back(New); // Make sure to revisit the new Phi
7127 return &PN; // PN is now dead!
7128 }
7129 }
7130
7131 // If all PHI operands are the same operation, pull them through the PHI,
7132 // reducing code size.
7133 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7134 PN.getIncomingValue(0)->hasOneUse())
7135 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7136 return Result;
7137
7138 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7139 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7140 // PHI)... break the cycle.
7141 if (PN.hasOneUse())
7142 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7143 std::set<PHINode*> PotentiallyDeadPHIs;
7144 PotentiallyDeadPHIs.insert(&PN);
7145 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7146 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7147 }
7148
Chris Lattner91daeb52003-12-19 05:58:40 +00007149 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007150}
7151
Chris Lattner69193f92004-04-05 01:30:19 +00007152static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7153 Instruction *InsertPoint,
7154 InstCombiner *IC) {
7155 unsigned PS = IC->getTargetData().getPointerSize();
7156 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007157 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7158 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007159 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7160 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007161}
7162
Chris Lattner48a44f72002-05-02 17:06:02 +00007163
Chris Lattner113f4f42002-06-25 16:13:24 +00007164Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007165 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007166 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007167 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007168 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007169 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007170
Chris Lattner81a7a232004-10-16 18:11:37 +00007171 if (isa<UndefValue>(GEP.getOperand(0)))
7172 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7173
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007174 bool HasZeroPointerIndex = false;
7175 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7176 HasZeroPointerIndex = C->isNullValue();
7177
7178 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007179 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007180
Chris Lattner69193f92004-04-05 01:30:19 +00007181 // Eliminate unneeded casts for indices.
7182 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007183 gep_type_iterator GTI = gep_type_begin(GEP);
7184 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7185 if (isa<SequentialType>(*GTI)) {
7186 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7187 Value *Src = CI->getOperand(0);
7188 const Type *SrcTy = Src->getType();
7189 const Type *DestTy = CI->getType();
7190 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007191 if (SrcTy->getPrimitiveSizeInBits() ==
7192 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007193 // We can always eliminate a cast from ulong or long to the other.
7194 // We can always eliminate a cast from uint to int or the other on
7195 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007196 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007197 MadeChange = true;
7198 GEP.setOperand(i, Src);
7199 }
7200 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7201 SrcTy->getPrimitiveSize() == 4) {
7202 // We can always eliminate a cast from int to [u]long. We can
7203 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7204 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007205 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007206 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007207 MadeChange = true;
7208 GEP.setOperand(i, Src);
7209 }
Chris Lattner69193f92004-04-05 01:30:19 +00007210 }
7211 }
7212 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007213 // If we are using a wider index than needed for this platform, shrink it
7214 // to what we need. If the incoming value needs a cast instruction,
7215 // insert it. This explicit cast can make subsequent optimizations more
7216 // obvious.
7217 Value *Op = GEP.getOperand(i);
7218 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007219 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007220 GEP.setOperand(i, ConstantExpr::getCast(C,
7221 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007222 MadeChange = true;
7223 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007224 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007225 GEP.setOperand(i, Op);
7226 MadeChange = true;
7227 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007228
7229 // If this is a constant idx, make sure to canonicalize it to be a signed
7230 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007231 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7232 if (CUI->getType()->isUnsigned()) {
7233 GEP.setOperand(i,
7234 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7235 MadeChange = true;
7236 }
Chris Lattner69193f92004-04-05 01:30:19 +00007237 }
7238 if (MadeChange) return &GEP;
7239
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007240 // Combine Indices - If the source pointer to this getelementptr instruction
7241 // is a getelementptr instruction, combine the indices of the two
7242 // getelementptr instructions into a single instruction.
7243 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007244 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007245 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007246 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007247
7248 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007249 // Note that if our source is a gep chain itself that we wait for that
7250 // chain to be resolved before we perform this transformation. This
7251 // avoids us creating a TON of code in some cases.
7252 //
7253 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7254 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7255 return 0; // Wait until our source is folded to completion.
7256
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007257 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007258
7259 // Find out whether the last index in the source GEP is a sequential idx.
7260 bool EndsWithSequential = false;
7261 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7262 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007263 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007264
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007265 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007266 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007267 // Replace: gep (gep %P, long B), long A, ...
7268 // With: T = long A+B; gep %P, T, ...
7269 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007270 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007271 if (SO1 == Constant::getNullValue(SO1->getType())) {
7272 Sum = GO1;
7273 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7274 Sum = SO1;
7275 } else {
7276 // If they aren't the same type, convert both to an integer of the
7277 // target's pointer size.
7278 if (SO1->getType() != GO1->getType()) {
7279 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7280 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7281 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7282 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7283 } else {
7284 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007285 if (SO1->getType()->getPrimitiveSize() == PS) {
7286 // Convert GO1 to SO1's type.
7287 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7288
7289 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7290 // Convert SO1 to GO1's type.
7291 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7292 } else {
7293 const Type *PT = TD->getIntPtrType();
7294 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7295 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7296 }
7297 }
7298 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007299 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7300 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7301 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007302 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7303 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007304 }
Chris Lattner69193f92004-04-05 01:30:19 +00007305 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007306
7307 // Recycle the GEP we already have if possible.
7308 if (SrcGEPOperands.size() == 2) {
7309 GEP.setOperand(0, SrcGEPOperands[0]);
7310 GEP.setOperand(1, Sum);
7311 return &GEP;
7312 } else {
7313 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7314 SrcGEPOperands.end()-1);
7315 Indices.push_back(Sum);
7316 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7317 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007318 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007319 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007320 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007321 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007322 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7323 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007324 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7325 }
7326
7327 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007328 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007329
Chris Lattner5f667a62004-05-07 22:09:22 +00007330 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007331 // GEP of global variable. If all of the indices for this GEP are
7332 // constants, we can promote this to a constexpr instead of an instruction.
7333
7334 // Scan for nonconstants...
7335 std::vector<Constant*> Indices;
7336 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7337 for (; I != E && isa<Constant>(*I); ++I)
7338 Indices.push_back(cast<Constant>(*I));
7339
7340 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007341 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007342
7343 // Replace all uses of the GEP with the new constexpr...
7344 return ReplaceInstUsesWith(GEP, CE);
7345 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007346 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7347 if (!isa<PointerType>(X->getType())) {
7348 // Not interesting. Source pointer must be a cast from pointer.
7349 } else if (HasZeroPointerIndex) {
7350 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7351 // into : GEP [10 x ubyte]* X, long 0, ...
7352 //
7353 // This occurs when the program declares an array extern like "int X[];"
7354 //
7355 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7356 const PointerType *XTy = cast<PointerType>(X->getType());
7357 if (const ArrayType *XATy =
7358 dyn_cast<ArrayType>(XTy->getElementType()))
7359 if (const ArrayType *CATy =
7360 dyn_cast<ArrayType>(CPTy->getElementType()))
7361 if (CATy->getElementType() == XATy->getElementType()) {
7362 // At this point, we know that the cast source type is a pointer
7363 // to an array of the same type as the destination pointer
7364 // array. Because the array type is never stepped over (there
7365 // is a leading zero) we can fold the cast into this GEP.
7366 GEP.setOperand(0, X);
7367 return &GEP;
7368 }
7369 } else if (GEP.getNumOperands() == 2) {
7370 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007371 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7372 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007373 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7374 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7375 if (isa<ArrayType>(SrcElTy) &&
7376 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7377 TD->getTypeSize(ResElTy)) {
7378 Value *V = InsertNewInstBefore(
7379 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7380 GEP.getOperand(1), GEP.getName()), GEP);
7381 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007382 }
Chris Lattner2a893292005-09-13 18:36:04 +00007383
7384 // Transform things like:
7385 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7386 // (where tmp = 8*tmp2) into:
7387 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7388
7389 if (isa<ArrayType>(SrcElTy) &&
7390 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7391 uint64_t ArrayEltSize =
7392 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7393
7394 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7395 // allow either a mul, shift, or constant here.
7396 Value *NewIdx = 0;
7397 ConstantInt *Scale = 0;
7398 if (ArrayEltSize == 1) {
7399 NewIdx = GEP.getOperand(1);
7400 Scale = ConstantInt::get(NewIdx->getType(), 1);
7401 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007402 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007403 Scale = CI;
7404 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7405 if (Inst->getOpcode() == Instruction::Shl &&
7406 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007407 unsigned ShAmt =
7408 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007409 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007410 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007411 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007412 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007413 NewIdx = Inst->getOperand(0);
7414 } else if (Inst->getOpcode() == Instruction::Mul &&
7415 isa<ConstantInt>(Inst->getOperand(1))) {
7416 Scale = cast<ConstantInt>(Inst->getOperand(1));
7417 NewIdx = Inst->getOperand(0);
7418 }
7419 }
7420
7421 // If the index will be to exactly the right offset with the scale taken
7422 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007423 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007424 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007425 Scale = ConstantInt::get(Scale->getType(),
7426 Scale->getZExtValue() / ArrayEltSize);
7427 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007428 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7429 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7430 NewIdx = InsertNewInstBefore(Sc, GEP);
7431 }
7432
7433 // Insert the new GEP instruction.
7434 Instruction *Idx =
7435 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7436 NewIdx, GEP.getName());
7437 Idx = InsertNewInstBefore(Idx, GEP);
7438 return new CastInst(Idx, GEP.getType());
7439 }
7440 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007441 }
Chris Lattnerca081252001-12-14 16:52:21 +00007442 }
7443
Chris Lattnerca081252001-12-14 16:52:21 +00007444 return 0;
7445}
7446
Chris Lattner1085bdf2002-11-04 16:18:53 +00007447Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7448 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7449 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007450 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7451 const Type *NewTy =
7452 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007453 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007454
7455 // Create and insert the replacement instruction...
7456 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007457 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007458 else {
7459 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007460 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007461 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007462
7463 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007464
Chris Lattner1085bdf2002-11-04 16:18:53 +00007465 // Scan to the end of the allocation instructions, to skip over a block of
7466 // allocas if possible...
7467 //
7468 BasicBlock::iterator It = New;
7469 while (isa<AllocationInst>(*It)) ++It;
7470
7471 // Now that I is pointing to the first non-allocation-inst in the block,
7472 // insert our getelementptr instruction...
7473 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007474 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7475 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7476 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007477
7478 // Now make everything use the getelementptr instead of the original
7479 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007480 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007481 } else if (isa<UndefValue>(AI.getArraySize())) {
7482 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007483 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007484
7485 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7486 // Note that we only do this for alloca's, because malloc should allocate and
7487 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007488 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007489 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007490 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7491
Chris Lattner1085bdf2002-11-04 16:18:53 +00007492 return 0;
7493}
7494
Chris Lattner8427bff2003-12-07 01:24:23 +00007495Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7496 Value *Op = FI.getOperand(0);
7497
7498 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7499 if (CastInst *CI = dyn_cast<CastInst>(Op))
7500 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7501 FI.setOperand(0, CI->getOperand(0));
7502 return &FI;
7503 }
7504
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007505 // free undef -> unreachable.
7506 if (isa<UndefValue>(Op)) {
7507 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007508 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007509 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7510 return EraseInstFromFunction(FI);
7511 }
7512
Chris Lattnerf3a36602004-02-28 04:57:37 +00007513 // If we have 'free null' delete the instruction. This can happen in stl code
7514 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007515 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007516 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007517
Chris Lattner8427bff2003-12-07 01:24:23 +00007518 return 0;
7519}
7520
7521
Chris Lattner72684fe2005-01-31 05:51:45 +00007522/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007523static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7524 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007525 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007526
7527 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007528 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007529 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007530
Chris Lattnerebca4762006-04-02 05:37:12 +00007531 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7532 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007533 // If the source is an array, the code below will not succeed. Check to
7534 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7535 // constants.
7536 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7537 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7538 if (ASrcTy->getNumElements() != 0) {
7539 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7540 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7541 SrcTy = cast<PointerType>(CastOp->getType());
7542 SrcPTy = SrcTy->getElementType();
7543 }
7544
Chris Lattnerebca4762006-04-02 05:37:12 +00007545 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7546 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007547 // Do not allow turning this into a load of an integer, which is then
7548 // casted to a pointer, this pessimizes pointer analysis a lot.
7549 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007550 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007551 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007552
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007553 // Okay, we are casting from one integer or pointer type to another of
7554 // the same size. Instead of casting the pointer before the load, cast
7555 // the result of the loaded value.
7556 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7557 CI->getName(),
7558 LI.isVolatile()),LI);
7559 // Now cast the result of the load.
7560 return new CastInst(NewLoad, LI.getType());
7561 }
Chris Lattner35e24772004-07-13 01:49:43 +00007562 }
7563 }
7564 return 0;
7565}
7566
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007567/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007568/// from this value cannot trap. If it is not obviously safe to load from the
7569/// specified pointer, we do a quick local scan of the basic block containing
7570/// ScanFrom, to determine if the address is already accessed.
7571static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7572 // If it is an alloca or global variable, it is always safe to load from.
7573 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7574
7575 // Otherwise, be a little bit agressive by scanning the local block where we
7576 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007577 // from/to. If so, the previous load or store would have already trapped,
7578 // so there is no harm doing an extra load (also, CSE will later eliminate
7579 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007580 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7581
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007582 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007583 --BBI;
7584
7585 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7586 if (LI->getOperand(0) == V) return true;
7587 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7588 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007589
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007590 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007591 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007592}
7593
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007594Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7595 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007596
Chris Lattnera9d84e32005-05-01 04:24:53 +00007597 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007598 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007599 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7600 return Res;
7601
7602 // None of the following transforms are legal for volatile loads.
7603 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007604
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007605 if (&LI.getParent()->front() != &LI) {
7606 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007607 // If the instruction immediately before this is a store to the same
7608 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007609 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7610 if (SI->getOperand(1) == LI.getOperand(0))
7611 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007612 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7613 if (LIB->getOperand(0) == LI.getOperand(0))
7614 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007615 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007616
7617 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7618 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7619 isa<UndefValue>(GEPI->getOperand(0))) {
7620 // Insert a new store to null instruction before the load to indicate
7621 // that this code is not reachable. We do this instead of inserting
7622 // an unreachable instruction directly because we cannot modify the
7623 // CFG.
7624 new StoreInst(UndefValue::get(LI.getType()),
7625 Constant::getNullValue(Op->getType()), &LI);
7626 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7627 }
7628
Chris Lattner81a7a232004-10-16 18:11:37 +00007629 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007630 // load null/undef -> undef
7631 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007632 // Insert a new store to null instruction before the load to indicate that
7633 // this code is not reachable. We do this instead of inserting an
7634 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007635 new StoreInst(UndefValue::get(LI.getType()),
7636 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007637 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007638 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007639
Chris Lattner81a7a232004-10-16 18:11:37 +00007640 // Instcombine load (constant global) into the value loaded.
7641 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7642 if (GV->isConstant() && !GV->isExternal())
7643 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007644
Chris Lattner81a7a232004-10-16 18:11:37 +00007645 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7646 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7647 if (CE->getOpcode() == Instruction::GetElementPtr) {
7648 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7649 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007650 if (Constant *V =
7651 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007652 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007653 if (CE->getOperand(0)->isNullValue()) {
7654 // Insert a new store to null instruction before the load to indicate
7655 // that this code is not reachable. We do this instead of inserting
7656 // an unreachable instruction directly because we cannot modify the
7657 // CFG.
7658 new StoreInst(UndefValue::get(LI.getType()),
7659 Constant::getNullValue(Op->getType()), &LI);
7660 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7661 }
7662
Chris Lattner81a7a232004-10-16 18:11:37 +00007663 } else if (CE->getOpcode() == Instruction::Cast) {
7664 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7665 return Res;
7666 }
7667 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007668
Chris Lattnera9d84e32005-05-01 04:24:53 +00007669 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007670 // Change select and PHI nodes to select values instead of addresses: this
7671 // helps alias analysis out a lot, allows many others simplifications, and
7672 // exposes redundancy in the code.
7673 //
7674 // Note that we cannot do the transformation unless we know that the
7675 // introduced loads cannot trap! Something like this is valid as long as
7676 // the condition is always false: load (select bool %C, int* null, int* %G),
7677 // but it would not be valid if we transformed it to load from null
7678 // unconditionally.
7679 //
7680 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7681 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007682 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7683 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007684 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007685 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007686 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007687 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007688 return new SelectInst(SI->getCondition(), V1, V2);
7689 }
7690
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007691 // load (select (cond, null, P)) -> load P
7692 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7693 if (C->isNullValue()) {
7694 LI.setOperand(0, SI->getOperand(2));
7695 return &LI;
7696 }
7697
7698 // load (select (cond, P, null)) -> load P
7699 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7700 if (C->isNullValue()) {
7701 LI.setOperand(0, SI->getOperand(1));
7702 return &LI;
7703 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007704 }
7705 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007706 return 0;
7707}
7708
Chris Lattner72684fe2005-01-31 05:51:45 +00007709/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7710/// when possible.
7711static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7712 User *CI = cast<User>(SI.getOperand(1));
7713 Value *CastOp = CI->getOperand(0);
7714
7715 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7716 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7717 const Type *SrcPTy = SrcTy->getElementType();
7718
7719 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7720 // If the source is an array, the code below will not succeed. Check to
7721 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7722 // constants.
7723 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7724 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7725 if (ASrcTy->getNumElements() != 0) {
7726 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7727 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7728 SrcTy = cast<PointerType>(CastOp->getType());
7729 SrcPTy = SrcTy->getElementType();
7730 }
7731
7732 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007733 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007734 IC.getTargetData().getTypeSize(DestPTy)) {
7735
7736 // Okay, we are casting from one integer or pointer type to another of
7737 // the same size. Instead of casting the pointer before the store, cast
7738 // the value to be stored.
7739 Value *NewCast;
7740 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7741 NewCast = ConstantExpr::getCast(C, SrcPTy);
7742 else
7743 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7744 SrcPTy,
7745 SI.getOperand(0)->getName()+".c"), SI);
7746
7747 return new StoreInst(NewCast, CastOp);
7748 }
7749 }
7750 }
7751 return 0;
7752}
7753
Chris Lattner31f486c2005-01-31 05:36:43 +00007754Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7755 Value *Val = SI.getOperand(0);
7756 Value *Ptr = SI.getOperand(1);
7757
7758 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007759 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007760 ++NumCombined;
7761 return 0;
7762 }
7763
Chris Lattner5997cf92006-02-08 03:25:32 +00007764 // Do really simple DSE, to catch cases where there are several consequtive
7765 // stores to the same location, separated by a few arithmetic operations. This
7766 // situation often occurs with bitfield accesses.
7767 BasicBlock::iterator BBI = &SI;
7768 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7769 --ScanInsts) {
7770 --BBI;
7771
7772 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7773 // Prev store isn't volatile, and stores to the same location?
7774 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7775 ++NumDeadStore;
7776 ++BBI;
7777 EraseInstFromFunction(*PrevSI);
7778 continue;
7779 }
7780 break;
7781 }
7782
Chris Lattnerdab43b22006-05-26 19:19:20 +00007783 // If this is a load, we have to stop. However, if the loaded value is from
7784 // the pointer we're loading and is producing the pointer we're storing,
7785 // then *this* store is dead (X = load P; store X -> P).
7786 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7787 if (LI == Val && LI->getOperand(0) == Ptr) {
7788 EraseInstFromFunction(SI);
7789 ++NumCombined;
7790 return 0;
7791 }
7792 // Otherwise, this is a load from some other location. Stores before it
7793 // may not be dead.
7794 break;
7795 }
7796
Chris Lattner5997cf92006-02-08 03:25:32 +00007797 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007798 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007799 break;
7800 }
7801
7802
7803 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007804
7805 // store X, null -> turns into 'unreachable' in SimplifyCFG
7806 if (isa<ConstantPointerNull>(Ptr)) {
7807 if (!isa<UndefValue>(Val)) {
7808 SI.setOperand(0, UndefValue::get(Val->getType()));
7809 if (Instruction *U = dyn_cast<Instruction>(Val))
7810 WorkList.push_back(U); // Dropped a use.
7811 ++NumCombined;
7812 }
7813 return 0; // Do not modify these!
7814 }
7815
7816 // store undef, Ptr -> noop
7817 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007818 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007819 ++NumCombined;
7820 return 0;
7821 }
7822
Chris Lattner72684fe2005-01-31 05:51:45 +00007823 // If the pointer destination is a cast, see if we can fold the cast into the
7824 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00007825 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00007826 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7827 return Res;
7828 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7829 if (CE->getOpcode() == Instruction::Cast)
7830 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7831 return Res;
7832
Chris Lattner219175c2005-09-12 23:23:25 +00007833
7834 // If this store is the last instruction in the basic block, and if the block
7835 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007836 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007837 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7838 if (BI->isUnconditional()) {
7839 // Check to see if the successor block has exactly two incoming edges. If
7840 // so, see if the other predecessor contains a store to the same location.
7841 // if so, insert a PHI node (if needed) and move the stores down.
7842 BasicBlock *Dest = BI->getSuccessor(0);
7843
7844 pred_iterator PI = pred_begin(Dest);
7845 BasicBlock *Other = 0;
7846 if (*PI != BI->getParent())
7847 Other = *PI;
7848 ++PI;
7849 if (PI != pred_end(Dest)) {
7850 if (*PI != BI->getParent())
7851 if (Other)
7852 Other = 0;
7853 else
7854 Other = *PI;
7855 if (++PI != pred_end(Dest))
7856 Other = 0;
7857 }
7858 if (Other) { // If only one other pred...
7859 BBI = Other->getTerminator();
7860 // Make sure this other block ends in an unconditional branch and that
7861 // there is an instruction before the branch.
7862 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7863 BBI != Other->begin()) {
7864 --BBI;
7865 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7866
7867 // If this instruction is a store to the same location.
7868 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7869 // Okay, we know we can perform this transformation. Insert a PHI
7870 // node now if we need it.
7871 Value *MergedVal = OtherStore->getOperand(0);
7872 if (MergedVal != SI.getOperand(0)) {
7873 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7874 PN->reserveOperandSpace(2);
7875 PN->addIncoming(SI.getOperand(0), SI.getParent());
7876 PN->addIncoming(OtherStore->getOperand(0), Other);
7877 MergedVal = InsertNewInstBefore(PN, Dest->front());
7878 }
7879
7880 // Advance to a place where it is safe to insert the new store and
7881 // insert it.
7882 BBI = Dest->begin();
7883 while (isa<PHINode>(BBI)) ++BBI;
7884 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7885 OtherStore->isVolatile()), *BBI);
7886
7887 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007888 EraseInstFromFunction(SI);
7889 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007890 ++NumCombined;
7891 return 0;
7892 }
7893 }
7894 }
7895 }
7896
Chris Lattner31f486c2005-01-31 05:36:43 +00007897 return 0;
7898}
7899
7900
Chris Lattner9eef8a72003-06-04 04:46:00 +00007901Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7902 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007903 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007904 BasicBlock *TrueDest;
7905 BasicBlock *FalseDest;
7906 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7907 !isa<Constant>(X)) {
7908 // Swap Destinations and condition...
7909 BI.setCondition(X);
7910 BI.setSuccessor(0, FalseDest);
7911 BI.setSuccessor(1, TrueDest);
7912 return &BI;
7913 }
7914
7915 // Cannonicalize setne -> seteq
7916 Instruction::BinaryOps Op; Value *Y;
7917 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7918 TrueDest, FalseDest)))
7919 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7920 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7921 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7922 std::string Name = I->getName(); I->setName("");
7923 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7924 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007925 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007926 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007927 BI.setSuccessor(0, FalseDest);
7928 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007929 removeFromWorkList(I);
7930 I->getParent()->getInstList().erase(I);
7931 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007932 return &BI;
7933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007934
Chris Lattner9eef8a72003-06-04 04:46:00 +00007935 return 0;
7936}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007937
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007938Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7939 Value *Cond = SI.getCondition();
7940 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7941 if (I->getOpcode() == Instruction::Add)
7942 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7943 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7944 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007945 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007946 AddRHS));
7947 SI.setOperand(0, I->getOperand(0));
7948 WorkList.push_back(I);
7949 return &SI;
7950 }
7951 }
7952 return 0;
7953}
7954
Chris Lattner6bc98652006-03-05 00:22:33 +00007955/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7956/// is to leave as a vector operation.
7957static bool CheapToScalarize(Value *V, bool isConstant) {
7958 if (isa<ConstantAggregateZero>(V))
7959 return true;
7960 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7961 if (isConstant) return true;
7962 // If all elts are the same, we can extract.
7963 Constant *Op0 = C->getOperand(0);
7964 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7965 if (C->getOperand(i) != Op0)
7966 return false;
7967 return true;
7968 }
7969 Instruction *I = dyn_cast<Instruction>(V);
7970 if (!I) return false;
7971
7972 // Insert element gets simplified to the inserted element or is deleted if
7973 // this is constant idx extract element and its a constant idx insertelt.
7974 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7975 isa<ConstantInt>(I->getOperand(2)))
7976 return true;
7977 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7978 return true;
7979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7980 if (BO->hasOneUse() &&
7981 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7982 CheapToScalarize(BO->getOperand(1), isConstant)))
7983 return true;
7984
7985 return false;
7986}
7987
Chris Lattner12249be2006-05-25 23:48:38 +00007988/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7989/// elements into values that are larger than the #elts in the input.
7990static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7991 unsigned NElts = SVI->getType()->getNumElements();
7992 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7993 return std::vector<unsigned>(NElts, 0);
7994 if (isa<UndefValue>(SVI->getOperand(2)))
7995 return std::vector<unsigned>(NElts, 2*NElts);
7996
7997 std::vector<unsigned> Result;
7998 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7999 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8000 if (isa<UndefValue>(CP->getOperand(i)))
8001 Result.push_back(NElts*2); // undef -> 8
8002 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008003 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008004 return Result;
8005}
8006
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008007/// FindScalarElement - Given a vector and an element number, see if the scalar
8008/// value is already around as a register, for example if it were inserted then
8009/// extracted from the vector.
8010static Value *FindScalarElement(Value *V, unsigned EltNo) {
8011 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8012 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008013 unsigned Width = PTy->getNumElements();
8014 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008015 return UndefValue::get(PTy->getElementType());
8016
8017 if (isa<UndefValue>(V))
8018 return UndefValue::get(PTy->getElementType());
8019 else if (isa<ConstantAggregateZero>(V))
8020 return Constant::getNullValue(PTy->getElementType());
8021 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8022 return CP->getOperand(EltNo);
8023 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8024 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008025 if (!isa<ConstantInt>(III->getOperand(2)))
8026 return 0;
8027 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008028
8029 // If this is an insert to the element we are looking for, return the
8030 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008031 if (EltNo == IIElt)
8032 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008033
8034 // Otherwise, the insertelement doesn't modify the value, recurse on its
8035 // vector input.
8036 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008037 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008038 unsigned InEl = getShuffleMask(SVI)[EltNo];
8039 if (InEl < Width)
8040 return FindScalarElement(SVI->getOperand(0), InEl);
8041 else if (InEl < Width*2)
8042 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8043 else
8044 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008045 }
8046
8047 // Otherwise, we don't know.
8048 return 0;
8049}
8050
Robert Bocchinoa8352962006-01-13 22:48:06 +00008051Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008052
Chris Lattner92346c32006-03-31 18:25:14 +00008053 // If packed val is undef, replace extract with scalar undef.
8054 if (isa<UndefValue>(EI.getOperand(0)))
8055 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8056
8057 // If packed val is constant 0, replace extract with scalar 0.
8058 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8059 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8060
Robert Bocchinoa8352962006-01-13 22:48:06 +00008061 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8062 // If packed val is constant with uniform operands, replace EI
8063 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008064 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008065 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008066 if (C->getOperand(i) != op0) {
8067 op0 = 0;
8068 break;
8069 }
8070 if (op0)
8071 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008072 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008073
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008074 // If extracting a specified index from the vector, see if we can recursively
8075 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008076 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008077 // This instruction only demands the single element from the input vector.
8078 // If the input vector has a single use, simplify it based on this use
8079 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008080 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008081 if (EI.getOperand(0)->hasOneUse()) {
8082 uint64_t UndefElts;
8083 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008084 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008085 UndefElts)) {
8086 EI.setOperand(0, V);
8087 return &EI;
8088 }
8089 }
8090
Reid Spencere0fc4df2006-10-20 07:07:24 +00008091 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008092 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008093 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008094
Chris Lattner83f65782006-05-25 22:53:38 +00008095 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008096 if (I->hasOneUse()) {
8097 // Push extractelement into predecessor operation if legal and
8098 // profitable to do so
8099 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008100 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8101 if (CheapToScalarize(BO, isConstantElt)) {
8102 ExtractElementInst *newEI0 =
8103 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8104 EI.getName()+".lhs");
8105 ExtractElementInst *newEI1 =
8106 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8107 EI.getName()+".rhs");
8108 InsertNewInstBefore(newEI0, EI);
8109 InsertNewInstBefore(newEI1, EI);
8110 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8111 }
Reid Spencerde46e482006-11-02 20:25:50 +00008112 } else if (isa<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008113 Value *Ptr = InsertCastBefore(I->getOperand(0),
8114 PointerType::get(EI.getType()), EI);
8115 GetElementPtrInst *GEP =
8116 new GetElementPtrInst(Ptr, EI.getOperand(1),
8117 I->getName() + ".gep");
8118 InsertNewInstBefore(GEP, EI);
8119 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008120 }
8121 }
8122 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8123 // Extracting the inserted element?
8124 if (IE->getOperand(2) == EI.getOperand(1))
8125 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8126 // If the inserted and extracted elements are constants, they must not
8127 // be the same value, extract from the pre-inserted value instead.
8128 if (isa<Constant>(IE->getOperand(2)) &&
8129 isa<Constant>(EI.getOperand(1))) {
8130 AddUsesToWorkList(EI);
8131 EI.setOperand(0, IE->getOperand(0));
8132 return &EI;
8133 }
8134 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8135 // If this is extracting an element from a shufflevector, figure out where
8136 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008137 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8138 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008139 Value *Src;
8140 if (SrcIdx < SVI->getType()->getNumElements())
8141 Src = SVI->getOperand(0);
8142 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8143 SrcIdx -= SVI->getType()->getNumElements();
8144 Src = SVI->getOperand(1);
8145 } else {
8146 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008147 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008148 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008149 }
8150 }
Chris Lattner83f65782006-05-25 22:53:38 +00008151 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008152 return 0;
8153}
8154
Chris Lattner90951862006-04-16 00:51:47 +00008155/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8156/// elements from either LHS or RHS, return the shuffle mask and true.
8157/// Otherwise, return false.
8158static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8159 std::vector<Constant*> &Mask) {
8160 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8161 "Invalid CollectSingleShuffleElements");
8162 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8163
8164 if (isa<UndefValue>(V)) {
8165 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8166 return true;
8167 } else if (V == LHS) {
8168 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008169 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008170 return true;
8171 } else if (V == RHS) {
8172 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008173 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008174 return true;
8175 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8176 // If this is an insert of an extract from some other vector, include it.
8177 Value *VecOp = IEI->getOperand(0);
8178 Value *ScalarOp = IEI->getOperand(1);
8179 Value *IdxOp = IEI->getOperand(2);
8180
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008181 if (!isa<ConstantInt>(IdxOp))
8182 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008183 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008184
8185 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8186 // Okay, we can handle this if the vector we are insertinting into is
8187 // transitively ok.
8188 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8189 // If so, update the mask to reflect the inserted undef.
8190 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8191 return true;
8192 }
8193 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8194 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008195 EI->getOperand(0)->getType() == V->getType()) {
8196 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008197 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008198
8199 // This must be extracting from either LHS or RHS.
8200 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8201 // Okay, we can handle this if the vector we are insertinting into is
8202 // transitively ok.
8203 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8204 // If so, update the mask to reflect the inserted value.
8205 if (EI->getOperand(0) == LHS) {
8206 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008207 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008208 } else {
8209 assert(EI->getOperand(0) == RHS);
8210 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008211 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008212
8213 }
8214 return true;
8215 }
8216 }
8217 }
8218 }
8219 }
8220 // TODO: Handle shufflevector here!
8221
8222 return false;
8223}
8224
8225/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8226/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8227/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008228static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008229 Value *&RHS) {
8230 assert(isa<PackedType>(V->getType()) &&
8231 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008232 "Invalid shuffle!");
8233 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8234
8235 if (isa<UndefValue>(V)) {
8236 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8237 return V;
8238 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008239 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008240 return V;
8241 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8242 // If this is an insert of an extract from some other vector, include it.
8243 Value *VecOp = IEI->getOperand(0);
8244 Value *ScalarOp = IEI->getOperand(1);
8245 Value *IdxOp = IEI->getOperand(2);
8246
8247 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8248 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8249 EI->getOperand(0)->getType() == V->getType()) {
8250 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008251 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8252 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008253
8254 // Either the extracted from or inserted into vector must be RHSVec,
8255 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008256 if (EI->getOperand(0) == RHS || RHS == 0) {
8257 RHS = EI->getOperand(0);
8258 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008259 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008260 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008261 return V;
8262 }
8263
Chris Lattner90951862006-04-16 00:51:47 +00008264 if (VecOp == RHS) {
8265 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008266 // Everything but the extracted element is replaced with the RHS.
8267 for (unsigned i = 0; i != NumElts; ++i) {
8268 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008269 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008270 }
8271 return V;
8272 }
Chris Lattner90951862006-04-16 00:51:47 +00008273
8274 // If this insertelement is a chain that comes from exactly these two
8275 // vectors, return the vector and the effective shuffle.
8276 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8277 return EI->getOperand(0);
8278
Chris Lattner39fac442006-04-15 01:39:45 +00008279 }
8280 }
8281 }
Chris Lattner90951862006-04-16 00:51:47 +00008282 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008283
8284 // Otherwise, can't do anything fancy. Return an identity vector.
8285 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008286 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008287 return V;
8288}
8289
8290Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8291 Value *VecOp = IE.getOperand(0);
8292 Value *ScalarOp = IE.getOperand(1);
8293 Value *IdxOp = IE.getOperand(2);
8294
8295 // If the inserted element was extracted from some other vector, and if the
8296 // indexes are constant, try to turn this into a shufflevector operation.
8297 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8298 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8299 EI->getOperand(0)->getType() == IE.getType()) {
8300 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008301 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8302 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008303
8304 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8305 return ReplaceInstUsesWith(IE, VecOp);
8306
8307 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8308 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8309
8310 // If we are extracting a value from a vector, then inserting it right
8311 // back into the same place, just use the input vector.
8312 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8313 return ReplaceInstUsesWith(IE, VecOp);
8314
8315 // We could theoretically do this for ANY input. However, doing so could
8316 // turn chains of insertelement instructions into a chain of shufflevector
8317 // instructions, and right now we do not merge shufflevectors. As such,
8318 // only do this in a situation where it is clear that there is benefit.
8319 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8320 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8321 // the values of VecOp, except then one read from EIOp0.
8322 // Build a new shuffle mask.
8323 std::vector<Constant*> Mask;
8324 if (isa<UndefValue>(VecOp))
8325 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8326 else {
8327 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008328 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008329 NumVectorElts));
8330 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008331 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008332 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8333 ConstantPacked::get(Mask));
8334 }
8335
8336 // If this insertelement isn't used by some other insertelement, turn it
8337 // (and any insertelements it points to), into one big shuffle.
8338 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8339 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008340 Value *RHS = 0;
8341 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8342 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8343 // We now have a shuffle of LHS, RHS, Mask.
8344 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008345 }
8346 }
8347 }
8348
8349 return 0;
8350}
8351
8352
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008353Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8354 Value *LHS = SVI.getOperand(0);
8355 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008356 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008357
8358 bool MadeChange = false;
8359
Chris Lattner2deeaea2006-10-05 06:55:50 +00008360 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008361 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008362 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8363
Chris Lattner39fac442006-04-15 01:39:45 +00008364 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8365 // the undef, change them to undefs.
8366
Chris Lattner12249be2006-05-25 23:48:38 +00008367 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8368 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8369 if (LHS == RHS || isa<UndefValue>(LHS)) {
8370 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008371 // shuffle(undef,undef,mask) -> undef.
8372 return ReplaceInstUsesWith(SVI, LHS);
8373 }
8374
Chris Lattner12249be2006-05-25 23:48:38 +00008375 // Remap any references to RHS to use LHS.
8376 std::vector<Constant*> Elts;
8377 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008378 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008379 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008380 else {
8381 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8382 (Mask[i] < e && isa<UndefValue>(LHS)))
8383 Mask[i] = 2*e; // Turn into undef.
8384 else
8385 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008386 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008387 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008388 }
Chris Lattner12249be2006-05-25 23:48:38 +00008389 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008390 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008391 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008392 LHS = SVI.getOperand(0);
8393 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008394 MadeChange = true;
8395 }
8396
Chris Lattner0e477162006-05-26 00:29:06 +00008397 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008398 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008399
Chris Lattner12249be2006-05-25 23:48:38 +00008400 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8401 if (Mask[i] >= e*2) continue; // Ignore undef values.
8402 // Is this an identity shuffle of the LHS value?
8403 isLHSID &= (Mask[i] == i);
8404
8405 // Is this an identity shuffle of the RHS value?
8406 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008407 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008408
Chris Lattner12249be2006-05-25 23:48:38 +00008409 // Eliminate identity shuffles.
8410 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8411 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008412
Chris Lattner0e477162006-05-26 00:29:06 +00008413 // If the LHS is a shufflevector itself, see if we can combine it with this
8414 // one without producing an unusual shuffle. Here we are really conservative:
8415 // we are absolutely afraid of producing a shuffle mask not in the input
8416 // program, because the code gen may not be smart enough to turn a merged
8417 // shuffle into two specific shuffles: it may produce worse code. As such,
8418 // we only merge two shuffles if the result is one of the two input shuffle
8419 // masks. In this case, merging the shuffles just removes one instruction,
8420 // which we know is safe. This is good for things like turning:
8421 // (splat(splat)) -> splat.
8422 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8423 if (isa<UndefValue>(RHS)) {
8424 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8425
8426 std::vector<unsigned> NewMask;
8427 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8428 if (Mask[i] >= 2*e)
8429 NewMask.push_back(2*e);
8430 else
8431 NewMask.push_back(LHSMask[Mask[i]]);
8432
8433 // If the result mask is equal to the src shuffle or this shuffle mask, do
8434 // the replacement.
8435 if (NewMask == LHSMask || NewMask == Mask) {
8436 std::vector<Constant*> Elts;
8437 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8438 if (NewMask[i] >= e*2) {
8439 Elts.push_back(UndefValue::get(Type::UIntTy));
8440 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008441 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008442 }
8443 }
8444 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8445 LHSSVI->getOperand(1),
8446 ConstantPacked::get(Elts));
8447 }
8448 }
8449 }
8450
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008451 return MadeChange ? &SVI : 0;
8452}
8453
8454
Robert Bocchinoa8352962006-01-13 22:48:06 +00008455
Chris Lattner99f48c62002-09-02 04:59:56 +00008456void InstCombiner::removeFromWorkList(Instruction *I) {
8457 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8458 WorkList.end());
8459}
8460
Chris Lattner39c98bb2004-12-08 23:43:58 +00008461
8462/// TryToSinkInstruction - Try to move the specified instruction from its
8463/// current block into the beginning of DestBlock, which can only happen if it's
8464/// safe to move the instruction past all of the instructions between it and the
8465/// end of its block.
8466static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8467 assert(I->hasOneUse() && "Invariants didn't hold!");
8468
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008469 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8470 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008471
Chris Lattner39c98bb2004-12-08 23:43:58 +00008472 // Do not sink alloca instructions out of the entry block.
8473 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8474 return false;
8475
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008476 // We can only sink load instructions if there is nothing between the load and
8477 // the end of block that could change the value.
8478 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008479 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8480 Scan != E; ++Scan)
8481 if (Scan->mayWriteToMemory())
8482 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008483 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008484
8485 BasicBlock::iterator InsertPos = DestBlock->begin();
8486 while (isa<PHINode>(InsertPos)) ++InsertPos;
8487
Chris Lattner9f269e42005-08-08 19:11:57 +00008488 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008489 ++NumSunkInst;
8490 return true;
8491}
8492
Chris Lattner1443bc52006-05-11 17:11:52 +00008493/// OptimizeConstantExpr - Given a constant expression and target data layout
8494/// information, symbolically evaluation the constant expr to something simpler
8495/// if possible.
8496static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8497 if (!TD) return CE;
8498
8499 Constant *Ptr = CE->getOperand(0);
8500 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8501 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8502 // If this is a constant expr gep that is effectively computing an
8503 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8504 bool isFoldableGEP = true;
8505 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8506 if (!isa<ConstantInt>(CE->getOperand(i)))
8507 isFoldableGEP = false;
8508 if (isFoldableGEP) {
8509 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8510 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008511 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008512 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8513 return ConstantExpr::getCast(C, CE->getType());
8514 }
8515 }
8516
8517 return CE;
8518}
8519
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008520
8521/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8522/// all reachable code to the worklist.
8523///
8524/// This has a couple of tricks to make the code faster and more powerful. In
8525/// particular, we constant fold and DCE instructions as we go, to avoid adding
8526/// them to the worklist (this significantly speeds up instcombine on code where
8527/// many instructions are dead or constant). Additionally, if we find a branch
8528/// whose condition is a known constant, we only visit the reachable successors.
8529///
8530static void AddReachableCodeToWorklist(BasicBlock *BB,
8531 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008532 std::vector<Instruction*> &WorkList,
8533 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008534 // We have now visited this block! If we've already been here, bail out.
8535 if (!Visited.insert(BB).second) return;
8536
8537 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8538 Instruction *Inst = BBI++;
8539
8540 // DCE instruction if trivially dead.
8541 if (isInstructionTriviallyDead(Inst)) {
8542 ++NumDeadInst;
8543 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8544 Inst->eraseFromParent();
8545 continue;
8546 }
8547
8548 // ConstantProp instruction if trivially constant.
8549 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008550 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8551 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008552 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8553 Inst->replaceAllUsesWith(C);
8554 ++NumConstProp;
8555 Inst->eraseFromParent();
8556 continue;
8557 }
8558
8559 WorkList.push_back(Inst);
8560 }
8561
8562 // Recursively visit successors. If this is a branch or switch on a constant,
8563 // only visit the reachable successor.
8564 TerminatorInst *TI = BB->getTerminator();
8565 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8566 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8567 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008568 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8569 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008570 return;
8571 }
8572 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8573 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8574 // See if this is an explicit destination.
8575 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8576 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008577 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008578 return;
8579 }
8580
8581 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008582 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008583 return;
8584 }
8585 }
8586
8587 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008588 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008589}
8590
Chris Lattner113f4f42002-06-25 16:13:24 +00008591bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008592 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008593 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008594
Chris Lattner4ed40f72005-07-07 20:40:38 +00008595 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008596 // Do a depth-first traversal of the function, populate the worklist with
8597 // the reachable instructions. Ignore blocks that are not reachable. Keep
8598 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008599 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008600 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008601
Chris Lattner4ed40f72005-07-07 20:40:38 +00008602 // Do a quick scan over the function. If we find any blocks that are
8603 // unreachable, remove any instructions inside of them. This prevents
8604 // the instcombine code from having to deal with some bad special cases.
8605 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8606 if (!Visited.count(BB)) {
8607 Instruction *Term = BB->getTerminator();
8608 while (Term != BB->begin()) { // Remove instrs bottom-up
8609 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008610
Chris Lattner4ed40f72005-07-07 20:40:38 +00008611 DEBUG(std::cerr << "IC: DCE: " << *I);
8612 ++NumDeadInst;
8613
8614 if (!I->use_empty())
8615 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8616 I->eraseFromParent();
8617 }
8618 }
8619 }
Chris Lattnerca081252001-12-14 16:52:21 +00008620
8621 while (!WorkList.empty()) {
8622 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8623 WorkList.pop_back();
8624
Chris Lattner1443bc52006-05-11 17:11:52 +00008625 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008626 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008627 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008628 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008629 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008630 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008631
Chris Lattnercd517ff2005-01-28 19:32:01 +00008632 DEBUG(std::cerr << "IC: DCE: " << *I);
8633
8634 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008635 removeFromWorkList(I);
8636 continue;
8637 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008638
Chris Lattner1443bc52006-05-11 17:11:52 +00008639 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008640 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008641 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8642 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008643 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8644
Chris Lattner1443bc52006-05-11 17:11:52 +00008645 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008646 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008647 ReplaceInstUsesWith(*I, C);
8648
Chris Lattner99f48c62002-09-02 04:59:56 +00008649 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008650 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008651 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008652 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008653 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008654
Chris Lattner39c98bb2004-12-08 23:43:58 +00008655 // See if we can trivially sink this instruction to a successor basic block.
8656 if (I->hasOneUse()) {
8657 BasicBlock *BB = I->getParent();
8658 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8659 if (UserParent != BB) {
8660 bool UserIsSuccessor = false;
8661 // See if the user is one of our successors.
8662 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8663 if (*SI == UserParent) {
8664 UserIsSuccessor = true;
8665 break;
8666 }
8667
8668 // If the user is one of our immediate successors, and if that successor
8669 // only has us as a predecessors (we'd have to split the critical edge
8670 // otherwise), we can keep going.
8671 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8672 next(pred_begin(UserParent)) == pred_end(UserParent))
8673 // Okay, the CFG is simple enough, try to sink this instruction.
8674 Changed |= TryToSinkInstruction(I, UserParent);
8675 }
8676 }
8677
Chris Lattnerca081252001-12-14 16:52:21 +00008678 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008679 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008680 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008681 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008682 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008683 DEBUG(std::cerr << "IC: Old = " << *I
8684 << " New = " << *Result);
8685
Chris Lattner396dbfe2004-06-09 05:08:07 +00008686 // Everything uses the new instruction now.
8687 I->replaceAllUsesWith(Result);
8688
8689 // Push the new instruction and any users onto the worklist.
8690 WorkList.push_back(Result);
8691 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008692
8693 // Move the name to the new instruction first...
8694 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008695 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008696
8697 // Insert the new instruction into the basic block...
8698 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008699 BasicBlock::iterator InsertPos = I;
8700
8701 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8702 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8703 ++InsertPos;
8704
8705 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008706
Chris Lattner63d75af2004-05-01 23:27:23 +00008707 // Make sure that we reprocess all operands now that we reduced their
8708 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008709 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8710 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8711 WorkList.push_back(OpI);
8712
Chris Lattner396dbfe2004-06-09 05:08:07 +00008713 // Instructions can end up on the worklist more than once. Make sure
8714 // we do not process an instruction that has been deleted.
8715 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008716
8717 // Erase the old instruction.
8718 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008719 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008720 DEBUG(std::cerr << "IC: MOD = " << *I);
8721
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008722 // If the instruction was modified, it's possible that it is now dead.
8723 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008724 if (isInstructionTriviallyDead(I)) {
8725 // Make sure we process all operands now that we are reducing their
8726 // use counts.
8727 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8728 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8729 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008730
Chris Lattner63d75af2004-05-01 23:27:23 +00008731 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008732 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008733 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008734 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008735 } else {
8736 WorkList.push_back(Result);
8737 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008738 }
Chris Lattner053c0932002-05-14 15:24:07 +00008739 }
Chris Lattner260ab202002-04-18 17:39:14 +00008740 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008741 }
8742 }
8743
Chris Lattner260ab202002-04-18 17:39:14 +00008744 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008745}
8746
Brian Gaeke38b79e82004-07-27 17:43:21 +00008747FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008748 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008749}
Brian Gaeke960707c2003-11-11 22:41:34 +00008750