blob: f631d61457316e9d197a69fe540529100671beec [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 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.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 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.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
204
205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208 BinaryOperator &I);
209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
211 Instruction *commonPointerCastTransforms(CastInst &CI);
212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000221 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 Instruction *visitBitCast(BitCastInst &CI);
224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman58c09632008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232 Instruction *visitAllocationInst(AllocationInst &AI);
233 Instruction *visitFreeInst(FreeInst &FI);
234 Instruction *visitLoadInst(LoadInst &LI);
235 Instruction *visitStoreInst(StoreInst &SI);
236 Instruction *visitBranchInst(BranchInst &BI);
237 Instruction *visitSwitchInst(SwitchInst &SI);
238 Instruction *visitInsertElementInst(InsertElementInst &IE);
239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
244 Instruction *visitInstruction(Instruction &I) { return 0; }
245
246 private:
247 Instruction *visitCallSite(CallSite CS);
248 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000253 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
254
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255
256 public:
257 // InsertNewInstBefore - insert an instruction New before instruction Old
258 // in the program. Add the new instruction to the worklist.
259 //
260 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
261 assert(New && New->getParent() == 0 &&
262 "New instruction already inserted into a basic block!");
263 BasicBlock *BB = Old.getParent();
264 BB->getInstList().insert(&Old, New); // Insert inst
265 AddToWorkList(New);
266 return New;
267 }
268
269 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
270 /// This also adds the cast to the worklist. Finally, this returns the
271 /// cast.
272 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
273 Instruction &Pos) {
274 if (V->getType() == Ty) return V;
275
276 if (Constant *CV = dyn_cast<Constant>(V))
277 return ConstantExpr::getCast(opc, CV, Ty);
278
Gabor Greifa645dd32008-05-16 19:29:10 +0000279 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 AddToWorkList(C);
281 return C;
282 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000283
284 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
285 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
286 }
287
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288
289 // ReplaceInstUsesWith - This method is to be used when an instruction is
290 // found to be dead, replacable with another preexisting expression. Here
291 // we add all uses of I to the worklist, replace all uses of I with the new
292 // value, then return I, so that the inst combiner will know that I was
293 // modified.
294 //
295 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
296 AddUsersToWorkList(I); // Add all modified instrs to worklist
297 if (&I != V) {
298 I.replaceAllUsesWith(V);
299 return &I;
300 } else {
301 // If we are replacing the instruction with itself, this must be in a
302 // segment of unreachable code, so just clobber the instruction.
303 I.replaceAllUsesWith(UndefValue::get(I.getType()));
304 return &I;
305 }
306 }
307
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 // EraseInstFromFunction - When dealing with an instruction that has side
309 // effects or produces a void value, we can't rely on DCE to delete the
310 // instruction. Instead, visit methods should return the value returned by
311 // this function.
312 Instruction *EraseInstFromFunction(Instruction &I) {
313 assert(I.use_empty() && "Cannot erase instruction that is used!");
314 AddUsesToWorkList(I);
315 RemoveFromWorkList(&I);
316 I.eraseFromParent();
317 return 0; // Don't do anything with FI
318 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000319
320 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
321 APInt &KnownOne, unsigned Depth = 0) const {
322 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
323 }
324
325 bool MaskedValueIsZero(Value *V, const APInt &Mask,
326 unsigned Depth = 0) const {
327 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
328 }
329 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
330 return llvm::ComputeNumSignBits(Op, TD, Depth);
331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332
333 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
335 /// SimplifyCommutative - This performs a few simplifications for
336 /// commutative operators.
337 bool SimplifyCommutative(BinaryOperator &I);
338
339 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340 /// most-complex to least-complex order.
341 bool SimplifyCompare(CmpInst &I);
342
Chris Lattner676c78e2009-01-31 08:15:18 +0000343 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
344 /// based on the demanded bits.
345 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth);
348 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000350 unsigned Depth=0);
351
352 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
353 /// SimplifyDemandedBits knows about. See if the instruction has any
354 /// properties that allow us to simplify its operands.
355 bool SimplifyDemandedInstructionBits(Instruction &Inst);
356
Evan Cheng63295ab2009-02-03 10:05:09 +0000357 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
358 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359
360 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
361 // PHI node as operand #0, see if we can fold the instruction into the PHI
362 // (which is only possible if all operands to the PHI are constants).
363 Instruction *FoldOpIntoPhi(Instruction &I);
364
365 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
366 // operator and they all are only used by the PHI, PHI together their
367 // inputs, and do the operation once, to the result of the PHI.
368 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
369 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000370 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372
373 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
374 ConstantInt *AndRHS, BinaryOperator &TheAnd);
375
376 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
377 bool isSub, Instruction &I);
378 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
379 bool isSigned, bool Inside, Instruction &IB);
380 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
381 Instruction *MatchBSwap(BinaryOperator &I);
382 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000383 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000384 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000385
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386
387 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000388
Dan Gohman2d648bb2008-04-10 18:43:06 +0000389 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000390 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000391 unsigned GetOrEnforceKnownAlignment(Value *V,
392 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000393
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395}
396
Dan Gohman089efff2008-05-13 00:00:25 +0000397char InstCombiner::ID = 0;
398static RegisterPass<InstCombiner>
399X("instcombine", "Combine redundant instructions");
400
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401// getComplexity: Assign a complexity or rank value to LLVM Values...
402// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
403static unsigned getComplexity(Value *V) {
404 if (isa<Instruction>(V)) {
405 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
406 return 3;
407 return 4;
408 }
409 if (isa<Argument>(V)) return 3;
410 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
411}
412
413// isOnlyUse - Return true if this instruction will be deleted if we stop using
414// it.
415static bool isOnlyUse(Value *V) {
416 return V->hasOneUse() || isa<Constant>(V);
417}
418
419// getPromotedType - Return the specified type promoted as it would be to pass
420// though a va_arg area...
421static const Type *getPromotedType(const Type *Ty) {
422 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
423 if (ITy->getBitWidth() < 32)
424 return Type::Int32Ty;
425 }
426 return Ty;
427}
428
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000429/// getBitCastOperand - If the specified operand is a CastInst, a constant
430/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
431/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432static Value *getBitCastOperand(Value *V) {
433 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000434 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000436 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
437 // GetElementPtrInst?
438 if (GEP->hasAllZeroIndices())
439 return GEP->getOperand(0);
440 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000442 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000444 else if (CE->getOpcode() == Instruction::GetElementPtr) {
445 // GetElementPtr ConstantExp?
446 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
447 I != E; ++I) {
448 ConstantInt *CI = dyn_cast<ConstantInt>(I);
449 if (!CI || !CI->isZero())
450 // Any non-zero indices? Not cast-like.
451 return 0;
452 }
453 // All-zero indices? This is just like casting.
454 return CE->getOperand(0);
455 }
456 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 return 0;
458}
459
460/// This function is a wrapper around CastInst::isEliminableCastPair. It
461/// simply extracts arguments and returns what that function returns.
462static Instruction::CastOps
463isEliminableCastPair(
464 const CastInst *CI, ///< The first cast instruction
465 unsigned opcode, ///< The opcode of the second cast instruction
466 const Type *DstTy, ///< The target type for the second cast instruction
467 TargetData *TD ///< The target data for pointer size
468) {
469
470 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
471 const Type *MidTy = CI->getType(); // B from above
472
473 // Get the opcodes of the two Cast instructions
474 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
475 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
476
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000477 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
478 DstTy, TD->getIntPtrType());
479
480 // We don't want to form an inttoptr or ptrtoint that converts to an integer
481 // type that differs from the pointer size.
482 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
483 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
484 Res = 0;
485
486 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
496 // If this is another cast that can be eliminated, it isn't codegen either.
497 if (const CastInst *CI = dyn_cast<CastInst>(V))
498 if (isEliminableCastPair(CI, opcode, Ty, TD))
499 return false;
500 return true;
501}
502
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
505//
506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512//
513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514 bool Changed = false;
515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516 Changed = !I.swapOperands();
517
518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
528 return true;
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 Op1->getOperand(0),
539 Op1->getName(), &I);
540 AddToWorkList(New);
541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
543 return true;
544 }
545 }
546 return Changed;
547}
548
549/// SimplifyCompare - For a CmpInst this function just orders the operands
550/// so that theyare listed from right (least complex) to left (most complex).
551/// This puts constants before unary operators before binary operators.
552bool InstCombiner::SimplifyCompare(CmpInst &I) {
553 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
562//
563static inline Value *dyn_castNegVal(Value *V) {
564 if (BinaryOperator::isNeg(V))
565 return BinaryOperator::getNegArgument(V);
566
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
573 return ConstantExpr::getNeg(C);
574
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return 0;
576}
577
578static inline Value *dyn_castNotVal(Value *V) {
579 if (BinaryOperator::isNot(V))
580 return BinaryOperator::getNotArgument(V);
581
582 // Constants can be considered to be not'ed values...
583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584 return ConstantInt::get(~C->getValue());
585 return 0;
586}
587
588// dyn_castFoldableMul - If this value is a multiply that can be folded into
589// other computations (because it has a constant operand), return the
590// non-constant operand of the multiply, and set CST to point to the multiplier.
591// Otherwise, return null.
592//
593static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
594 if (V->hasOneUse() && V->getType()->isInteger())
595 if (Instruction *I = dyn_cast<Instruction>(V)) {
596 if (I->getOpcode() == Instruction::Mul)
597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
598 return I->getOperand(0);
599 if (I->getOpcode() == Instruction::Shl)
600 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
601 // The multiplier is really 1 << CST.
602 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
603 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
604 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
605 return I->getOperand(0);
606 }
607 }
608 return 0;
609}
610
611/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612/// expression, return it.
613static User *dyn_castGetElementPtr(Value *V) {
614 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616 if (CE->getOpcode() == Instruction::GetElementPtr)
617 return cast<User>(V);
618 return false;
619}
620
Dan Gohman2d648bb2008-04-10 18:43:06 +0000621/// getOpcode - If this is an Instruction or a ConstantExpr, return the
622/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000623static unsigned getOpcode(const Value *V) {
624 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000625 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000626 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000627 return CE->getOpcode();
628 // Use UserOp1 to mean there's no opcode.
629 return Instruction::UserOp1;
630}
631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632/// AddOne - Add one to a ConstantInt
633static ConstantInt *AddOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(++Val);
636}
637/// SubOne - Subtract one from a ConstantInt
638static ConstantInt *SubOne(ConstantInt *C) {
639 APInt Val(C->getValue());
640 return ConstantInt::get(--Val);
641}
642/// Add - Add two ConstantInts together
643static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() + C2->getValue());
645}
646/// And - Bitwise AND two ConstantInts together
647static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() & C2->getValue());
649}
650/// Subtract - Subtract one ConstantInt from another
651static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() - C2->getValue());
653}
654/// Multiply - Multiply two ConstantInts together
655static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656 return ConstantInt::get(C1->getValue() * C2->getValue());
657}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000658/// MultiplyOverflows - True if the multiply can not be expressed in an int
659/// this size.
660static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661 uint32_t W = C1->getBitWidth();
662 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663 if (sign) {
664 LHSExt.sext(W * 2);
665 RHSExt.sext(W * 2);
666 } else {
667 LHSExt.zext(W * 2);
668 RHSExt.zext(W * 2);
669 }
670
671 APInt MulExt = LHSExt * RHSExt;
672
673 if (sign) {
674 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676 return MulExt.slt(Min) || MulExt.sgt(Max);
677 } else
678 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
679}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681
682/// ShrinkDemandedConstant - Check to see if the specified operand of the
683/// specified instruction is a constant integer. If so, check to see if there
684/// are any bits set in the constant that are not demanded. If so, shrink the
685/// constant and return true.
686static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
687 APInt Demanded) {
688 assert(I && "No instruction?");
689 assert(OpNo < I->getNumOperands() && "Operand index too large");
690
691 // If the operand is not a constant integer, nothing to do.
692 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693 if (!OpC) return false;
694
695 // If there are no bits set that aren't demanded, nothing to do.
696 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697 if ((~Demanded & OpC->getValue()) == 0)
698 return false;
699
700 // This instruction is producing bits that are not demanded. Shrink the RHS.
701 Demanded &= OpC->getValue();
702 I->setOperand(OpNo, ConstantInt::get(Demanded));
703 return true;
704}
705
706// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
707// set of known zero and one bits, compute the maximum and minimum values that
708// could have the specified known zero and known one bits, returning them in
709// min/max.
710static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
711 const APInt& KnownZero,
712 const APInt& KnownOne,
713 APInt& Min, APInt& Max) {
714 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715 assert(KnownZero.getBitWidth() == BitWidth &&
716 KnownOne.getBitWidth() == BitWidth &&
717 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
719 APInt UnknownBits = ~(KnownZero|KnownOne);
720
721 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722 // bit if it is unknown.
723 Min = KnownOne;
724 Max = KnownOne|UnknownBits;
725
726 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
727 Min.set(BitWidth-1);
728 Max.clear(BitWidth-1);
729 }
730}
731
732// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733// a set of known zero and one bits, compute the maximum and minimum values that
734// could have the specified known zero and known one bits, returning them in
735// min/max.
736static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000737 const APInt &KnownZero,
738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
740 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 assert(KnownZero.getBitWidth() == BitWidth &&
742 KnownOne.getBitWidth() == BitWidth &&
743 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745 APInt UnknownBits = ~(KnownZero|KnownOne);
746
747 // The minimum value is when the unknown bits are all zeros.
748 Min = KnownOne;
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
751}
752
Chris Lattner676c78e2009-01-31 08:15:18 +0000753/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
754/// SimplifyDemandedBits knows about. See if the instruction has any
755/// properties that allow us to simplify its operands.
756bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
757 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
758 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
759 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
760
761 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
762 KnownZero, KnownOne, 0);
763 if (V == 0) return false;
764 if (V == &Inst) return true;
765 ReplaceInstUsesWith(Inst, V);
766 return true;
767}
768
769/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
770/// specified instruction operand if possible, updating it in place. It returns
771/// true if it made any change and false otherwise.
772bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
773 APInt &KnownZero, APInt &KnownOne,
774 unsigned Depth) {
775 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
776 KnownZero, KnownOne, Depth);
777 if (NewVal == 0) return false;
778 U.set(NewVal);
779 return true;
780}
781
782
783/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
784/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785/// that only the bits set in DemandedMask of the result of V are ever used
786/// downstream. Consequently, depending on the mask and V, it may be possible
787/// to replace V with a constant or one of its operands. In such cases, this
788/// function does the replacement and returns true. In all other cases, it
789/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000790/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791/// to be zero in the expression. These are provided to potentially allow the
792/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
793/// the expression. KnownOne and KnownZero always follow the invariant that
794/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
795/// the bits in KnownOne and KnownZero may only be accurate for those bits set
796/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
797/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000798///
799/// This returns null if it did not change anything and it permits no
800/// simplification. This returns V itself if it did some simplification of V's
801/// operands based on the information about what bits are demanded. This returns
802/// some other non-null value if it found out that V is equal to another value
803/// in the context where the specified bits are demanded, but not for all users.
804Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
805 APInt &KnownZero, APInt &KnownOne,
806 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 assert(V != 0 && "Null pointer of Value???");
808 assert(Depth <= 6 && "Limit Search Depth");
809 uint32_t BitWidth = DemandedMask.getBitWidth();
810 const IntegerType *VTy = cast<IntegerType>(V->getType());
811 assert(VTy->getBitWidth() == BitWidth &&
812 KnownZero.getBitWidth() == BitWidth &&
813 KnownOne.getBitWidth() == BitWidth &&
814 "Value *V, DemandedMask, KnownZero and KnownOne \
815 must have same BitWidth");
816 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
817 // We know all of the bits for a constant!
818 KnownOne = CI->getValue() & DemandedMask;
819 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000820 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 }
822
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000823 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
827 return 0;
828 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 }
830
Chris Lattner08817332009-01-31 08:24:16 +0000831 if (Depth == 6) // Limit search depth.
832 return 0;
833
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner676c78e2009-01-31 08:15:18 +0000835 if (!I) return 0; // Only analyze instructions.
Chris Lattner08817332009-01-31 08:24:16 +0000836
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000837 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
838 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
839
Chris Lattner08817332009-01-31 08:24:16 +0000840 // If there are multiple uses of this value and we aren't at the root, then
841 // we can't do any simplifications of the operands, because DemandedMask
842 // only reflects the bits demanded by *one* of the users.
843 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000844 // Despite the fact that we can't simplify this instruction in all User's
845 // context, we can at least compute the knownzero/knownone bits, and we can
846 // do simplifications that apply to *just* the one user if we know that
847 // this instruction has a simpler value in that context.
848 if (I->getOpcode() == Instruction::And) {
849 // If either the LHS or the RHS are Zero, the result is zero.
850 ComputeMaskedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1);
852 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853 LHSKnownZero, LHSKnownOne, Depth+1);
854
855 // If all of the demanded bits are known 1 on one side, return the other.
856 // These bits cannot contribute to the result of the 'and' in this
857 // context.
858 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
859 (DemandedMask & ~LHSKnownZero))
860 return I->getOperand(0);
861 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
862 (DemandedMask & ~RHSKnownZero))
863 return I->getOperand(1);
864
865 // If all of the demanded bits in the inputs are known zeros, return zero.
866 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867 return Constant::getNullValue(VTy);
868
869 } else if (I->getOpcode() == Instruction::Or) {
870 // We can simplify (X|Y) -> X or Y in the user's context if we know that
871 // only bits from X or Y are demanded.
872
873 // If either the LHS or the RHS are One, the result is One.
874 ComputeMaskedBits(I->getOperand(1), DemandedMask,
875 RHSKnownZero, RHSKnownOne, Depth+1);
876 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
877 LHSKnownZero, LHSKnownOne, Depth+1);
878
879 // If all of the demanded bits are known zero on one side, return the
880 // other. These bits cannot contribute to the result of the 'or' in this
881 // context.
882 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
883 (DemandedMask & ~LHSKnownOne))
884 return I->getOperand(0);
885 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
886 (DemandedMask & ~RHSKnownOne))
887 return I->getOperand(1);
888
889 // If all of the potentially set bits on one side are known to be set on
890 // the other side, just use the 'other' side.
891 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
892 (DemandedMask & (~RHSKnownZero)))
893 return I->getOperand(0);
894 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
895 (DemandedMask & (~LHSKnownZero)))
896 return I->getOperand(1);
897 }
898
Chris Lattner08817332009-01-31 08:24:16 +0000899 // Compute the KnownZero/KnownOne bits to simplify things downstream.
900 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
901 return 0;
902 }
903
904 // If this is the root being simplified, allow it to have multiple uses,
905 // just set the DemandedMask to all bits so that we can try to simplify the
906 // operands. This allows visitTruncInst (for example) to simplify the
907 // operand of a trunc without duplicating all the logic below.
908 if (Depth == 0 && !V->hasOneUse())
909 DemandedMask = APInt::getAllOnesValue(BitWidth);
910
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000912 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000913 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000914 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 case Instruction::And:
916 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000917 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1) ||
919 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000921 return I;
922 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
923 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924
925 // If all of the demanded bits are known 1 on one side, return the other.
926 // These bits cannot contribute to the result of the 'and'.
927 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
928 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000929 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
931 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000932 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933
934 // If all of the demanded bits in the inputs are known zeros, return zero.
935 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000936 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937
938 // If the RHS is a constant, see if we can simplify it.
939 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000940 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941
942 // Output known-1 bits are only known if set in both the LHS & RHS.
943 RHSKnownOne &= LHSKnownOne;
944 // Output known-0 are known to be clear if zero in either the LHS | RHS.
945 RHSKnownZero |= LHSKnownZero;
946 break;
947 case Instruction::Or:
948 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000949 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
950 RHSKnownZero, RHSKnownOne, Depth+1) ||
951 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000953 return I;
954 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
955 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
957 // If all of the demanded bits are known zero on one side, return the other.
958 // These bits cannot contribute to the result of the 'or'.
959 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
960 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000961 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
963 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000964 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965
966 // If all of the potentially set bits on one side are known to be set on
967 // the other side, just use the 'other' side.
968 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
969 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000970 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
972 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000973 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974
975 // If the RHS is a constant, see if we can simplify it.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978
979 // Output known-0 bits are only known if clear in both the LHS & RHS.
980 RHSKnownZero &= LHSKnownZero;
981 // Output known-1 are known to be set if set in either the LHS | RHS.
982 RHSKnownOne |= LHSKnownOne;
983 break;
984 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000985 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1) ||
987 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000989 return I;
990 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
991 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992
993 // If all of the demanded bits are known zero on one side, return the other.
994 // These bits cannot contribute to the result of the 'xor'.
995 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000996 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000998 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999
1000 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1002 (RHSKnownOne & LHSKnownOne);
1003 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1005 (RHSKnownOne & LHSKnownZero);
1006
1007 // If all of the demanded bits are known to be zero on one side or the
1008 // other, turn this into an *inclusive* or.
1009 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1011 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001012 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001014 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 }
1016
1017 // If all of the demanded bits on one side are known, and all of the set
1018 // bits on that side are also known to be set on the other side, turn this
1019 // into an AND, as we know the bits will be cleared.
1020 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1022 // all known
1023 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1025 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001026 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001027 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 }
1029 }
1030
1031 // If the RHS is a constant, see if we can simplify it.
1032 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001034 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035
1036 RHSKnownZero = KnownZeroOut;
1037 RHSKnownOne = KnownOneOut;
1038 break;
1039 }
1040 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001041 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042 RHSKnownZero, RHSKnownOne, Depth+1) ||
1043 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001045 return I;
1046 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1047 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048
1049 // If the operands are constants, see if we can simplify them.
Chris Lattner676c78e2009-01-31 08:15:18 +00001050 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1051 ShrinkDemandedConstant(I, 2, DemandedMask))
1052 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
1054 // Only known if known in both the LHS and RHS.
1055 RHSKnownOne &= LHSKnownOne;
1056 RHSKnownZero &= LHSKnownZero;
1057 break;
1058 case Instruction::Trunc: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001059 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 DemandedMask.zext(truncBf);
1061 RHSKnownZero.zext(truncBf);
1062 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001063 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001065 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 DemandedMask.trunc(BitWidth);
1067 RHSKnownZero.trunc(BitWidth);
1068 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 break;
1071 }
1072 case Instruction::BitCast:
1073 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner676c78e2009-01-31 08:15:18 +00001074 return false; // vector->int or fp->int?
1075 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001077 return I;
1078 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 break;
1080 case Instruction::ZExt: {
1081 // Compute the bits in the result that are not present in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083
1084 DemandedMask.trunc(SrcBitWidth);
1085 RHSKnownZero.trunc(SrcBitWidth);
1086 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001087 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001089 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 DemandedMask.zext(BitWidth);
1091 RHSKnownZero.zext(BitWidth);
1092 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 // The top bits are known to be zero.
1095 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1096 break;
1097 }
1098 case Instruction::SExt: {
1099 // Compute the bits in the result that are not present in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001100 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101
1102 APInt InputDemandedBits = DemandedMask &
1103 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1104
1105 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1106 // If any of the sign extended bits are demanded, we know that the sign
1107 // bit is demanded.
1108 if ((NewBits & DemandedMask) != 0)
1109 InputDemandedBits.set(SrcBitWidth-1);
1110
1111 InputDemandedBits.trunc(SrcBitWidth);
1112 RHSKnownZero.trunc(SrcBitWidth);
1113 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001114 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001116 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 InputDemandedBits.zext(BitWidth);
1118 RHSKnownZero.zext(BitWidth);
1119 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001120 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121
1122 // If the sign bit of the input is known set or clear, then we know the
1123 // top bits of the result.
1124
1125 // If the input sign bit is known zero, or if the NewBits are not demanded
1126 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001127 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001129 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1130 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1132 RHSKnownOne |= NewBits;
1133 }
1134 break;
1135 }
1136 case Instruction::Add: {
1137 // Figure out what the input bits are. If the top bits of the and result
1138 // are not demanded, then the add doesn't demand them from its input
1139 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001140 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141
1142 // If there is a constant on the RHS, there are a variety of xformations
1143 // we can do.
1144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1145 // If null, this should be simplified elsewhere. Some of the xforms here
1146 // won't work if the RHS is zero.
1147 if (RHS->isZero())
1148 break;
1149
1150 // If the top bit of the output is demanded, demand everything from the
1151 // input. Otherwise, we demand all the input bits except NLZ top bits.
1152 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1153
1154 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001155 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001157 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158
1159 // If the RHS of the add has bits set that can't affect the input, reduce
1160 // the constant.
1161 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001162 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163
1164 // Avoid excess work.
1165 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1166 break;
1167
1168 // Turn it into OR if input bits are zero.
1169 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1170 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001171 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001173 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 }
1175
1176 // We can say something about the output known-zero and known-one bits,
1177 // depending on potential carries from the input constant and the
1178 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1179 // bits set and the RHS constant is 0x01001, then we know we have a known
1180 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1181
1182 // To compute this, we first compute the potential carry bits. These are
1183 // the bits which may be modified. I'm not aware of a better way to do
1184 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001185 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1187
1188 // Now that we know which bits have carries, compute the known-1/0 sets.
1189
1190 // Bits are known one if they are known zero in one operand and one in the
1191 // other, and there is no input carry.
1192 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1193 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1194
1195 // Bits are known zero if they are known zero in both operands and there
1196 // is no input carry.
1197 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1198 } else {
1199 // If the high-bits of this ADD are not demanded, then it does not demand
1200 // the high bits of its LHS or RHS.
1201 if (DemandedMask[BitWidth-1] == 0) {
1202 // Right fill the mask of bits for this ADD to demand the most
1203 // significant bit and all those below it.
1204 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001205 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1206 LHSKnownZero, LHSKnownOne, Depth+1) ||
1207 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001209 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 }
1211 }
1212 break;
1213 }
1214 case Instruction::Sub:
1215 // If the high-bits of this SUB are not demanded, then it does not demand
1216 // the high bits of its LHS or RHS.
1217 if (DemandedMask[BitWidth-1] == 0) {
1218 // Right fill the mask of bits for this SUB to demand the most
1219 // significant bit and all those below it.
1220 uint32_t NLZ = DemandedMask.countLeadingZeros();
1221 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001222 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1223 LHSKnownZero, LHSKnownOne, Depth+1) ||
1224 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001226 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001228 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1229 // the known zeros and ones.
1230 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 break;
1232 case Instruction::Shl:
1233 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1234 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1235 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001236 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001238 return I;
1239 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 RHSKnownZero <<= ShiftAmt;
1241 RHSKnownOne <<= ShiftAmt;
1242 // low bits known zero.
1243 if (ShiftAmt)
1244 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1245 }
1246 break;
1247 case Instruction::LShr:
1248 // For a logical shift right
1249 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1250 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1251
1252 // Unsigned shift right.
1253 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001256 return I;
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1259 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1260 if (ShiftAmt) {
1261 // Compute the new bits that are at the top now.
1262 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1263 RHSKnownZero |= HighBits; // high bits known zero.
1264 }
1265 }
1266 break;
1267 case Instruction::AShr:
1268 // If this is an arithmetic shift right and only the low-bit is set, we can
1269 // always convert this into a logical shr, even if the shift amount is
1270 // variable. The low bit of the shift cannot be an input sign bit unless
1271 // the shift amount is >= the size of the datatype, which is undefined.
1272 if (DemandedMask == 1) {
1273 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001274 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001276 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 }
1278
1279 // If the sign bit is the only bit demanded by this ashr, then there is no
1280 // need to do it, the shift doesn't change the high bit.
1281 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001282 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283
1284 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1285 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1286
1287 // Signed shift right.
1288 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1289 // If any of the "high bits" are demanded, we should set the sign bit as
1290 // demanded.
1291 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1292 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001293 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001295 return I;
1296 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 // Compute the new bits that are at the top now.
1298 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1299 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1300 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1301
1302 // Handle the sign bits.
1303 APInt SignBit(APInt::getSignBit(BitWidth));
1304 // Adjust to where it is now in the mask.
1305 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1306
1307 // If the input sign bit is known to be zero, or if none of the top bits
1308 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001309 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 (HighBits & ~DemandedMask) == HighBits) {
1311 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001312 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001314 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1316 RHSKnownOne |= HighBits;
1317 }
1318 }
1319 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001320 case Instruction::SRem:
1321 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001322 APInt RA = Rem->getValue().abs();
1323 if (RA.isPowerOf2()) {
Nick Lewycky245de422008-07-12 05:04:38 +00001324 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001325 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001326
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001327 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001328 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001329 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001330 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001331 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001332
1333 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1334 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001335
1336 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001337
Chris Lattner676c78e2009-01-31 08:15:18 +00001338 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001339 }
1340 }
1341 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001342 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001343 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1344 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001345 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1346 KnownZero2, KnownOne2, Depth+1) ||
1347 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001348 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001349 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001350
Chris Lattneree5417c2009-01-21 18:09:24 +00001351 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001352 Leaders = std::max(Leaders,
1353 KnownZero2.countLeadingOnes());
1354 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001355 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 }
Chris Lattner989ba312008-06-18 04:33:20 +00001357 case Instruction::Call:
1358 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1359 switch (II->getIntrinsicID()) {
1360 default: break;
1361 case Intrinsic::bswap: {
1362 // If the only bits demanded come from one byte of the bswap result,
1363 // just shift the input byte into position to eliminate the bswap.
1364 unsigned NLZ = DemandedMask.countLeadingZeros();
1365 unsigned NTZ = DemandedMask.countTrailingZeros();
1366
1367 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1368 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1369 // have 14 leading zeros, round to 8.
1370 NLZ &= ~7;
1371 NTZ &= ~7;
1372 // If we need exactly one byte, we can do this transformation.
1373 if (BitWidth-NLZ-NTZ == 8) {
1374 unsigned ResultBit = NTZ;
1375 unsigned InputBit = BitWidth-NTZ-8;
1376
1377 // Replace this with either a left or right shift to get the byte into
1378 // the right place.
1379 Instruction *NewVal;
1380 if (InputBit > ResultBit)
1381 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1382 ConstantInt::get(I->getType(), InputBit-ResultBit));
1383 else
1384 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1385 ConstantInt::get(I->getType(), ResultBit-InputBit));
1386 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001387 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001388 }
1389
1390 // TODO: Could compute known zero/one bits based on the input.
1391 break;
1392 }
1393 }
1394 }
Chris Lattner4946e222008-06-18 18:11:55 +00001395 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001396 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001397 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398
1399 // If the client is only demanding bits that we know, return the known
1400 // constant.
1401 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001402 return ConstantInt::get(RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 return false;
1404}
1405
1406
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001407/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001408/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409/// actually used by the caller. This method analyzes which elements of the
1410/// operand are undef and returns that information in UndefElts.
1411///
1412/// If the information about demanded elements can be used to simplify the
1413/// operation, the operation is simplified, then the resultant value is
1414/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001415Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1416 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 unsigned Depth) {
1418 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001419 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001420 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421
1422 if (isa<UndefValue>(V)) {
1423 // If the entire vector is undefined, just return this info.
1424 UndefElts = EltMask;
1425 return 0;
1426 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1427 UndefElts = EltMask;
1428 return UndefValue::get(V->getType());
1429 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001430
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 UndefElts = 0;
1432 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1433 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1434 Constant *Undef = UndefValue::get(EltTy);
1435
1436 std::vector<Constant*> Elts;
1437 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001438 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001440 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1442 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001443 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 } else { // Otherwise, defined.
1445 Elts.push_back(CP->getOperand(i));
1446 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 // If we changed the constant, return it.
1449 Constant *NewCP = ConstantVector::get(Elts);
1450 return NewCP != CP ? NewCP : 0;
1451 } else if (isa<ConstantAggregateZero>(V)) {
1452 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1453 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001454
1455 // Check if this is identity. If so, return 0 since we are not simplifying
1456 // anything.
1457 if (DemandedElts == ((1ULL << VWidth) -1))
1458 return 0;
1459
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1461 Constant *Zero = Constant::getNullValue(EltTy);
1462 Constant *Undef = UndefValue::get(EltTy);
1463 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001464 for (unsigned i = 0; i != VWidth; ++i) {
1465 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1466 Elts.push_back(Elt);
1467 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468 UndefElts = DemandedElts ^ EltMask;
1469 return ConstantVector::get(Elts);
1470 }
1471
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001472 // Limit search depth.
1473 if (Depth == 10)
1474 return false;
1475
1476 // If multiple users are using the root value, procede with
1477 // simplification conservatively assuming that all elements
1478 // are needed.
1479 if (!V->hasOneUse()) {
1480 // Quit if we find multiple users of a non-root value though.
1481 // They'll be handled when it's their turn to be visited by
1482 // the main instcombine process.
1483 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 // TODO: Just compute the UndefElts information recursively.
1485 return false;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001486
1487 // Conservatively assume that all elements are needed.
1488 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 }
1490
1491 Instruction *I = dyn_cast<Instruction>(V);
1492 if (!I) return false; // Only analyze instructions.
1493
1494 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001495 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 Value *TmpV;
1497 switch (I->getOpcode()) {
1498 default: break;
1499
1500 case Instruction::InsertElement: {
1501 // If this is a variable index, we don't know which element it overwrites.
1502 // demand exactly the same input as we produce.
1503 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1504 if (Idx == 0) {
1505 // Note that we can't propagate undef elt info, because we don't know
1506 // which elt is getting updated.
1507 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1508 UndefElts2, Depth+1);
1509 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1510 break;
1511 }
1512
1513 // If this is inserting an element that isn't demanded, remove this
1514 // insertelement.
1515 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001516 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 return AddSoonDeadInstToWorklist(*I, 0);
1518
1519 // Otherwise, the element inserted overwrites whatever was there, so the
1520 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001521 APInt DemandedElts2 = DemandedElts;
1522 DemandedElts2.clear(IdxNo);
1523 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 UndefElts, Depth+1);
1525 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1526
1527 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001528 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001529 break;
1530 }
1531 case Instruction::ShuffleVector: {
1532 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001533 uint64_t LHSVWidth =
1534 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001535 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001536 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001537 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001538 unsigned MaskVal = Shuffle->getMaskValue(i);
1539 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001540 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001541 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001542 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001543 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001544 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001545 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001546 }
1547 }
1548 }
1549
Nate Begemanb4d176f2009-02-11 22:36:25 +00001550 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001551 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001552 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001553 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554
Nate Begemanb4d176f2009-02-11 22:36:25 +00001555 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001556 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1557 UndefElts3, Depth+1);
1558 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1559
1560 bool NewUndefElts = false;
1561 for (unsigned i = 0; i < VWidth; i++) {
1562 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001563 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001564 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001565 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001566 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001567 NewUndefElts = true;
1568 UndefElts.set(i);
1569 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001570 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001571 if (UndefElts3[MaskVal - LHSVWidth]) {
1572 NewUndefElts = true;
1573 UndefElts.set(i);
1574 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575 }
1576 }
1577
1578 if (NewUndefElts) {
1579 // Add additional discovered undefs.
1580 std::vector<Constant*> Elts;
1581 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001582 if (UndefElts[i])
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001583 Elts.push_back(UndefValue::get(Type::Int32Ty));
1584 else
1585 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1586 Shuffle->getMaskValue(i)));
1587 }
1588 I->setOperand(2, ConstantVector::get(Elts));
1589 MadeChange = true;
1590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 break;
1592 }
1593 case Instruction::BitCast: {
1594 // Vector->vector casts only.
1595 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1596 if (!VTy) break;
1597 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001598 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 unsigned Ratio;
1600
1601 if (VWidth == InVWidth) {
1602 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1603 // elements as are demanded of us.
1604 Ratio = 1;
1605 InputDemandedElts = DemandedElts;
1606 } else if (VWidth > InVWidth) {
1607 // Untested so far.
1608 break;
1609
1610 // If there are more elements in the result than there are in the source,
1611 // then an input element is live if any of the corresponding output
1612 // elements are live.
1613 Ratio = VWidth/InVWidth;
1614 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001615 if (DemandedElts[OutIdx])
1616 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617 }
1618 } else {
1619 // Untested so far.
1620 break;
1621
1622 // If there are more elements in the source than there are in the result,
1623 // then an input element is live if the corresponding output element is
1624 // live.
1625 Ratio = InVWidth/VWidth;
1626 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001627 if (DemandedElts[InIdx/Ratio])
1628 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 }
1630
1631 // div/rem demand all inputs, because they don't want divide by zero.
1632 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1633 UndefElts2, Depth+1);
1634 if (TmpV) {
1635 I->setOperand(0, TmpV);
1636 MadeChange = true;
1637 }
1638
1639 UndefElts = UndefElts2;
1640 if (VWidth > InVWidth) {
1641 assert(0 && "Unimp");
1642 // If there are more elements in the result than there are in the source,
1643 // then an output element is undef if the corresponding input element is
1644 // undef.
1645 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001646 if (UndefElts2[OutIdx/Ratio])
1647 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 } else if (VWidth < InVWidth) {
1649 assert(0 && "Unimp");
1650 // If there are more elements in the source than there are in the result,
1651 // then a result element is undef if all of the corresponding input
1652 // elements are undef.
1653 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1654 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001655 if (!UndefElts2[InIdx]) // Not undef?
1656 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 }
1658 break;
1659 }
1660 case Instruction::And:
1661 case Instruction::Or:
1662 case Instruction::Xor:
1663 case Instruction::Add:
1664 case Instruction::Sub:
1665 case Instruction::Mul:
1666 // div/rem demand all inputs, because they don't want divide by zero.
1667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1668 UndefElts, Depth+1);
1669 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1671 UndefElts2, Depth+1);
1672 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1673
1674 // Output elements are undefined if both are undefined. Consider things
1675 // like undef&0. The result is known zero, not undef.
1676 UndefElts &= UndefElts2;
1677 break;
1678
1679 case Instruction::Call: {
1680 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1681 if (!II) break;
1682 switch (II->getIntrinsicID()) {
1683 default: break;
1684
1685 // Binary vector operations that work column-wise. A dest element is a
1686 // function of the corresponding input elements from the two inputs.
1687 case Intrinsic::x86_sse_sub_ss:
1688 case Intrinsic::x86_sse_mul_ss:
1689 case Intrinsic::x86_sse_min_ss:
1690 case Intrinsic::x86_sse_max_ss:
1691 case Intrinsic::x86_sse2_sub_sd:
1692 case Intrinsic::x86_sse2_mul_sd:
1693 case Intrinsic::x86_sse2_min_sd:
1694 case Intrinsic::x86_sse2_max_sd:
1695 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1696 UndefElts, Depth+1);
1697 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1698 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1699 UndefElts2, Depth+1);
1700 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1701
1702 // If only the low elt is demanded and this is a scalarizable intrinsic,
1703 // scalarize it now.
1704 if (DemandedElts == 1) {
1705 switch (II->getIntrinsicID()) {
1706 default: break;
1707 case Intrinsic::x86_sse_sub_ss:
1708 case Intrinsic::x86_sse_mul_ss:
1709 case Intrinsic::x86_sse2_sub_sd:
1710 case Intrinsic::x86_sse2_mul_sd:
1711 // TODO: Lower MIN/MAX/ABS/etc
1712 Value *LHS = II->getOperand(1);
1713 Value *RHS = II->getOperand(2);
1714 // Extract the element as scalars.
1715 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1716 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1717
1718 switch (II->getIntrinsicID()) {
1719 default: assert(0 && "Case stmts out of sync!");
1720 case Intrinsic::x86_sse_sub_ss:
1721 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001722 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 II->getName()), *II);
1724 break;
1725 case Intrinsic::x86_sse_mul_ss:
1726 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001727 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728 II->getName()), *II);
1729 break;
1730 }
1731
1732 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001733 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1734 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001735 InsertNewInstBefore(New, *II);
1736 AddSoonDeadInstToWorklist(*II, 0);
1737 return New;
1738 }
1739 }
1740
1741 // Output elements are undefined if both are undefined. Consider things
1742 // like undef&0. The result is known zero, not undef.
1743 UndefElts &= UndefElts2;
1744 break;
1745 }
1746 break;
1747 }
1748 }
1749 return MadeChange ? I : 0;
1750}
1751
Dan Gohman5d56fd42008-05-19 22:14:15 +00001752
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753/// AssociativeOpt - Perform an optimization on an associative operator. This
1754/// function is designed to check a chain of associative operators for a
1755/// potential to apply a certain optimization. Since the optimization may be
1756/// applicable if the expression was reassociated, this checks the chain, then
1757/// reassociates the expression as necessary to expose the optimization
1758/// opportunity. This makes use of a special Functor, which must define
1759/// 'shouldApply' and 'apply' methods.
1760///
1761template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001762static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763 unsigned Opcode = Root.getOpcode();
1764 Value *LHS = Root.getOperand(0);
1765
1766 // Quick check, see if the immediate LHS matches...
1767 if (F.shouldApply(LHS))
1768 return F.apply(Root);
1769
1770 // Otherwise, if the LHS is not of the same opcode as the root, return.
1771 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1772 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1773 // Should we apply this transform to the RHS?
1774 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1775
1776 // If not to the RHS, check to see if we should apply to the LHS...
1777 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1778 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1779 ShouldApply = true;
1780 }
1781
1782 // If the functor wants to apply the optimization to the RHS of LHSI,
1783 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1784 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 // Now all of the instructions are in the current basic block, go ahead
1786 // and perform the reassociation.
1787 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1788
1789 // First move the selected RHS to the LHS of the root...
1790 Root.setOperand(0, LHSI->getOperand(1));
1791
1792 // Make what used to be the LHS of the root be the user of the root...
1793 Value *ExtraOperand = TmpLHSI->getOperand(1);
1794 if (&Root == TmpLHSI) {
1795 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1796 return 0;
1797 }
1798 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1799 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001801 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 ARI = Root;
1803
1804 // Now propagate the ExtraOperand down the chain of instructions until we
1805 // get to LHSI.
1806 while (TmpLHSI != LHSI) {
1807 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1808 // Move the instruction to immediately before the chain we are
1809 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001810 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 ARI = NextLHSI;
1812
1813 Value *NextOp = NextLHSI->getOperand(1);
1814 NextLHSI->setOperand(1, ExtraOperand);
1815 TmpLHSI = NextLHSI;
1816 ExtraOperand = NextOp;
1817 }
1818
1819 // Now that the instructions are reassociated, have the functor perform
1820 // the transformation...
1821 return F.apply(Root);
1822 }
1823
1824 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1825 }
1826 return 0;
1827}
1828
Dan Gohman089efff2008-05-13 00:00:25 +00001829namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830
Nick Lewycky27f6c132008-05-23 04:34:58 +00001831// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832struct AddRHS {
1833 Value *RHS;
1834 AddRHS(Value *rhs) : RHS(rhs) {}
1835 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1836 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001837 return BinaryOperator::CreateShl(Add.getOperand(0),
1838 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001839 }
1840};
1841
1842// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1843// iff C1&C2 == 0
1844struct AddMaskingAnd {
1845 Constant *C2;
1846 AddMaskingAnd(Constant *c) : C2(c) {}
1847 bool shouldApply(Value *LHS) const {
1848 ConstantInt *C1;
1849 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1850 ConstantExpr::getAnd(C1, C2)->isNullValue();
1851 }
1852 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001853 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 }
1855};
1856
Dan Gohman089efff2008-05-13 00:00:25 +00001857}
1858
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1860 InstCombiner *IC) {
1861 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001862 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
1864
1865 // Figure out if the constant is the left or the right argument.
1866 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1867 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1868
1869 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1870 if (ConstIsRHS)
1871 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1872 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1873 }
1874
1875 Value *Op0 = SO, *Op1 = ConstOperand;
1876 if (!ConstIsRHS)
1877 std::swap(Op0, Op1);
1878 Instruction *New;
1879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001880 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001882 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 SO->getName()+".cmp");
1884 else {
1885 assert(0 && "Unknown binary instruction type!");
1886 abort();
1887 }
1888 return IC->InsertNewInstBefore(New, I);
1889}
1890
1891// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1892// constant as the other operand, try to fold the binary operator into the
1893// select arguments. This also works for Cast instructions, which obviously do
1894// not have a second operand.
1895static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1896 InstCombiner *IC) {
1897 // Don't modify shared select instructions
1898 if (!SI->hasOneUse()) return 0;
1899 Value *TV = SI->getOperand(1);
1900 Value *FV = SI->getOperand(2);
1901
1902 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1903 // Bool selects with constant operands can be folded to logical ops.
1904 if (SI->getType() == Type::Int1Ty) return 0;
1905
1906 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1907 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1908
Gabor Greifd6da1d02008-04-06 20:25:17 +00001909 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1910 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911 }
1912 return 0;
1913}
1914
1915
1916/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1917/// node as operand #0, see if we can fold the instruction into the PHI (which
1918/// is only possible if all operands to the PHI are constants).
1919Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1920 PHINode *PN = cast<PHINode>(I.getOperand(0));
1921 unsigned NumPHIValues = PN->getNumIncomingValues();
1922 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1923
1924 // Check to see if all of the operands of the PHI are constants. If there is
1925 // one non-constant value, remember the BB it is. If there is more than one
1926 // or if *it* is a PHI, bail out.
1927 BasicBlock *NonConstBB = 0;
1928 for (unsigned i = 0; i != NumPHIValues; ++i)
1929 if (!isa<Constant>(PN->getIncomingValue(i))) {
1930 if (NonConstBB) return 0; // More than one non-const value.
1931 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1932 NonConstBB = PN->getIncomingBlock(i);
1933
1934 // If the incoming non-constant value is in I's block, we have an infinite
1935 // loop.
1936 if (NonConstBB == I.getParent())
1937 return 0;
1938 }
1939
1940 // If there is exactly one non-constant value, we can insert a copy of the
1941 // operation in that block. However, if this is a critical edge, we would be
1942 // inserting the computation one some other paths (e.g. inside a loop). Only
1943 // do this if the pred block is unconditionally branching into the phi block.
1944 if (NonConstBB) {
1945 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1946 if (!BI || !BI->isUnconditional()) return 0;
1947 }
1948
1949 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001950 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1952 InsertNewInstBefore(NewPN, *PN);
1953 NewPN->takeName(PN);
1954
1955 // Next, add all of the operands to the PHI.
1956 if (I.getNumOperands() == 2) {
1957 Constant *C = cast<Constant>(I.getOperand(1));
1958 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001959 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1961 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1962 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1963 else
1964 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1965 } else {
1966 assert(PN->getIncomingBlock(i) == NonConstBB);
1967 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001968 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969 PN->getIncomingValue(i), C, "phitmp",
1970 NonConstBB->getTerminator());
1971 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001972 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001973 CI->getPredicate(),
1974 PN->getIncomingValue(i), C, "phitmp",
1975 NonConstBB->getTerminator());
1976 else
1977 assert(0 && "Unknown binop!");
1978
1979 AddToWorkList(cast<Instruction>(InV));
1980 }
1981 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1982 }
1983 } else {
1984 CastInst *CI = cast<CastInst>(&I);
1985 const Type *RetTy = CI->getType();
1986 for (unsigned i = 0; i != NumPHIValues; ++i) {
1987 Value *InV;
1988 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1989 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1990 } else {
1991 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001992 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993 I.getType(), "phitmp",
1994 NonConstBB->getTerminator());
1995 AddToWorkList(cast<Instruction>(InV));
1996 }
1997 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1998 }
1999 }
2000 return ReplaceInstUsesWith(I, NewPN);
2001}
2002
Chris Lattner55476162008-01-29 06:52:45 +00002003
Chris Lattner3554f972008-05-20 05:46:13 +00002004/// WillNotOverflowSignedAdd - Return true if we can prove that:
2005/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2006/// This basically requires proving that the add in the original type would not
2007/// overflow to change the sign bit or have a carry out.
2008bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2009 // There are different heuristics we can use for this. Here are some simple
2010 // ones.
2011
2012 // Add has the property that adding any two 2's complement numbers can only
2013 // have one carry bit which can change a sign. As such, if LHS and RHS each
2014 // have at least two sign bits, we know that the addition of the two values will
2015 // sign extend fine.
2016 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2017 return true;
2018
2019
2020 // If one of the operands only has one non-zero bit, and if the other operand
2021 // has a known-zero bit in a more significant place than it (not including the
2022 // sign bit) the ripple may go up to and fill the zero, but won't change the
2023 // sign. For example, (X & ~4) + 1.
2024
2025 // TODO: Implement.
2026
2027 return false;
2028}
2029
Chris Lattner55476162008-01-29 06:52:45 +00002030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002031Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2032 bool Changed = SimplifyCommutative(I);
2033 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2034
2035 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2036 // X + undef -> undef
2037 if (isa<UndefValue>(RHS))
2038 return ReplaceInstUsesWith(I, RHS);
2039
2040 // X + 0 --> X
2041 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2042 if (RHSC->isNullValue())
2043 return ReplaceInstUsesWith(I, LHS);
2044 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002045 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2046 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 return ReplaceInstUsesWith(I, LHS);
2048 }
2049
2050 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2051 // X + (signbit) --> X ^ signbit
2052 const APInt& Val = CI->getValue();
2053 uint32_t BitWidth = Val.getBitWidth();
2054 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002055 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056
2057 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2058 // (X & 254)+1 -> (X&254)|1
Chris Lattner676c78e2009-01-31 08:15:18 +00002059 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2060 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002061
2062 // zext(i1) - 1 -> select i1, 0, -1
2063 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2064 if (CI->isAllOnesValue() &&
2065 ZI->getOperand(0)->getType() == Type::Int1Ty)
2066 return SelectInst::Create(ZI->getOperand(0),
2067 Constant::getNullValue(I.getType()),
2068 ConstantInt::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069 }
2070
2071 if (isa<PHINode>(LHS))
2072 if (Instruction *NV = FoldOpIntoPhi(I))
2073 return NV;
2074
2075 ConstantInt *XorRHS = 0;
2076 Value *XorLHS = 0;
2077 if (isa<ConstantInt>(RHSC) &&
2078 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2079 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2080 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2081
2082 uint32_t Size = TySizeBits / 2;
2083 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2084 APInt CFF80Val(-C0080Val);
2085 do {
2086 if (TySizeBits > Size) {
2087 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2088 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2089 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2090 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2091 // This is a sign extend if the top bits are known zero.
2092 if (!MaskedValueIsZero(XorLHS,
2093 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2094 Size = 0; // Not a sign ext, but can't be any others either.
2095 break;
2096 }
2097 }
2098 Size >>= 1;
2099 C0080Val = APIntOps::lshr(C0080Val, Size);
2100 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2101 } while (Size >= 1);
2102
2103 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002104 // with funny bit widths then this switch statement should be removed. It
2105 // is just here to get the size of the "middle" type back up to something
2106 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 const Type *MiddleType = 0;
2108 switch (Size) {
2109 default: break;
2110 case 32: MiddleType = Type::Int32Ty; break;
2111 case 16: MiddleType = Type::Int16Ty; break;
2112 case 8: MiddleType = Type::Int8Ty; break;
2113 }
2114 if (MiddleType) {
2115 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2116 InsertNewInstBefore(NewTrunc, I);
2117 return new SExtInst(NewTrunc, I.getType(), I.getName());
2118 }
2119 }
2120 }
2121
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002122 if (I.getType() == Type::Int1Ty)
2123 return BinaryOperator::CreateXor(LHS, RHS);
2124
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002125 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002126 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2128
2129 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2130 if (RHSI->getOpcode() == Instruction::Sub)
2131 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2132 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2133 }
2134 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2135 if (LHSI->getOpcode() == Instruction::Sub)
2136 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2137 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2138 }
2139 }
2140
2141 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002142 // -A + -B --> -(A + B)
2143 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002144 if (LHS->getType()->isIntOrIntVector()) {
2145 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002146 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002147 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002148 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002149 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002150 }
2151
Gabor Greifa645dd32008-05-16 19:29:10 +00002152 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002153 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154
2155 // A + -B --> A - B
2156 if (!isa<Constant>(RHS))
2157 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002158 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159
2160
2161 ConstantInt *C2;
2162 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2163 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002164 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002165
2166 // X*C1 + X*C2 --> X * (C1+C2)
2167 ConstantInt *C1;
2168 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002169 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170 }
2171
2172 // X + X*C --> X * (C+1)
2173 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002174 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175
2176 // X + ~X --> -1 since ~X = -X-1
2177 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2178 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2179
2180
2181 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2182 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2183 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2184 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002185
2186 // A+B --> A|B iff A and B have no bits set in common.
2187 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2188 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2189 APInt LHSKnownOne(IT->getBitWidth(), 0);
2190 APInt LHSKnownZero(IT->getBitWidth(), 0);
2191 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2192 if (LHSKnownZero != 0) {
2193 APInt RHSKnownOne(IT->getBitWidth(), 0);
2194 APInt RHSKnownZero(IT->getBitWidth(), 0);
2195 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2196
2197 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002198 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002199 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002200 }
2201 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202
Nick Lewycky83598a72008-02-03 07:42:09 +00002203 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002204 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002205 Value *W, *X, *Y, *Z;
2206 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2207 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2208 if (W != Y) {
2209 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002210 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002211 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002212 std::swap(W, X);
2213 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002214 std::swap(Y, Z);
2215 std::swap(W, X);
2216 }
2217 }
2218
2219 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002220 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002221 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002222 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002223 }
2224 }
2225 }
2226
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2228 Value *X = 0;
2229 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002230 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231
2232 // (X & FF00) + xx00 -> (X+xx00) & FF00
2233 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2234 Constant *Anded = And(CRHS, C2);
2235 if (Anded == CRHS) {
2236 // See if all bits from the first bit set in the Add RHS up are included
2237 // in the mask. First, get the rightmost bit.
2238 const APInt& AddRHSV = CRHS->getValue();
2239
2240 // Form a mask of all bits from the lowest bit added through the top.
2241 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2242
2243 // See if the and mask includes all of these bits.
2244 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2245
2246 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2247 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002248 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002250 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002251 }
2252 }
2253 }
2254
2255 // Try to fold constant add into select arguments.
2256 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2258 return R;
2259 }
2260
2261 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002262 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 {
2264 CastInst *CI = dyn_cast<CastInst>(LHS);
2265 Value *Other = RHS;
2266 if (!CI) {
2267 CI = dyn_cast<CastInst>(RHS);
2268 Other = LHS;
2269 }
2270 if (CI && CI->getType()->isSized() &&
2271 (CI->getType()->getPrimitiveSizeInBits() ==
2272 TD->getIntPtrType()->getPrimitiveSizeInBits())
2273 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002274 unsigned AS =
2275 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002276 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2277 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002278 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 return new PtrToIntInst(I2, CI->getType());
2280 }
2281 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002282
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002283 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002284 {
2285 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002286 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002287 if (!SI) {
2288 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002289 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002290 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002291 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002292 Value *TV = SI->getTrueValue();
2293 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002294 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002295
2296 // Can we fold the add into the argument of the select?
2297 // We check both true and false select arguments for a matching subtract.
Chris Lattner641ea462008-11-16 04:46:19 +00002298 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2299 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002300 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner641ea462008-11-16 04:46:19 +00002301 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2302 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002303 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002304 }
2305 }
Chris Lattner55476162008-01-29 06:52:45 +00002306
2307 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2308 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2309 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2310 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311
Chris Lattner3554f972008-05-20 05:46:13 +00002312 // Check for (add (sext x), y), see if we can merge this into an
2313 // integer add followed by a sext.
2314 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2315 // (add (sext x), cst) --> (sext (add x, cst'))
2316 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2317 Constant *CI =
2318 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2319 if (LHSConv->hasOneUse() &&
2320 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2321 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2322 // Insert the new, smaller add.
2323 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2324 CI, "addconv");
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SExtInst(NewAdd, I.getType());
2327 }
2328 }
2329
2330 // (add (sext x), (sext y)) --> (sext (add int x, y))
2331 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2332 // Only do this if x/y have the same type, if at last one of them has a
2333 // single use (so we don't increase the number of sexts), and if the
2334 // integer add will not overflow.
2335 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2336 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2337 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2338 RHSConv->getOperand(0))) {
2339 // Insert the new integer add.
2340 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2341 RHSConv->getOperand(0),
2342 "addconv");
2343 InsertNewInstBefore(NewAdd, I);
2344 return new SExtInst(NewAdd, I.getType());
2345 }
2346 }
2347 }
2348
2349 // Check for (add double (sitofp x), y), see if we can merge this into an
2350 // integer add followed by a promotion.
2351 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2352 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2353 // ... if the constant fits in the integer value. This is useful for things
2354 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2355 // requires a constant pool load, and generally allows the add to be better
2356 // instcombined.
2357 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2358 Constant *CI =
2359 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2360 if (LHSConv->hasOneUse() &&
2361 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2362 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2363 // Insert the new integer add.
2364 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2365 CI, "addconv");
2366 InsertNewInstBefore(NewAdd, I);
2367 return new SIToFPInst(NewAdd, I.getType());
2368 }
2369 }
2370
2371 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2372 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2373 // Only do this if x/y have the same type, if at last one of them has a
2374 // single use (so we don't increase the number of int->fp conversions),
2375 // and if the integer add will not overflow.
2376 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2377 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2378 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2379 RHSConv->getOperand(0))) {
2380 // Insert the new integer add.
2381 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2382 RHSConv->getOperand(0),
2383 "addconv");
2384 InsertNewInstBefore(NewAdd, I);
2385 return new SIToFPInst(NewAdd, I.getType());
2386 }
2387 }
2388 }
2389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 return Changed ? &I : 0;
2391}
2392
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002393Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2394 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2395
Chris Lattner27fbef42008-07-17 06:07:20 +00002396 if (Op0 == Op1 && // sub X, X -> 0
2397 !I.getType()->isFPOrFPVector())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2399
2400 // If this is a 'B = x-(-A)', change to B = x+A...
2401 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002403
2404 if (isa<UndefValue>(Op0))
2405 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2406 if (isa<UndefValue>(Op1))
2407 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2408
2409 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2410 // Replace (-1 - A) with (~A)...
2411 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002412 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413
2414 // C - ~X == X + (1+C)
2415 Value *X = 0;
2416 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002417 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418
2419 // -(X >>u 31) -> (X >>s 31)
2420 // -(X >>s 31) -> (X >>u 31)
2421 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002422 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423 if (SI->getOpcode() == Instruction::LShr) {
2424 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2425 // Check to see if we are shifting out everything but the sign bit.
2426 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2427 SI->getType()->getPrimitiveSizeInBits()-1) {
2428 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002429 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002430 SI->getOperand(0), CU, SI->getName());
2431 }
2432 }
2433 }
2434 else if (SI->getOpcode() == Instruction::AShr) {
2435 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2436 // Check to see if we are shifting out everything but the sign bit.
2437 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2438 SI->getType()->getPrimitiveSizeInBits()-1) {
2439 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002440 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002441 SI->getOperand(0), CU, SI->getName());
2442 }
2443 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002444 }
2445 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002446 }
2447
2448 // Try to fold constant sub into select arguments.
2449 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2450 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2451 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 }
2453
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002454 if (I.getType() == Type::Int1Ty)
2455 return BinaryOperator::CreateXor(Op0, Op1);
2456
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2458 if (Op1I->getOpcode() == Instruction::Add &&
2459 !Op0->getType()->isFPOrFPVector()) {
2460 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002461 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002462 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002463 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002464 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2465 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2466 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002467 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002468 Op1I->getOperand(0));
2469 }
2470 }
2471
2472 if (Op1I->hasOneUse()) {
2473 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2474 // is not used by anyone else...
2475 //
2476 if (Op1I->getOpcode() == Instruction::Sub &&
2477 !Op1I->getType()->isFPOrFPVector()) {
2478 // Swap the two operands of the subexpr...
2479 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2480 Op1I->setOperand(0, IIOp1);
2481 Op1I->setOperand(1, IIOp0);
2482
2483 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002484 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 }
2486
2487 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2488 //
2489 if (Op1I->getOpcode() == Instruction::And &&
2490 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2491 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2492
2493 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002494 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2495 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496 }
2497
2498 // 0 - (X sdiv C) -> (X sdiv -C)
2499 if (Op1I->getOpcode() == Instruction::SDiv)
2500 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2501 if (CSI->isZero())
2502 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 ConstantExpr::getNeg(DivRHS));
2505
2506 // X - X*C --> X * (1-C)
2507 ConstantInt *C2 = 0;
2508 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2509 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002510 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511 }
2512 }
2513 }
2514
2515 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002516 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 if (Op0I->getOpcode() == Instruction::Add) {
2518 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2519 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2520 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2521 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2522 } else if (Op0I->getOpcode() == Instruction::Sub) {
2523 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527
2528 ConstantInt *C1;
2529 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2530 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002531 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532
2533 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2534 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002535 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 }
2537 return 0;
2538}
2539
2540/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2541/// comparison only checks the sign bit. If it only checks the sign bit, set
2542/// TrueIfSigned if the result of the comparison is true when the input value is
2543/// signed.
2544static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2545 bool &TrueIfSigned) {
2546 switch (pred) {
2547 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2548 TrueIfSigned = true;
2549 return RHS->isZero();
2550 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2551 TrueIfSigned = true;
2552 return RHS->isAllOnesValue();
2553 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2554 TrueIfSigned = false;
2555 return RHS->isAllOnesValue();
2556 case ICmpInst::ICMP_UGT:
2557 // True if LHS u> RHS and RHS == high-bit-mask - 1
2558 TrueIfSigned = true;
2559 return RHS->getValue() ==
2560 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2561 case ICmpInst::ICMP_UGE:
2562 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2563 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002564 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002565 default:
2566 return false;
2567 }
2568}
2569
2570Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2571 bool Changed = SimplifyCommutative(I);
2572 Value *Op0 = I.getOperand(0);
2573
2574 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2575 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2576
2577 // Simplify mul instructions with a constant RHS...
2578 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2579 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2580
2581 // ((X << C1)*C2) == (X * (C2 << C1))
2582 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2583 if (SI->getOpcode() == Instruction::Shl)
2584 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 ConstantExpr::getShl(CI, ShOp));
2587
2588 if (CI->isZero())
2589 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2590 if (CI->equalsInt(1)) // X * 1 == X
2591 return ReplaceInstUsesWith(I, Op0);
2592 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002593 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002594
2595 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2596 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002597 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 ConstantInt::get(Op0->getType(), Val.logBase2()));
2599 }
2600 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2601 if (Op1F->isNullValue())
2602 return ReplaceInstUsesWith(I, Op1);
2603
2604 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2605 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner6297fc72008-08-11 22:06:05 +00002606 if (Op1F->isExactlyValue(1.0))
2607 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2608 } else if (isa<VectorType>(Op1->getType())) {
2609 if (isa<ConstantAggregateZero>(Op1))
2610 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002611
2612 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2613 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2614 return BinaryOperator::CreateNeg(Op0, I.getName());
2615
2616 // As above, vector X*splat(1.0) -> X in all defined cases.
2617 if (Constant *Splat = Op1V->getSplatValue()) {
2618 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2619 if (F->isExactlyValue(1.0))
2620 return ReplaceInstUsesWith(I, Op0);
2621 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2622 if (CI->equalsInt(1))
2623 return ReplaceInstUsesWith(I, Op0);
2624 }
2625 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002626 }
2627
2628 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2629 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002630 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002632 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002633 Op1, "tmp");
2634 InsertNewInstBefore(Add, I);
2635 Value *C1C2 = ConstantExpr::getMul(Op1,
2636 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002637 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638
2639 }
2640
2641 // Try to fold constant mul into select arguments.
2642 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2643 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2644 return R;
2645
2646 if (isa<PHINode>(Op0))
2647 if (Instruction *NV = FoldOpIntoPhi(I))
2648 return NV;
2649 }
2650
2651 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2652 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002654
Nick Lewycky1c246402008-11-21 07:33:58 +00002655 // (X / Y) * Y = X - (X % Y)
2656 // (X / Y) * -Y = (X % Y) - X
2657 {
2658 Value *Op1 = I.getOperand(1);
2659 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2660 if (!BO ||
2661 (BO->getOpcode() != Instruction::UDiv &&
2662 BO->getOpcode() != Instruction::SDiv)) {
2663 Op1 = Op0;
2664 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2665 }
2666 Value *Neg = dyn_castNegVal(Op1);
2667 if (BO && BO->hasOneUse() &&
2668 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2669 (BO->getOpcode() == Instruction::UDiv ||
2670 BO->getOpcode() == Instruction::SDiv)) {
2671 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2672
2673 Instruction *Rem;
2674 if (BO->getOpcode() == Instruction::UDiv)
2675 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2676 else
2677 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2678
2679 InsertNewInstBefore(Rem, I);
2680 Rem->takeName(BO);
2681
2682 if (Op1BO == Op1)
2683 return BinaryOperator::CreateSub(Op0BO, Rem);
2684 else
2685 return BinaryOperator::CreateSub(Rem, Op0BO);
2686 }
2687 }
2688
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002689 if (I.getType() == Type::Int1Ty)
2690 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2691
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002692 // If one of the operands of the multiply is a cast from a boolean value, then
2693 // we know the bool is either zero or one, so this is a 'masking' multiply.
2694 // See if we can simplify things based on how the boolean was originally
2695 // formed.
2696 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002697 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2699 BoolCast = CI;
2700 if (!BoolCast)
2701 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2702 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2703 BoolCast = CI;
2704 if (BoolCast) {
2705 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2706 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2707 const Type *SCOpTy = SCIOp0->getType();
2708 bool TIS = false;
2709
2710 // If the icmp is true iff the sign bit of X is set, then convert this
2711 // multiply into a shift/and combination.
2712 if (isa<ConstantInt>(SCIOp1) &&
2713 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2714 TIS) {
2715 // Shift the X value right to turn it into "all signbits".
2716 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2717 SCOpTy->getPrimitiveSizeInBits()-1);
2718 Value *V =
2719 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002720 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 BoolCast->getOperand(0)->getName()+
2722 ".mask"), I);
2723
2724 // If the multiply type is not the same as the source type, sign extend
2725 // or truncate to the multiply type.
2726 if (I.getType() != V->getType()) {
2727 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2728 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2729 Instruction::CastOps opcode =
2730 (SrcBits == DstBits ? Instruction::BitCast :
2731 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2732 V = InsertCastBefore(opcode, V, I.getType(), I);
2733 }
2734
2735 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002736 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 }
2738 }
2739 }
2740
2741 return Changed ? &I : 0;
2742}
2743
Chris Lattner76972db2008-07-14 00:15:52 +00002744/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2745/// instruction.
2746bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2747 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2748
2749 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2750 int NonNullOperand = -1;
2751 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2752 if (ST->isNullValue())
2753 NonNullOperand = 2;
2754 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2755 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2756 if (ST->isNullValue())
2757 NonNullOperand = 1;
2758
2759 if (NonNullOperand == -1)
2760 return false;
2761
2762 Value *SelectCond = SI->getOperand(0);
2763
2764 // Change the div/rem to use 'Y' instead of the select.
2765 I.setOperand(1, SI->getOperand(NonNullOperand));
2766
2767 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2768 // problem. However, the select, or the condition of the select may have
2769 // multiple uses. Based on our knowledge that the operand must be non-zero,
2770 // propagate the known value for the select into other uses of it, and
2771 // propagate a known value of the condition into its other users.
2772
2773 // If the select and condition only have a single use, don't bother with this,
2774 // early exit.
2775 if (SI->use_empty() && SelectCond->hasOneUse())
2776 return true;
2777
2778 // Scan the current block backward, looking for other uses of SI.
2779 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2780
2781 while (BBI != BBFront) {
2782 --BBI;
2783 // If we found a call to a function, we can't assume it will return, so
2784 // information from below it cannot be propagated above it.
2785 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2786 break;
2787
2788 // Replace uses of the select or its condition with the known values.
2789 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2790 I != E; ++I) {
2791 if (*I == SI) {
2792 *I = SI->getOperand(NonNullOperand);
2793 AddToWorkList(BBI);
2794 } else if (*I == SelectCond) {
2795 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2796 ConstantInt::getFalse();
2797 AddToWorkList(BBI);
2798 }
2799 }
2800
2801 // If we past the instruction, quit looking for it.
2802 if (&*BBI == SI)
2803 SI = 0;
2804 if (&*BBI == SelectCond)
2805 SelectCond = 0;
2806
2807 // If we ran out of things to eliminate, break out of the loop.
2808 if (SelectCond == 0 && SI == 0)
2809 break;
2810
2811 }
2812 return true;
2813}
2814
2815
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002816/// This function implements the transforms on div instructions that work
2817/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2818/// used by the visitors to those instructions.
2819/// @brief Transforms common to all three div instructions
2820Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2822
Chris Lattner653ef3c2008-02-19 06:12:18 +00002823 // undef / X -> 0 for integer.
2824 // undef / X -> undef for FP (the undef could be a snan).
2825 if (isa<UndefValue>(Op0)) {
2826 if (Op0->getType()->isFPOrFPVector())
2827 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002829 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830
2831 // X / undef -> undef
2832 if (isa<UndefValue>(Op1))
2833 return ReplaceInstUsesWith(I, Op1);
2834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002835 return 0;
2836}
2837
2838/// This function implements the transforms common to both integer division
2839/// instructions (udiv and sdiv). It is called by the visitors to those integer
2840/// division instructions.
2841/// @brief Common integer divide transforms
2842Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2843 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2844
Chris Lattnercefb36c2008-05-16 02:59:42 +00002845 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002846 if (Op0 == Op1) {
2847 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2848 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2849 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2850 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2851 }
2852
2853 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2854 return ReplaceInstUsesWith(I, CI);
2855 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002856
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 if (Instruction *Common = commonDivTransforms(I))
2858 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002859
2860 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2861 // This does not apply for fdiv.
2862 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2863 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002864
2865 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2866 // div X, 1 == X
2867 if (RHS->equalsInt(1))
2868 return ReplaceInstUsesWith(I, Op0);
2869
2870 // (X / C1) / C2 -> X / (C1*C2)
2871 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2872 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2873 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002874 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2875 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2876 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002877 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002878 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 }
2880
2881 if (!RHS->isZero()) { // avoid X udiv 0
2882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2884 return R;
2885 if (isa<PHINode>(Op0))
2886 if (Instruction *NV = FoldOpIntoPhi(I))
2887 return NV;
2888 }
2889 }
2890
2891 // 0 / X == 0, we don't need to preserve faults!
2892 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2893 if (LHS->equalsInt(0))
2894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2895
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002896 // It can't be division by zero, hence it must be division by one.
2897 if (I.getType() == Type::Int1Ty)
2898 return ReplaceInstUsesWith(I, Op0);
2899
Nick Lewycky94418732008-11-27 20:21:08 +00002900 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2901 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2902 // div X, 1 == X
2903 if (X->isOne())
2904 return ReplaceInstUsesWith(I, Op0);
2905 }
2906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907 return 0;
2908}
2909
2910Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2911 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913 // Handle the integer div common cases
2914 if (Instruction *Common = commonIDivTransforms(I))
2915 return Common;
2916
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002918 // X udiv C^2 -> X >> C
2919 // Check to see if this is an unsigned division with an exact power of 2,
2920 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002922 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00002924
2925 // X udiv C, where C >= signbit
2926 if (C->getValue().isNegative()) {
2927 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2928 I);
2929 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2930 ConstantInt::get(I.getType(), 1));
2931 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932 }
2933
2934 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2935 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2936 if (RHSI->getOpcode() == Instruction::Shl &&
2937 isa<ConstantInt>(RHSI->getOperand(0))) {
2938 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2939 if (C1.isPowerOf2()) {
2940 Value *N = RHSI->getOperand(1);
2941 const Type *NTy = N->getType();
2942 if (uint32_t C2 = C1.logBase2()) {
2943 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002944 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002946 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 }
2948 }
2949 }
2950
2951 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2952 // where C1&C2 are powers of two.
2953 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2954 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2955 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2956 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2957 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2958 // Compute the shift amounts
2959 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2960 // Construct the "on true" case of the select
2961 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002962 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002963 Op0, TC, SI->getName()+".t");
2964 TSI = InsertNewInstBefore(TSI, I);
2965
2966 // Construct the "on false" case of the select
2967 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002968 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 Op0, FC, SI->getName()+".f");
2970 FSI = InsertNewInstBefore(FSI, I);
2971
2972 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002973 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974 }
2975 }
2976 return 0;
2977}
2978
2979Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2981
2982 // Handle the integer div common cases
2983 if (Instruction *Common = commonIDivTransforms(I))
2984 return Common;
2985
2986 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2987 // sdiv X, -1 == -X
2988 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002989 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002990 }
2991
2992 // If the sign bits of both operands are zero (i.e. we can prove they are
2993 // unsigned inputs), turn this into a udiv.
2994 if (I.getType()->isInteger()) {
2995 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2996 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002997 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002998 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999 }
3000 }
3001
3002 return 0;
3003}
3004
3005Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3006 return commonDivTransforms(I);
3007}
3008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009/// This function implements the transforms on rem instructions that work
3010/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3011/// is used by the visitors to those instructions.
3012/// @brief Transforms common to all three rem instructions
3013Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015
Chris Lattner653ef3c2008-02-19 06:12:18 +00003016 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3017 if (I.getType()->isFPOrFPVector())
3018 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 if (isa<UndefValue>(Op1))
3022 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3023
3024 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003025 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3026 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027
3028 return 0;
3029}
3030
3031/// This function implements the transforms common to both integer remainder
3032/// instructions (urem and srem). It is called by the visitors to those integer
3033/// remainder instructions.
3034/// @brief Common integer remainder transforms
3035Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3036 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3037
3038 if (Instruction *common = commonRemTransforms(I))
3039 return common;
3040
Dale Johannesena51f7372009-01-21 00:35:19 +00003041 // 0 % X == 0 for integer, we don't need to preserve faults!
3042 if (Constant *LHS = dyn_cast<Constant>(Op0))
3043 if (LHS->isNullValue())
3044 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3047 // X % 0 == undef, we don't need to preserve faults!
3048 if (RHS->equalsInt(0))
3049 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3050
3051 if (RHS->equalsInt(1)) // X % 1 == 0
3052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053
3054 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3057 return R;
3058 } else if (isa<PHINode>(Op0I)) {
3059 if (Instruction *NV = FoldOpIntoPhi(I))
3060 return NV;
3061 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003062
3063 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003064 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003065 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003066 }
3067 }
3068
3069 return 0;
3070}
3071
3072Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3073 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3074
3075 if (Instruction *common = commonIRemTransforms(I))
3076 return common;
3077
3078 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3079 // X urem C^2 -> X and C
3080 // Check to see if this is an unsigned remainder with an exact power of 2,
3081 // if so, convert to a bitwise and.
3082 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3083 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003084 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085 }
3086
3087 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3088 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3089 if (RHSI->getOpcode() == Instruction::Shl &&
3090 isa<ConstantInt>(RHSI->getOperand(0))) {
3091 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3092 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003093 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003094 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003095 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096 }
3097 }
3098 }
3099
3100 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3101 // where C1&C2 are powers of two.
3102 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3103 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3104 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3105 // STO == 0 and SFO == 0 handled above.
3106 if ((STO->getValue().isPowerOf2()) &&
3107 (SFO->getValue().isPowerOf2())) {
3108 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003109 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003111 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003112 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113 }
3114 }
3115 }
3116
3117 return 0;
3118}
3119
3120Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3122
Dan Gohmandb3dd962007-11-05 23:16:33 +00003123 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124 if (Instruction *common = commonIRemTransforms(I))
3125 return common;
3126
3127 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003128 if (!isa<Constant>(RHSNeg) ||
3129 (isa<ConstantInt>(RHSNeg) &&
3130 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131 // X % -Y -> X % Y
3132 AddUsesToWorkList(I);
3133 I.setOperand(1, RHSNeg);
3134 return &I;
3135 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003136
Dan Gohmandb3dd962007-11-05 23:16:33 +00003137 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003139 if (I.getType()->isInteger()) {
3140 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3141 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3142 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003143 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003144 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 }
3146
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003147 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003148 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3149 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003150
Nick Lewyckyfd746832008-12-20 16:48:00 +00003151 bool hasNegative = false;
3152 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3154 if (RHS->getValue().isNegative())
3155 hasNegative = true;
3156
3157 if (hasNegative) {
3158 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003159 for (unsigned i = 0; i != VWidth; ++i) {
3160 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3161 if (RHS->getValue().isNegative())
3162 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3163 else
3164 Elts[i] = RHS;
3165 }
3166 }
3167
3168 Constant *NewRHSV = ConstantVector::get(Elts);
3169 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003170 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003171 I.setOperand(1, NewRHSV);
3172 return &I;
3173 }
3174 }
3175 }
3176
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 return 0;
3178}
3179
3180Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3181 return commonRemTransforms(I);
3182}
3183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184// isOneBitSet - Return true if there is exactly one bit set in the specified
3185// constant.
3186static bool isOneBitSet(const ConstantInt *CI) {
3187 return CI->getValue().isPowerOf2();
3188}
3189
3190// isHighOnes - Return true if the constant is of the form 1+0+.
3191// This is the same as lowones(~X).
3192static bool isHighOnes(const ConstantInt *CI) {
3193 return (~CI->getValue() + 1).isPowerOf2();
3194}
3195
3196/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3197/// are carefully arranged to allow folding of expressions such as:
3198///
3199/// (A < B) | (A > B) --> (A != B)
3200///
3201/// Note that this is only valid if the first and second predicates have the
3202/// same sign. Is illegal to do: (A u< B) | (A s> B)
3203///
3204/// Three bits are used to represent the condition, as follows:
3205/// 0 A > B
3206/// 1 A == B
3207/// 2 A < B
3208///
3209/// <=> Value Definition
3210/// 000 0 Always false
3211/// 001 1 A > B
3212/// 010 2 A == B
3213/// 011 3 A >= B
3214/// 100 4 A < B
3215/// 101 5 A != B
3216/// 110 6 A <= B
3217/// 111 7 Always true
3218///
3219static unsigned getICmpCode(const ICmpInst *ICI) {
3220 switch (ICI->getPredicate()) {
3221 // False -> 0
3222 case ICmpInst::ICMP_UGT: return 1; // 001
3223 case ICmpInst::ICMP_SGT: return 1; // 001
3224 case ICmpInst::ICMP_EQ: return 2; // 010
3225 case ICmpInst::ICMP_UGE: return 3; // 011
3226 case ICmpInst::ICMP_SGE: return 3; // 011
3227 case ICmpInst::ICMP_ULT: return 4; // 100
3228 case ICmpInst::ICMP_SLT: return 4; // 100
3229 case ICmpInst::ICMP_NE: return 5; // 101
3230 case ICmpInst::ICMP_ULE: return 6; // 110
3231 case ICmpInst::ICMP_SLE: return 6; // 110
3232 // True -> 7
3233 default:
3234 assert(0 && "Invalid ICmp predicate!");
3235 return 0;
3236 }
3237}
3238
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003239/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3240/// predicate into a three bit mask. It also returns whether it is an ordered
3241/// predicate by reference.
3242static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3243 isOrdered = false;
3244 switch (CC) {
3245 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3246 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003247 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3248 case FCmpInst::FCMP_UGT: return 1; // 001
3249 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3250 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003251 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3252 case FCmpInst::FCMP_UGE: return 3; // 011
3253 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3254 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003255 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3256 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003257 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3258 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003259 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003260 default:
3261 // Not expecting FCMP_FALSE and FCMP_TRUE;
3262 assert(0 && "Unexpected FCmp predicate!");
3263 return 0;
3264 }
3265}
3266
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267/// getICmpValue - This is the complement of getICmpCode, which turns an
3268/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003269/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003270/// of predicate to use in the new icmp instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3272 switch (code) {
3273 default: assert(0 && "Illegal ICmp code!");
3274 case 0: return ConstantInt::getFalse();
3275 case 1:
3276 if (sign)
3277 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3278 else
3279 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3280 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3281 case 3:
3282 if (sign)
3283 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3284 else
3285 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3286 case 4:
3287 if (sign)
3288 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3289 else
3290 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3291 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3292 case 6:
3293 if (sign)
3294 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3295 else
3296 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3297 case 7: return ConstantInt::getTrue();
3298 }
3299}
3300
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003301/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3302/// opcode and two operands into either a FCmp instruction. isordered is passed
3303/// in to determine which kind of predicate to use in the new fcmp instruction.
3304static Value *getFCmpValue(bool isordered, unsigned code,
3305 Value *LHS, Value *RHS) {
3306 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003307 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003308 case 0:
3309 if (isordered)
3310 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3311 else
3312 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3313 case 1:
3314 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003315 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3316 else
3317 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003318 case 2:
3319 if (isordered)
3320 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3321 else
3322 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003323 case 3:
3324 if (isordered)
3325 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3326 else
3327 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3328 case 4:
3329 if (isordered)
3330 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3331 else
3332 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3333 case 5:
3334 if (isordered)
Evan Chengf1f2cea2008-10-14 18:13:38 +00003335 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3336 else
3337 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3338 case 6:
3339 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003340 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3341 else
3342 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng72988052008-10-14 18:44:08 +00003343 case 7: return ConstantInt::getTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003344 }
3345}
3346
Chris Lattner2972b822008-11-16 04:55:20 +00003347/// PredicatesFoldable - Return true if both predicates match sign or if at
3348/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3350 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003351 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3352 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353}
3354
3355namespace {
3356// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3357struct FoldICmpLogical {
3358 InstCombiner &IC;
3359 Value *LHS, *RHS;
3360 ICmpInst::Predicate pred;
3361 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3362 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3363 pred(ICI->getPredicate()) {}
3364 bool shouldApply(Value *V) const {
3365 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3366 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003367 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3368 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 return false;
3370 }
3371 Instruction *apply(Instruction &Log) const {
3372 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3373 if (ICI->getOperand(0) != LHS) {
3374 assert(ICI->getOperand(1) == LHS);
3375 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3376 }
3377
3378 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3379 unsigned LHSCode = getICmpCode(ICI);
3380 unsigned RHSCode = getICmpCode(RHSICI);
3381 unsigned Code;
3382 switch (Log.getOpcode()) {
3383 case Instruction::And: Code = LHSCode & RHSCode; break;
3384 case Instruction::Or: Code = LHSCode | RHSCode; break;
3385 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3386 default: assert(0 && "Illegal logical opcode!"); return 0;
3387 }
3388
3389 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3390 ICmpInst::isSignedPredicate(ICI->getPredicate());
3391
3392 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3393 if (Instruction *I = dyn_cast<Instruction>(RV))
3394 return I;
3395 // Otherwise, it's a constant boolean value...
3396 return IC.ReplaceInstUsesWith(Log, RV);
3397 }
3398};
3399} // end anonymous namespace
3400
3401// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3402// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3403// guaranteed to be a binary operator.
3404Instruction *InstCombiner::OptAndOp(Instruction *Op,
3405 ConstantInt *OpRHS,
3406 ConstantInt *AndRHS,
3407 BinaryOperator &TheAnd) {
3408 Value *X = Op->getOperand(0);
3409 Constant *Together = 0;
3410 if (!Op->isShift())
3411 Together = And(AndRHS, OpRHS);
3412
3413 switch (Op->getOpcode()) {
3414 case Instruction::Xor:
3415 if (Op->hasOneUse()) {
3416 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003417 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 InsertNewInstBefore(And, TheAnd);
3419 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003420 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 }
3422 break;
3423 case Instruction::Or:
3424 if (Together == AndRHS) // (X | C) & C --> C
3425 return ReplaceInstUsesWith(TheAnd, AndRHS);
3426
3427 if (Op->hasOneUse() && Together != OpRHS) {
3428 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003429 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003430 InsertNewInstBefore(Or, TheAnd);
3431 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003432 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433 }
3434 break;
3435 case Instruction::Add:
3436 if (Op->hasOneUse()) {
3437 // Adding a one to a single bit bit-field should be turned into an XOR
3438 // of the bit. First thing to check is to see if this AND is with a
3439 // single bit constant.
3440 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3441
3442 // If there is only one bit set...
3443 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3444 // Ok, at this point, we know that we are masking the result of the
3445 // ADD down to exactly one bit. If the constant we are adding has
3446 // no bits set below this bit, then we can eliminate the ADD.
3447 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3448
3449 // Check to see if any bits below the one bit set in AndRHSV are set.
3450 if ((AddRHS & (AndRHSV-1)) == 0) {
3451 // If not, the only thing that can effect the output of the AND is
3452 // the bit specified by AndRHSV. If that bit is set, the effect of
3453 // the XOR is to toggle the bit. If it is clear, then the ADD has
3454 // no effect.
3455 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3456 TheAnd.setOperand(0, X);
3457 return &TheAnd;
3458 } else {
3459 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003460 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 InsertNewInstBefore(NewAnd, TheAnd);
3462 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003463 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003464 }
3465 }
3466 }
3467 }
3468 break;
3469
3470 case Instruction::Shl: {
3471 // We know that the AND will not produce any of the bits shifted in, so if
3472 // the anded constant includes them, clear them now!
3473 //
3474 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3475 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3476 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3477 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3478
3479 if (CI->getValue() == ShlMask) {
3480 // Masking out bits that the shift already masks
3481 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3482 } else if (CI != AndRHS) { // Reducing bits set in and.
3483 TheAnd.setOperand(1, CI);
3484 return &TheAnd;
3485 }
3486 break;
3487 }
3488 case Instruction::LShr:
3489 {
3490 // We know that the AND will not produce any of the bits shifted in, so if
3491 // the anded constant includes them, clear them now! This only applies to
3492 // unsigned shifts, because a signed shr may bring in set bits!
3493 //
3494 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3495 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3496 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3497 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3498
3499 if (CI->getValue() == ShrMask) {
3500 // Masking out bits that the shift already masks.
3501 return ReplaceInstUsesWith(TheAnd, Op);
3502 } else if (CI != AndRHS) {
3503 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3504 return &TheAnd;
3505 }
3506 break;
3507 }
3508 case Instruction::AShr:
3509 // Signed shr.
3510 // See if this is shifting in some sign extension, then masking it out
3511 // with an and.
3512 if (Op->hasOneUse()) {
3513 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3514 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3515 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3516 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3517 if (C == AndRHS) { // Masking out bits shifted in.
3518 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3519 // Make the argument unsigned.
3520 Value *ShVal = Op->getOperand(0);
3521 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003522 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003524 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525 }
3526 }
3527 break;
3528 }
3529 return 0;
3530}
3531
3532
3533/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3534/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3535/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3536/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3537/// insert new instructions.
3538Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3539 bool isSigned, bool Inside,
3540 Instruction &IB) {
3541 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3542 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3543 "Lo is not <= Hi in range emission code!");
3544
3545 if (Inside) {
3546 if (Lo == Hi) // Trivially false.
3547 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3548
3549 // V >= Min && V < Hi --> V < Hi
3550 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3551 ICmpInst::Predicate pred = (isSigned ?
3552 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3553 return new ICmpInst(pred, V, Hi);
3554 }
3555
3556 // Emit V-Lo <u Hi-Lo
3557 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003558 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559 InsertNewInstBefore(Add, IB);
3560 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3561 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3562 }
3563
3564 if (Lo == Hi) // Trivially true.
3565 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3566
3567 // V < Min || V >= Hi -> V > Hi-1
3568 Hi = SubOne(cast<ConstantInt>(Hi));
3569 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3570 ICmpInst::Predicate pred = (isSigned ?
3571 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3572 return new ICmpInst(pred, V, Hi);
3573 }
3574
3575 // Emit V-Lo >u Hi-1-Lo
3576 // Note that Hi has already had one subtracted from it, above.
3577 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003578 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 InsertNewInstBefore(Add, IB);
3580 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3581 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3582}
3583
3584// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3585// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3586// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3587// not, since all 1s are not contiguous.
3588static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3589 const APInt& V = Val->getValue();
3590 uint32_t BitWidth = Val->getType()->getBitWidth();
3591 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3592
3593 // look for the first zero bit after the run of ones
3594 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3595 // look for the first non-zero bit
3596 ME = V.getActiveBits();
3597 return true;
3598}
3599
3600/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3601/// where isSub determines whether the operator is a sub. If we can fold one of
3602/// the following xforms:
3603///
3604/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3605/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3606/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3607///
3608/// return (A +/- B).
3609///
3610Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3611 ConstantInt *Mask, bool isSub,
3612 Instruction &I) {
3613 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3614 if (!LHSI || LHSI->getNumOperands() != 2 ||
3615 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3616
3617 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3618
3619 switch (LHSI->getOpcode()) {
3620 default: return 0;
3621 case Instruction::And:
3622 if (And(N, Mask) == Mask) {
3623 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3624 if ((Mask->getValue().countLeadingZeros() +
3625 Mask->getValue().countPopulation()) ==
3626 Mask->getValue().getBitWidth())
3627 break;
3628
3629 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3630 // part, we don't need any explicit masks to take them out of A. If that
3631 // is all N is, ignore it.
3632 uint32_t MB = 0, ME = 0;
3633 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3634 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3635 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3636 if (MaskedValueIsZero(RHS, Mask))
3637 break;
3638 }
3639 }
3640 return 0;
3641 case Instruction::Or:
3642 case Instruction::Xor:
3643 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3644 if ((Mask->getValue().countLeadingZeros() +
3645 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3646 && And(N, Mask)->isZero())
3647 break;
3648 return 0;
3649 }
3650
3651 Instruction *New;
3652 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003653 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003655 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656 return InsertNewInstBefore(New, I);
3657}
3658
Chris Lattner0631ea72008-11-16 05:06:21 +00003659/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3660Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3661 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003662 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003663 ConstantInt *LHSCst, *RHSCst;
3664 ICmpInst::Predicate LHSCC, RHSCC;
3665
Chris Lattnerf3803482008-11-16 05:10:52 +00003666 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner0631ea72008-11-16 05:06:21 +00003667 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerf3803482008-11-16 05:10:52 +00003668 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003669 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003670
3671 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3672 // where C is a power of 2
3673 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3674 LHSCst->getValue().isPowerOf2()) {
3675 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3676 InsertNewInstBefore(NewOr, I);
3677 return new ICmpInst(LHSCC, NewOr, LHSCst);
3678 }
3679
3680 // From here on, we only handle:
3681 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3682 if (Val != Val2) return 0;
3683
Chris Lattner0631ea72008-11-16 05:06:21 +00003684 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3685 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3686 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3687 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3688 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3689 return 0;
3690
3691 // We can't fold (ugt x, C) & (sgt x, C2).
3692 if (!PredicatesFoldable(LHSCC, RHSCC))
3693 return 0;
3694
3695 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003696 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003697 if (ICmpInst::isSignedPredicate(LHSCC) ||
3698 (ICmpInst::isEquality(LHSCC) &&
3699 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003700 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003701 else
Chris Lattner665298f2008-11-16 05:14:43 +00003702 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3703
3704 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003705 std::swap(LHS, RHS);
3706 std::swap(LHSCst, RHSCst);
3707 std::swap(LHSCC, RHSCC);
3708 }
3709
3710 // At this point, we know we have have two icmp instructions
3711 // comparing a value against two constants and and'ing the result
3712 // together. Because of the above check, we know that we only have
3713 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3714 // (from the FoldICmpLogical check above), that the two constants
3715 // are not equal and that the larger constant is on the RHS
3716 assert(LHSCst != RHSCst && "Compares not folded above?");
3717
3718 switch (LHSCC) {
3719 default: assert(0 && "Unknown integer condition code!");
3720 case ICmpInst::ICMP_EQ:
3721 switch (RHSCC) {
3722 default: assert(0 && "Unknown integer condition code!");
3723 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3724 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3725 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3726 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3727 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3728 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3729 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3730 return ReplaceInstUsesWith(I, LHS);
3731 }
3732 case ICmpInst::ICMP_NE:
3733 switch (RHSCC) {
3734 default: assert(0 && "Unknown integer condition code!");
3735 case ICmpInst::ICMP_ULT:
3736 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3737 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3738 break; // (X != 13 & X u< 15) -> no change
3739 case ICmpInst::ICMP_SLT:
3740 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3741 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3742 break; // (X != 13 & X s< 15) -> no change
3743 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3744 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3745 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3746 return ReplaceInstUsesWith(I, RHS);
3747 case ICmpInst::ICMP_NE:
3748 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3749 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3750 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3751 Val->getName()+".off");
3752 InsertNewInstBefore(Add, I);
3753 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3754 ConstantInt::get(Add->getType(), 1));
3755 }
3756 break; // (X != 13 & X != 15) -> no change
3757 }
3758 break;
3759 case ICmpInst::ICMP_ULT:
3760 switch (RHSCC) {
3761 default: assert(0 && "Unknown integer condition code!");
3762 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3763 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3764 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3765 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3766 break;
3767 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3768 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3769 return ReplaceInstUsesWith(I, LHS);
3770 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3771 break;
3772 }
3773 break;
3774 case ICmpInst::ICMP_SLT:
3775 switch (RHSCC) {
3776 default: assert(0 && "Unknown integer condition code!");
3777 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3778 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3779 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3780 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3781 break;
3782 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3783 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3784 return ReplaceInstUsesWith(I, LHS);
3785 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3786 break;
3787 }
3788 break;
3789 case ICmpInst::ICMP_UGT:
3790 switch (RHSCC) {
3791 default: assert(0 && "Unknown integer condition code!");
3792 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3793 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3794 return ReplaceInstUsesWith(I, RHS);
3795 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3796 break;
3797 case ICmpInst::ICMP_NE:
3798 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3799 return new ICmpInst(LHSCC, Val, RHSCst);
3800 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003801 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003802 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3803 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3804 break;
3805 }
3806 break;
3807 case ICmpInst::ICMP_SGT:
3808 switch (RHSCC) {
3809 default: assert(0 && "Unknown integer condition code!");
3810 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3811 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3812 return ReplaceInstUsesWith(I, RHS);
3813 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3814 break;
3815 case ICmpInst::ICMP_NE:
3816 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3817 return new ICmpInst(LHSCC, Val, RHSCst);
3818 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003819 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003820 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3821 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3822 break;
3823 }
3824 break;
3825 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003826
3827 return 0;
3828}
3829
3830
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3832 bool Changed = SimplifyCommutative(I);
3833 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3834
3835 if (isa<UndefValue>(Op1)) // X & undef -> 0
3836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3837
3838 // and X, X = X
3839 if (Op0 == Op1)
3840 return ReplaceInstUsesWith(I, Op1);
3841
3842 // See if we can simplify any instructions used by the instruction whose sole
3843 // purpose is to compute bits we don't care about.
3844 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00003845 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003846 return &I;
3847 } else {
3848 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3849 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3850 return ReplaceInstUsesWith(I, I.getOperand(0));
3851 } else if (isa<ConstantAggregateZero>(Op1)) {
3852 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3853 }
3854 }
3855
3856 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3857 const APInt& AndRHSMask = AndRHS->getValue();
3858 APInt NotAndRHS(~AndRHSMask);
3859
3860 // Optimize a variety of ((val OP C1) & C2) combinations...
3861 if (isa<BinaryOperator>(Op0)) {
3862 Instruction *Op0I = cast<Instruction>(Op0);
3863 Value *Op0LHS = Op0I->getOperand(0);
3864 Value *Op0RHS = Op0I->getOperand(1);
3865 switch (Op0I->getOpcode()) {
3866 case Instruction::Xor:
3867 case Instruction::Or:
3868 // If the mask is only needed on one incoming arm, push it up.
3869 if (Op0I->hasOneUse()) {
3870 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3871 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003872 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003873 Op0RHS->getName()+".masked");
3874 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003875 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003876 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3877 }
3878 if (!isa<Constant>(Op0RHS) &&
3879 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3880 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003881 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882 Op0LHS->getName()+".masked");
3883 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003884 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3886 }
3887 }
3888
3889 break;
3890 case Instruction::Add:
3891 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3892 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3893 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3894 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003895 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003896 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003897 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003898 break;
3899
3900 case Instruction::Sub:
3901 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3902 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3903 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3904 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003905 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003906
Nick Lewyckya349ba42008-07-10 05:51:40 +00003907 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3908 // has 1's for all bits that the subtraction with A might affect.
3909 if (Op0I->hasOneUse()) {
3910 uint32_t BitWidth = AndRHSMask.getBitWidth();
3911 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3912 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3913
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003914 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00003915 if (!(A && A->isZero()) && // avoid infinite recursion.
3916 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003917 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3918 InsertNewInstBefore(NewNeg, I);
3919 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3920 }
3921 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003923
3924 case Instruction::Shl:
3925 case Instruction::LShr:
3926 // (1 << x) & 1 --> zext(x == 0)
3927 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00003928 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003929 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3930 Constant::getNullValue(I.getType()));
3931 InsertNewInstBefore(NewICmp, I);
3932 return new ZExtInst(NewICmp, I.getType());
3933 }
3934 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003935 }
3936
3937 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3938 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3939 return Res;
3940 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3941 // If this is an integer truncation or change from signed-to-unsigned, and
3942 // if the source is an and/or with immediate, transform it. This
3943 // frequently occurs for bitfield accesses.
3944 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3945 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3946 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003947 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948 if (CastOp->getOpcode() == Instruction::And) {
3949 // Change: and (cast (and X, C1) to T), C2
3950 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3951 // This will fold the two constants together, which may allow
3952 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003953 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003954 CastOp->getOperand(0), I.getType(),
3955 CastOp->getName()+".shrunk");
3956 NewCast = InsertNewInstBefore(NewCast, I);
3957 // trunc_or_bitcast(C1)&C2
3958 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3959 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003960 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003961 } else if (CastOp->getOpcode() == Instruction::Or) {
3962 // Change: and (cast (or X, C1) to T), C2
3963 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3964 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3965 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3966 return ReplaceInstUsesWith(I, AndRHS);
3967 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003968 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003969 }
3970 }
3971
3972 // Try to fold constant and into select arguments.
3973 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3974 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3975 return R;
3976 if (isa<PHINode>(Op0))
3977 if (Instruction *NV = FoldOpIntoPhi(I))
3978 return NV;
3979 }
3980
3981 Value *Op0NotVal = dyn_castNotVal(Op0);
3982 Value *Op1NotVal = dyn_castNotVal(Op1);
3983
3984 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3986
3987 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3988 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003989 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990 I.getName()+".demorgan");
3991 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003992 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003993 }
3994
3995 {
3996 Value *A = 0, *B = 0, *C = 0, *D = 0;
3997 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3998 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3999 return ReplaceInstUsesWith(I, Op1);
4000
4001 // (A|B) & ~(A&B) -> A^B
4002 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4003 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004004 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004005 }
4006 }
4007
4008 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4009 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4010 return ReplaceInstUsesWith(I, Op0);
4011
4012 // ~(A&B) & (A|B) -> A^B
4013 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4014 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004015 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004016 }
4017 }
4018
4019 if (Op0->hasOneUse() &&
4020 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4021 if (A == Op1) { // (A^B)&A -> A&(A^B)
4022 I.swapOperands(); // Simplify below
4023 std::swap(Op0, Op1);
4024 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4025 cast<BinaryOperator>(Op0)->swapOperands();
4026 I.swapOperands(); // Simplify below
4027 std::swap(Op0, Op1);
4028 }
4029 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004031 if (Op1->hasOneUse() &&
4032 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4033 if (B == Op0) { // B&(A^B) -> B&(B^A)
4034 cast<BinaryOperator>(Op1)->swapOperands();
4035 std::swap(A, B);
4036 }
4037 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00004038 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004039 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004040 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004041 }
4042 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004043
4044 // (A&((~A)|B)) -> A&B
Chris Lattner9db479f2008-12-01 05:16:26 +00004045 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4046 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4047 return BinaryOperator::CreateAnd(A, Op1);
4048 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4049 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4050 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 }
4052
4053 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4054 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4055 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4056 return R;
4057
Chris Lattner0631ea72008-11-16 05:06:21 +00004058 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4059 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4060 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004061 }
4062
4063 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4064 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4065 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4066 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4067 const Type *SrcTy = Op0C->getOperand(0)->getType();
4068 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4069 // Only do this if the casts both really cause code to be generated.
4070 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4071 I.getType(), TD) &&
4072 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4073 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004074 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004075 Op1C->getOperand(0),
4076 I.getName());
4077 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004078 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004079 }
4080 }
4081
4082 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4083 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4084 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4085 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4086 SI0->getOperand(1) == SI1->getOperand(1) &&
4087 (SI0->hasOneUse() || SI1->hasOneUse())) {
4088 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004089 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 SI1->getOperand(0),
4091 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004092 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 SI1->getOperand(1));
4094 }
4095 }
4096
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004097 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004098 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4099 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4100 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004101 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4102 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004103 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4104 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4105 // If either of the constants are nans, then the whole thing returns
4106 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004107 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004108 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4109 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4110 RHS->getOperand(0));
4111 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004112 } else {
4113 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4114 FCmpInst::Predicate Op0CC, Op1CC;
4115 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4116 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004117 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4118 // Swap RHS operands to match LHS.
4119 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4120 std::swap(Op1LHS, Op1RHS);
4121 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004122 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4123 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4124 if (Op0CC == Op1CC)
4125 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4126 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4127 Op1CC == FCmpInst::FCMP_FALSE)
4128 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4129 else if (Op0CC == FCmpInst::FCMP_TRUE)
4130 return ReplaceInstUsesWith(I, Op1);
4131 else if (Op1CC == FCmpInst::FCMP_TRUE)
4132 return ReplaceInstUsesWith(I, Op0);
4133 bool Op0Ordered;
4134 bool Op1Ordered;
4135 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4136 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4137 if (Op1Pred == 0) {
4138 std::swap(Op0, Op1);
4139 std::swap(Op0Pred, Op1Pred);
4140 std::swap(Op0Ordered, Op1Ordered);
4141 }
4142 if (Op0Pred == 0) {
4143 // uno && ueq -> uno && (uno || eq) -> ueq
4144 // ord && olt -> ord && (ord && lt) -> olt
4145 if (Op0Ordered == Op1Ordered)
4146 return ReplaceInstUsesWith(I, Op1);
4147 // uno && oeq -> uno && (ord && eq) -> false
4148 // uno && ord -> false
4149 if (!Op0Ordered)
4150 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4151 // ord && ueq -> ord && (uno || eq) -> oeq
4152 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4153 Op0LHS, Op0RHS));
4154 }
4155 }
4156 }
4157 }
Chris Lattner91882432007-10-24 05:38:08 +00004158 }
4159 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004160
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161 return Changed ? &I : 0;
4162}
4163
Chris Lattner567f5112008-10-05 02:13:19 +00004164/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4165/// capable of providing pieces of a bswap. The subexpression provides pieces
4166/// of a bswap if it is proven that each of the non-zero bytes in the output of
4167/// the expression came from the corresponding "byte swapped" byte in some other
4168/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4169/// we know that the expression deposits the low byte of %X into the high byte
4170/// of the bswap result and that all other bytes are zero. This expression is
4171/// accepted, the high byte of ByteValues is set to X to indicate a correct
4172/// match.
4173///
4174/// This function returns true if the match was unsuccessful and false if so.
4175/// On entry to the function the "OverallLeftShift" is a signed integer value
4176/// indicating the number of bytes that the subexpression is later shifted. For
4177/// example, if the expression is later right shifted by 16 bits, the
4178/// OverallLeftShift value would be -2 on entry. This is used to specify which
4179/// byte of ByteValues is actually being set.
4180///
4181/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4182/// byte is masked to zero by a user. For example, in (X & 255), X will be
4183/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4184/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4185/// always in the local (OverallLeftShift) coordinate space.
4186///
4187static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4188 SmallVector<Value*, 8> &ByteValues) {
4189 if (Instruction *I = dyn_cast<Instruction>(V)) {
4190 // If this is an or instruction, it may be an inner node of the bswap.
4191 if (I->getOpcode() == Instruction::Or) {
4192 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4193 ByteValues) ||
4194 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4195 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004196 }
Chris Lattner567f5112008-10-05 02:13:19 +00004197
4198 // If this is a logical shift by a constant multiple of 8, recurse with
4199 // OverallLeftShift and ByteMask adjusted.
4200 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4201 unsigned ShAmt =
4202 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4203 // Ensure the shift amount is defined and of a byte value.
4204 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4205 return true;
4206
4207 unsigned ByteShift = ShAmt >> 3;
4208 if (I->getOpcode() == Instruction::Shl) {
4209 // X << 2 -> collect(X, +2)
4210 OverallLeftShift += ByteShift;
4211 ByteMask >>= ByteShift;
4212 } else {
4213 // X >>u 2 -> collect(X, -2)
4214 OverallLeftShift -= ByteShift;
4215 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004216 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004217 }
4218
4219 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4220 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4221
4222 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4223 ByteValues);
4224 }
4225
4226 // If this is a logical 'and' with a mask that clears bytes, clear the
4227 // corresponding bytes in ByteMask.
4228 if (I->getOpcode() == Instruction::And &&
4229 isa<ConstantInt>(I->getOperand(1))) {
4230 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4231 unsigned NumBytes = ByteValues.size();
4232 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4233 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4234
4235 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4236 // If this byte is masked out by a later operation, we don't care what
4237 // the and mask is.
4238 if ((ByteMask & (1 << i)) == 0)
4239 continue;
4240
4241 // If the AndMask is all zeros for this byte, clear the bit.
4242 APInt MaskB = AndMask & Byte;
4243 if (MaskB == 0) {
4244 ByteMask &= ~(1U << i);
4245 continue;
4246 }
4247
4248 // If the AndMask is not all ones for this byte, it's not a bytezap.
4249 if (MaskB != Byte)
4250 return true;
4251
4252 // Otherwise, this byte is kept.
4253 }
4254
4255 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4256 ByteValues);
4257 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004258 }
4259
Chris Lattner567f5112008-10-05 02:13:19 +00004260 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4261 // the input value to the bswap. Some observations: 1) if more than one byte
4262 // is demanded from this input, then it could not be successfully assembled
4263 // into a byteswap. At least one of the two bytes would not be aligned with
4264 // their ultimate destination.
4265 if (!isPowerOf2_32(ByteMask)) return true;
4266 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267
Chris Lattner567f5112008-10-05 02:13:19 +00004268 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4269 // is demanded, it needs to go into byte 0 of the result. This means that the
4270 // byte needs to be shifted until it lands in the right byte bucket. The
4271 // shift amount depends on the position: if the byte is coming from the high
4272 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4273 // low part, it must be shifted left.
4274 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4275 if (InputByteNo < ByteValues.size()/2) {
4276 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4277 return true;
4278 } else {
4279 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4280 return true;
4281 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004282
4283 // If the destination byte value is already defined, the values are or'd
4284 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004285 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004286 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004287 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004288 return false;
4289}
4290
4291/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4292/// If so, insert the new bswap intrinsic and return it.
4293Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4294 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004295 if (!ITy || ITy->getBitWidth() % 16 ||
4296 // ByteMask only allows up to 32-byte values.
4297 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4299
4300 /// ByteValues - For each byte of the result, we keep track of which value
4301 /// defines each byte.
4302 SmallVector<Value*, 8> ByteValues;
4303 ByteValues.resize(ITy->getBitWidth()/8);
4304
4305 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004306 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4307 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004308 return 0;
4309
4310 // Check to see if all of the bytes come from the same value.
4311 Value *V = ByteValues[0];
4312 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4313
4314 // Check to make sure that all of the bytes come from the same value.
4315 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4316 if (ByteValues[i] != V)
4317 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004318 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004319 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004320 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004321 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322}
4323
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004324/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4325/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4326/// we can simplify this expression to "cond ? C : D or B".
4327static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4328 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004329 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004330 Value *Cond = 0;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004331 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004332 return 0;
4333
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004334 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004335 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004336 return SelectInst::Create(Cond, C, B);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004337 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004338 return SelectInst::Create(Cond, C, B);
4339 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004340 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004341 return SelectInst::Create(Cond, C, D);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004342 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004343 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004344 return 0;
4345}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004346
Chris Lattner0c678e52008-11-16 05:20:07 +00004347/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4348Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4349 ICmpInst *LHS, ICmpInst *RHS) {
4350 Value *Val, *Val2;
4351 ConstantInt *LHSCst, *RHSCst;
4352 ICmpInst::Predicate LHSCC, RHSCC;
4353
4354 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4355 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4356 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4357 return 0;
4358
4359 // From here on, we only handle:
4360 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4361 if (Val != Val2) return 0;
4362
4363 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4364 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4365 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4366 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4367 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4368 return 0;
4369
4370 // We can't fold (ugt x, C) | (sgt x, C2).
4371 if (!PredicatesFoldable(LHSCC, RHSCC))
4372 return 0;
4373
4374 // Ensure that the larger constant is on the RHS.
4375 bool ShouldSwap;
4376 if (ICmpInst::isSignedPredicate(LHSCC) ||
4377 (ICmpInst::isEquality(LHSCC) &&
4378 ICmpInst::isSignedPredicate(RHSCC)))
4379 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4380 else
4381 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4382
4383 if (ShouldSwap) {
4384 std::swap(LHS, RHS);
4385 std::swap(LHSCst, RHSCst);
4386 std::swap(LHSCC, RHSCC);
4387 }
4388
4389 // At this point, we know we have have two icmp instructions
4390 // comparing a value against two constants and or'ing the result
4391 // together. Because of the above check, we know that we only have
4392 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4393 // FoldICmpLogical check above), that the two constants are not
4394 // equal.
4395 assert(LHSCst != RHSCst && "Compares not folded above?");
4396
4397 switch (LHSCC) {
4398 default: assert(0 && "Unknown integer condition code!");
4399 case ICmpInst::ICMP_EQ:
4400 switch (RHSCC) {
4401 default: assert(0 && "Unknown integer condition code!");
4402 case ICmpInst::ICMP_EQ:
4403 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4404 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4405 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4406 Val->getName()+".off");
4407 InsertNewInstBefore(Add, I);
4408 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4409 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4410 }
4411 break; // (X == 13 | X == 15) -> no change
4412 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4413 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4414 break;
4415 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4416 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4417 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4418 return ReplaceInstUsesWith(I, RHS);
4419 }
4420 break;
4421 case ICmpInst::ICMP_NE:
4422 switch (RHSCC) {
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4425 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4426 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4427 return ReplaceInstUsesWith(I, LHS);
4428 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4429 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4430 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432 }
4433 break;
4434 case ICmpInst::ICMP_ULT:
4435 switch (RHSCC) {
4436 default: assert(0 && "Unknown integer condition code!");
4437 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4438 break;
4439 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4440 // If RHSCst is [us]MAXINT, it is always false. Not handling
4441 // this can cause overflow.
4442 if (RHSCst->isMaxValue(false))
4443 return ReplaceInstUsesWith(I, LHS);
4444 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4445 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4446 break;
4447 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4448 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4449 return ReplaceInstUsesWith(I, RHS);
4450 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4451 break;
4452 }
4453 break;
4454 case ICmpInst::ICMP_SLT:
4455 switch (RHSCC) {
4456 default: assert(0 && "Unknown integer condition code!");
4457 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4458 break;
4459 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4460 // If RHSCst is [us]MAXINT, it is always false. Not handling
4461 // this can cause overflow.
4462 if (RHSCst->isMaxValue(true))
4463 return ReplaceInstUsesWith(I, LHS);
4464 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4465 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4466 break;
4467 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4468 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4469 return ReplaceInstUsesWith(I, RHS);
4470 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4471 break;
4472 }
4473 break;
4474 case ICmpInst::ICMP_UGT:
4475 switch (RHSCC) {
4476 default: assert(0 && "Unknown integer condition code!");
4477 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4478 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4479 return ReplaceInstUsesWith(I, LHS);
4480 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4481 break;
4482 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4483 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4484 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4485 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4486 break;
4487 }
4488 break;
4489 case ICmpInst::ICMP_SGT:
4490 switch (RHSCC) {
4491 default: assert(0 && "Unknown integer condition code!");
4492 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4493 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4494 return ReplaceInstUsesWith(I, LHS);
4495 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4496 break;
4497 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4498 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4499 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4500 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4501 break;
4502 }
4503 break;
4504 }
4505 return 0;
4506}
4507
Bill Wendlingdae376a2008-12-01 08:23:25 +00004508/// FoldOrWithConstants - This helper function folds:
4509///
Bill Wendling236a1192008-12-02 05:09:00 +00004510/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004511///
4512/// into:
4513///
Bill Wendling236a1192008-12-02 05:09:00 +00004514/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004515///
Bill Wendling236a1192008-12-02 05:09:00 +00004516/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004517Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004518 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004519 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4520 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004521
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004522 Value *V1 = 0;
4523 ConstantInt *CI2 = 0;
4524 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004525
Bill Wendling86ee3162008-12-02 06:18:11 +00004526 APInt Xor = CI1->getValue() ^ CI2->getValue();
4527 if (!Xor.isAllOnesValue()) return 0;
4528
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004529 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004530 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004531 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4532 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004533 }
4534
4535 return 0;
4536}
4537
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004538Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4539 bool Changed = SimplifyCommutative(I);
4540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4541
4542 if (isa<UndefValue>(Op1)) // X | undef -> -1
4543 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4544
4545 // or X, X = X
4546 if (Op0 == Op1)
4547 return ReplaceInstUsesWith(I, Op0);
4548
4549 // See if we can simplify any instructions used by the instruction whose sole
4550 // purpose is to compute bits we don't care about.
4551 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00004552 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004553 return &I;
4554 } else if (isa<ConstantAggregateZero>(Op1)) {
4555 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4556 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4557 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4558 return ReplaceInstUsesWith(I, I.getOperand(1));
4559 }
4560
4561
4562
4563 // or X, -1 == -1
4564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4565 ConstantInt *C1 = 0; Value *X = 0;
4566 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4567 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004568 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004569 InsertNewInstBefore(Or, I);
4570 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004571 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004572 ConstantInt::get(RHS->getValue() | C1->getValue()));
4573 }
4574
4575 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4576 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004577 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 InsertNewInstBefore(Or, I);
4579 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004580 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004581 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4582 }
4583
4584 // Try to fold constant and into select arguments.
4585 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4586 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4587 return R;
4588 if (isa<PHINode>(Op0))
4589 if (Instruction *NV = FoldOpIntoPhi(I))
4590 return NV;
4591 }
4592
4593 Value *A = 0, *B = 0;
4594 ConstantInt *C1 = 0, *C2 = 0;
4595
4596 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4597 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4598 return ReplaceInstUsesWith(I, Op1);
4599 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4600 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4601 return ReplaceInstUsesWith(I, Op0);
4602
4603 // (A | B) | C and A | (B | C) -> bswap if possible.
4604 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4605 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4606 match(Op1, m_Or(m_Value(), m_Value())) ||
4607 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4608 match(Op1, m_Shift(m_Value(), m_Value())))) {
4609 if (Instruction *BSwap = MatchBSwap(I))
4610 return BSwap;
4611 }
4612
4613 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4614 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4615 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004616 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004617 InsertNewInstBefore(NOr, I);
4618 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004619 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004620 }
4621
4622 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4623 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4624 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004625 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004626 InsertNewInstBefore(NOr, I);
4627 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004628 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004629 }
4630
4631 // (A & C)|(B & D)
4632 Value *C = 0, *D = 0;
4633 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4634 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4635 Value *V1 = 0, *V2 = 0, *V3 = 0;
4636 C1 = dyn_cast<ConstantInt>(C);
4637 C2 = dyn_cast<ConstantInt>(D);
4638 if (C1 && C2) { // (A & C1)|(B & C2)
4639 // If we have: ((V + N) & C1) | (V & C2)
4640 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4641 // replace with V+N.
4642 if (C1->getValue() == ~C2->getValue()) {
4643 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4644 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4645 // Add commutes, try both ways.
4646 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4647 return ReplaceInstUsesWith(I, A);
4648 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4649 return ReplaceInstUsesWith(I, A);
4650 }
4651 // Or commutes, try both ways.
4652 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4653 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4654 // Add commutes, try both ways.
4655 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4656 return ReplaceInstUsesWith(I, B);
4657 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4658 return ReplaceInstUsesWith(I, B);
4659 }
4660 }
4661 V1 = 0; V2 = 0; V3 = 0;
4662 }
4663
4664 // Check to see if we have any common things being and'ed. If so, find the
4665 // terms for V1 & (V2|V3).
4666 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4667 if (A == B) // (A & C)|(A & D) == A & (C|D)
4668 V1 = A, V2 = C, V3 = D;
4669 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4670 V1 = A, V2 = B, V3 = C;
4671 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4672 V1 = C, V2 = A, V3 = D;
4673 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4674 V1 = C, V2 = A, V3 = B;
4675
4676 if (V1) {
4677 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004678 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4679 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004681 }
Dan Gohman279952c2008-10-28 22:38:57 +00004682
Dan Gohman35b76162008-10-30 20:40:10 +00004683 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004684 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4685 return Match;
4686 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4687 return Match;
4688 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4689 return Match;
4690 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4691 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004692
Bill Wendling22ca8352008-11-30 13:52:49 +00004693 // ((A&~B)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004694 if ((match(C, m_Not(m_Specific(D))) &&
4695 match(B, m_Not(m_Specific(A)))))
4696 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004697 // ((~B&A)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004698 if ((match(A, m_Not(m_Specific(D))) &&
4699 match(B, m_Not(m_Specific(C)))))
4700 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004701 // ((A&~B)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004702 if ((match(C, m_Not(m_Specific(B))) &&
4703 match(D, m_Not(m_Specific(A)))))
4704 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004705 // ((~B&A)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004706 if ((match(A, m_Not(m_Specific(B))) &&
4707 match(D, m_Not(m_Specific(C)))))
4708 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 }
4710
4711 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4712 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4713 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4714 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4715 SI0->getOperand(1) == SI1->getOperand(1) &&
4716 (SI0->hasOneUse() || SI1->hasOneUse())) {
4717 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004718 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004719 SI1->getOperand(0),
4720 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004721 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004722 SI1->getOperand(1));
4723 }
4724 }
4725
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004726 // ((A|B)&1)|(B&-2) -> (A&1) | B
4727 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4728 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004729 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004730 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004731 }
4732 // (B&-2)|((A|B)&1) -> (A&1) | B
4733 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4734 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004735 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004736 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004737 }
4738
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004739 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4740 if (A == Op1) // ~A | A == -1
4741 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4742 } else {
4743 A = 0;
4744 }
4745 // Note, A is still live here!
4746 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4747 if (Op0 == B)
4748 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4749
4750 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4751 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004752 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004753 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004754 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004755 }
4756 }
4757
4758 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4759 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4760 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4761 return R;
4762
Chris Lattner0c678e52008-11-16 05:20:07 +00004763 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4764 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4765 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 }
4767
4768 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004769 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004770 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4771 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004772 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4773 !isa<ICmpInst>(Op1C->getOperand(0))) {
4774 const Type *SrcTy = Op0C->getOperand(0)->getType();
4775 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4776 // Only do this if the casts both really cause code to be
4777 // generated.
4778 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4779 I.getType(), TD) &&
4780 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4781 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004782 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004783 Op1C->getOperand(0),
4784 I.getName());
4785 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004786 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004787 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004788 }
4789 }
Chris Lattner91882432007-10-24 05:38:08 +00004790 }
4791
4792
4793 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4794 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4795 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4796 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004797 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004798 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004799 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4800 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4801 // If either of the constants are nans, then the whole thing returns
4802 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004803 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004804 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4805
4806 // Otherwise, no need to compare the two constants, compare the
4807 // rest.
4808 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4809 RHS->getOperand(0));
4810 }
Evan Cheng72988052008-10-14 18:44:08 +00004811 } else {
4812 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4813 FCmpInst::Predicate Op0CC, Op1CC;
4814 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4815 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4816 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4817 // Swap RHS operands to match LHS.
4818 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4819 std::swap(Op1LHS, Op1RHS);
4820 }
4821 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4822 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4823 if (Op0CC == Op1CC)
4824 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4825 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4826 Op1CC == FCmpInst::FCMP_TRUE)
4827 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4828 else if (Op0CC == FCmpInst::FCMP_FALSE)
4829 return ReplaceInstUsesWith(I, Op1);
4830 else if (Op1CC == FCmpInst::FCMP_FALSE)
4831 return ReplaceInstUsesWith(I, Op0);
4832 bool Op0Ordered;
4833 bool Op1Ordered;
4834 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4835 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4836 if (Op0Ordered == Op1Ordered) {
4837 // If both are ordered or unordered, return a new fcmp with
4838 // or'ed predicates.
4839 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4840 Op0LHS, Op0RHS);
4841 if (Instruction *I = dyn_cast<Instruction>(RV))
4842 return I;
4843 // Otherwise, it's a constant boolean value...
4844 return ReplaceInstUsesWith(I, RV);
4845 }
4846 }
4847 }
4848 }
Chris Lattner91882432007-10-24 05:38:08 +00004849 }
4850 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004851
4852 return Changed ? &I : 0;
4853}
4854
Dan Gohman089efff2008-05-13 00:00:25 +00004855namespace {
4856
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004857// XorSelf - Implements: X ^ X --> 0
4858struct XorSelf {
4859 Value *RHS;
4860 XorSelf(Value *rhs) : RHS(rhs) {}
4861 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4862 Instruction *apply(BinaryOperator &Xor) const {
4863 return &Xor;
4864 }
4865};
4866
Dan Gohman089efff2008-05-13 00:00:25 +00004867}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004868
4869Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4870 bool Changed = SimplifyCommutative(I);
4871 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4872
Evan Chenge5cd8032008-03-25 20:07:13 +00004873 if (isa<UndefValue>(Op1)) {
4874 if (isa<UndefValue>(Op0))
4875 // Handle undef ^ undef -> 0 special case. This is a common
4876 // idiom (misuse).
4877 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004878 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004879 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004880
4881 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4882 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004883 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004884 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4885 }
4886
4887 // See if we can simplify any instructions used by the instruction whose sole
4888 // purpose is to compute bits we don't care about.
4889 if (!isa<VectorType>(I.getType())) {
Chris Lattner676c78e2009-01-31 08:15:18 +00004890 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004891 return &I;
4892 } else if (isa<ConstantAggregateZero>(Op1)) {
4893 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4894 }
4895
4896 // Is this a ~ operation?
4897 if (Value *NotOp = dyn_castNotVal(&I)) {
4898 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4899 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4900 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4901 if (Op0I->getOpcode() == Instruction::And ||
4902 Op0I->getOpcode() == Instruction::Or) {
4903 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4904 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4905 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004906 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004907 Op0I->getOperand(1)->getName()+".not");
4908 InsertNewInstBefore(NotY, I);
4909 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004910 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004911 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004912 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004913 }
4914 }
4915 }
4916 }
4917
4918
4919 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004920 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00004921 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00004922 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004923 return new ICmpInst(ICI->getInversePredicate(),
4924 ICI->getOperand(0), ICI->getOperand(1));
4925
Nick Lewycky1405e922007-08-06 20:04:16 +00004926 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4927 return new FCmpInst(FCI->getInversePredicate(),
4928 FCI->getOperand(0), FCI->getOperand(1));
4929 }
4930
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004931 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4932 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4933 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4934 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4935 Instruction::CastOps Opcode = Op0C->getOpcode();
4936 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4937 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4938 Op0C->getDestTy())) {
4939 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4940 CI->getOpcode(), CI->getInversePredicate(),
4941 CI->getOperand(0), CI->getOperand(1)), I);
4942 NewCI->takeName(CI);
4943 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4944 }
4945 }
4946 }
4947 }
4948 }
4949
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004950 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4951 // ~(c-X) == X-c-1 == X+(-c-1)
4952 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4953 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4954 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4955 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4956 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004957 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004958 }
4959
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004960 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004961 if (Op0I->getOpcode() == Instruction::Add) {
4962 // ~(X-c) --> (-c-1)-X
4963 if (RHS->isAllOnesValue()) {
4964 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004965 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004966 ConstantExpr::getSub(NegOp0CI,
4967 ConstantInt::get(I.getType(), 1)),
4968 Op0I->getOperand(0));
4969 } else if (RHS->getValue().isSignBit()) {
4970 // (X + C) ^ signbit -> (X + C + signbit)
4971 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004972 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004973
4974 }
4975 } else if (Op0I->getOpcode() == Instruction::Or) {
4976 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4977 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4978 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4979 // Anything in both C1 and C2 is known to be zero, remove it from
4980 // NewRHS.
4981 Constant *CommonBits = And(Op0CI, RHS);
4982 NewRHS = ConstantExpr::getAnd(NewRHS,
4983 ConstantExpr::getNot(CommonBits));
4984 AddToWorkList(Op0I);
4985 I.setOperand(0, Op0I->getOperand(0));
4986 I.setOperand(1, NewRHS);
4987 return &I;
4988 }
4989 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004990 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004991 }
4992
4993 // Try to fold constant and into select arguments.
4994 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4995 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4996 return R;
4997 if (isa<PHINode>(Op0))
4998 if (Instruction *NV = FoldOpIntoPhi(I))
4999 return NV;
5000 }
5001
5002 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5003 if (X == Op1)
5004 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5005
5006 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5007 if (X == Op0)
5008 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5009
5010
5011 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5012 if (Op1I) {
5013 Value *A, *B;
5014 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5015 if (A == Op0) { // B^(B|A) == (A|B)^B
5016 Op1I->swapOperands();
5017 I.swapOperands();
5018 std::swap(Op0, Op1);
5019 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5020 I.swapOperands(); // Simplified below.
5021 std::swap(Op0, Op1);
5022 }
Chris Lattner3b874082008-11-16 05:38:51 +00005023 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5024 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5025 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5026 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005027 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5028 if (A == Op0) { // A^(A&B) -> A^(B&A)
5029 Op1I->swapOperands();
5030 std::swap(A, B);
5031 }
5032 if (B == Op0) { // A^(B&A) -> (B&A)^A
5033 I.swapOperands(); // Simplified below.
5034 std::swap(Op0, Op1);
5035 }
5036 }
5037 }
5038
5039 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5040 if (Op0I) {
5041 Value *A, *B;
5042 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5043 if (A == Op1) // (B|A)^B == (A|B)^B
5044 std::swap(A, B);
5045 if (B == Op1) { // (A|B)^B == A & ~B
5046 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005047 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5048 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 }
Chris Lattner3b874082008-11-16 05:38:51 +00005050 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5051 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5052 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5053 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005054 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5055 if (A == Op1) // (A&B)^A -> (B&A)^A
5056 std::swap(A, B);
5057 if (B == Op1 && // (B&A)^A == ~B & A
5058 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5059 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005060 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5061 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005062 }
5063 }
5064 }
5065
5066 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5067 if (Op0I && Op1I && Op0I->isShift() &&
5068 Op0I->getOpcode() == Op1I->getOpcode() &&
5069 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5070 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5071 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005072 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 Op1I->getOperand(0),
5074 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005075 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005076 Op1I->getOperand(1));
5077 }
5078
5079 if (Op0I && Op1I) {
5080 Value *A, *B, *C, *D;
5081 // (A & B)^(A | B) -> A ^ B
5082 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5083 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5084 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005085 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005086 }
5087 // (A | B)^(A & B) -> A ^ B
5088 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5089 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5090 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005091 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005092 }
5093
5094 // (A & B)^(C & D)
5095 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5096 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5097 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5098 // (X & Y)^(X & Y) -> (Y^Z) & X
5099 Value *X = 0, *Y = 0, *Z = 0;
5100 if (A == C)
5101 X = A, Y = B, Z = D;
5102 else if (A == D)
5103 X = A, Y = B, Z = C;
5104 else if (B == C)
5105 X = B, Y = A, Z = D;
5106 else if (B == D)
5107 X = B, Y = A, Z = C;
5108
5109 if (X) {
5110 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005111 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5112 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005113 }
5114 }
5115 }
5116
5117 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5118 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5119 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5120 return R;
5121
5122 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005123 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005124 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5125 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5126 const Type *SrcTy = Op0C->getOperand(0)->getType();
5127 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5128 // Only do this if the casts both really cause code to be generated.
5129 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5130 I.getType(), TD) &&
5131 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5132 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005133 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 Op1C->getOperand(0),
5135 I.getName());
5136 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005137 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005138 }
5139 }
Chris Lattner91882432007-10-24 05:38:08 +00005140 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005141
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005142 return Changed ? &I : 0;
5143}
5144
5145/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5146/// overflowed for this type.
5147static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5148 ConstantInt *In2, bool IsSigned = false) {
5149 Result = cast<ConstantInt>(Add(In1, In2));
5150
5151 if (IsSigned)
5152 if (In2->getValue().isNegative())
5153 return Result->getValue().sgt(In1->getValue());
5154 else
5155 return Result->getValue().slt(In1->getValue());
5156 else
5157 return Result->getValue().ult(In1->getValue());
5158}
5159
Dan Gohmanb80d5612008-09-10 23:30:57 +00005160/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5161/// overflowed for this type.
5162static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5163 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman2c3b4892008-09-11 18:53:02 +00005164 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanb80d5612008-09-10 23:30:57 +00005165
5166 if (IsSigned)
5167 if (In2->getValue().isNegative())
5168 return Result->getValue().slt(In1->getValue());
5169 else
5170 return Result->getValue().sgt(In1->getValue());
5171 else
5172 return Result->getValue().ugt(In1->getValue());
5173}
5174
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5176/// code necessary to compute the offset from the base pointer (without adding
5177/// in the base pointer). Return the result as a signed integer of intptr size.
5178static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5179 TargetData &TD = IC.getTargetData();
5180 gep_type_iterator GTI = gep_type_begin(GEP);
5181 const Type *IntPtrTy = TD.getIntPtrType();
5182 Value *Result = Constant::getNullValue(IntPtrTy);
5183
5184 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005185 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005186 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5187
Gabor Greif17396002008-06-12 21:37:33 +00005188 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5189 ++i, ++GTI) {
5190 Value *Op = *i;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005191 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5193 if (OpC->isZero()) continue;
5194
5195 // Handle a struct index, which adds its field offset to the pointer.
5196 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5197 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5198
5199 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5200 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5201 else
5202 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005203 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005204 ConstantInt::get(IntPtrTy, Size),
5205 GEP->getName()+".offs"), I);
5206 continue;
5207 }
5208
5209 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5210 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5211 Scale = ConstantExpr::getMul(OC, Scale);
5212 if (Constant *RC = dyn_cast<Constant>(Result))
5213 Result = ConstantExpr::getAdd(RC, Scale);
5214 else {
5215 // Emit an add instruction.
5216 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005217 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005218 GEP->getName()+".offs"), I);
5219 }
5220 continue;
5221 }
5222 // Convert to correct type.
5223 if (Op->getType() != IntPtrTy) {
5224 if (Constant *OpC = dyn_cast<Constant>(Op))
5225 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5226 else
5227 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5228 Op->getName()+".c"), I);
5229 }
5230 if (Size != 1) {
5231 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5232 if (Constant *OpC = dyn_cast<Constant>(Op))
5233 Op = ConstantExpr::getMul(OpC, Scale);
5234 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005235 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005236 GEP->getName()+".idx"), I);
5237 }
5238
5239 // Emit an add instruction.
5240 if (isa<Constant>(Op) && isa<Constant>(Result))
5241 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5242 cast<Constant>(Result));
5243 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005244 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005245 GEP->getName()+".offs"), I);
5246 }
5247 return Result;
5248}
5249
Chris Lattnereba75862008-04-22 02:53:33 +00005250
5251/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5252/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5253/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5254/// complex, and scales are involved. The above expression would also be legal
5255/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5256/// later form is less amenable to optimization though, and we are allowed to
5257/// generate the first by knowing that pointer arithmetic doesn't overflow.
5258///
5259/// If we can't emit an optimized form for this expression, this returns null.
5260///
5261static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5262 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005263 TargetData &TD = IC.getTargetData();
5264 gep_type_iterator GTI = gep_type_begin(GEP);
5265
5266 // Check to see if this gep only has a single variable index. If so, and if
5267 // any constant indices are a multiple of its scale, then we can compute this
5268 // in terms of the scale of the variable index. For example, if the GEP
5269 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5270 // because the expression will cross zero at the same point.
5271 unsigned i, e = GEP->getNumOperands();
5272 int64_t Offset = 0;
5273 for (i = 1; i != e; ++i, ++GTI) {
5274 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5275 // Compute the aggregate offset of constant indices.
5276 if (CI->isZero()) continue;
5277
5278 // Handle a struct index, which adds its field offset to the pointer.
5279 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5280 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5281 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005282 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005283 Offset += Size*CI->getSExtValue();
5284 }
5285 } else {
5286 // Found our variable index.
5287 break;
5288 }
5289 }
5290
5291 // If there are no variable indices, we must have a constant offset, just
5292 // evaluate it the general way.
5293 if (i == e) return 0;
5294
5295 Value *VariableIdx = GEP->getOperand(i);
5296 // Determine the scale factor of the variable element. For example, this is
5297 // 4 if the variable index is into an array of i32.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005298 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005299
5300 // Verify that there are no other variable indices. If so, emit the hard way.
5301 for (++i, ++GTI; i != e; ++i, ++GTI) {
5302 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5303 if (!CI) return 0;
5304
5305 // Compute the aggregate offset of constant indices.
5306 if (CI->isZero()) continue;
5307
5308 // Handle a struct index, which adds its field offset to the pointer.
5309 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5310 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5311 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005312 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005313 Offset += Size*CI->getSExtValue();
5314 }
5315 }
5316
5317 // Okay, we know we have a single variable index, which must be a
5318 // pointer/array/vector index. If there is no offset, life is simple, return
5319 // the index.
5320 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5321 if (Offset == 0) {
5322 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5323 // we don't need to bother extending: the extension won't affect where the
5324 // computation crosses zero.
5325 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5326 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5327 VariableIdx->getNameStart(), &I);
5328 return VariableIdx;
5329 }
5330
5331 // Otherwise, there is an index. The computation we will do will be modulo
5332 // the pointer size, so get it.
5333 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5334
5335 Offset &= PtrSizeMask;
5336 VariableScale &= PtrSizeMask;
5337
5338 // To do this transformation, any constant index must be a multiple of the
5339 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5340 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5341 // multiple of the variable scale.
5342 int64_t NewOffs = Offset / (int64_t)VariableScale;
5343 if (Offset != NewOffs*(int64_t)VariableScale)
5344 return 0;
5345
5346 // Okay, we can do this evaluation. Start by converting the index to intptr.
5347 const Type *IntPtrTy = TD.getIntPtrType();
5348 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005349 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005350 true /*SExt*/,
5351 VariableIdx->getNameStart(), &I);
5352 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005353 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005354}
5355
5356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005357/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5358/// else. At this point we know that the GEP is on the LHS of the comparison.
5359Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5360 ICmpInst::Predicate Cond,
5361 Instruction &I) {
5362 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5363
Chris Lattnereba75862008-04-22 02:53:33 +00005364 // Look through bitcasts.
5365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5366 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005367
5368 Value *PtrBase = GEPLHS->getOperand(0);
5369 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005370 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005371 // This transformation (ignoring the base and scales) is valid because we
5372 // know pointers can't overflow. See if we can output an optimized form.
5373 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5374
5375 // If not, synthesize the offset the hard way.
5376 if (Offset == 0)
5377 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005378 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5379 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005380 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5381 // If the base pointers are different, but the indices are the same, just
5382 // compare the base pointer.
5383 if (PtrBase != GEPRHS->getOperand(0)) {
5384 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5385 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5386 GEPRHS->getOperand(0)->getType();
5387 if (IndicesTheSame)
5388 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5389 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5390 IndicesTheSame = false;
5391 break;
5392 }
5393
5394 // If all indices are the same, just compare the base pointers.
5395 if (IndicesTheSame)
5396 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5397 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5398
5399 // Otherwise, the base pointers are different and the indices are
5400 // different, bail out.
5401 return 0;
5402 }
5403
5404 // If one of the GEPs has all zero indices, recurse.
5405 bool AllZeros = true;
5406 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5407 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5408 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5409 AllZeros = false;
5410 break;
5411 }
5412 if (AllZeros)
5413 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5414 ICmpInst::getSwappedPredicate(Cond), I);
5415
5416 // If the other GEP has all zero indices, recurse.
5417 AllZeros = true;
5418 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5419 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5420 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5421 AllZeros = false;
5422 break;
5423 }
5424 if (AllZeros)
5425 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5426
5427 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5428 // If the GEPs only differ by one index, compare it.
5429 unsigned NumDifferences = 0; // Keep track of # differences.
5430 unsigned DiffOperand = 0; // The operand that differs.
5431 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5432 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5433 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5434 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5435 // Irreconcilable differences.
5436 NumDifferences = 2;
5437 break;
5438 } else {
5439 if (NumDifferences++) break;
5440 DiffOperand = i;
5441 }
5442 }
5443
5444 if (NumDifferences == 0) // SAME GEP?
5445 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005446 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005447 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005448
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005449 else if (NumDifferences == 1) {
5450 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5451 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5452 // Make sure we do a signed comparison here.
5453 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5454 }
5455 }
5456
5457 // Only lower this if the icmp is the only user of the GEP or if we expect
5458 // the result to fold to a constant!
5459 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5460 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5461 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5462 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5463 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5464 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5465 }
5466 }
5467 return 0;
5468}
5469
Chris Lattnere6b62d92008-05-19 20:18:56 +00005470/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5471///
5472Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5473 Instruction *LHSI,
5474 Constant *RHSC) {
5475 if (!isa<ConstantFP>(RHSC)) return 0;
5476 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5477
5478 // Get the width of the mantissa. We don't want to hack on conversions that
5479 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005480 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005481 if (MantissaWidth == -1) return 0; // Unknown.
5482
5483 // Check to see that the input is converted from an integer type that is small
5484 // enough that preserves all bits. TODO: check here for "known" sign bits.
5485 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5486 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5487
5488 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005489 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5490 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005491 ++InputSize;
5492
5493 // If the conversion would lose info, don't hack on this.
5494 if ((int)InputSize > MantissaWidth)
5495 return 0;
5496
5497 // Otherwise, we can potentially simplify the comparison. We know that it
5498 // will always come through as an integer value and we know the constant is
5499 // not a NAN (it would have been previously simplified).
5500 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5501
5502 ICmpInst::Predicate Pred;
5503 switch (I.getPredicate()) {
5504 default: assert(0 && "Unexpected predicate!");
5505 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005506 case FCmpInst::FCMP_OEQ:
5507 Pred = ICmpInst::ICMP_EQ;
5508 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005509 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005510 case FCmpInst::FCMP_OGT:
5511 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5512 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005513 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005514 case FCmpInst::FCMP_OGE:
5515 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5516 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005517 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005518 case FCmpInst::FCMP_OLT:
5519 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5520 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005521 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005522 case FCmpInst::FCMP_OLE:
5523 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5524 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005525 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005526 case FCmpInst::FCMP_ONE:
5527 Pred = ICmpInst::ICMP_NE;
5528 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005529 case FCmpInst::FCMP_ORD:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005530 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005531 case FCmpInst::FCMP_UNO:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005532 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005533 }
5534
5535 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5536
5537 // Now we know that the APFloat is a normal number, zero or inf.
5538
Chris Lattnerf13ff492008-05-20 03:50:52 +00005539 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005540 // comparing an i8 to 300.0.
5541 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5542
Bill Wendling20636df2008-11-09 04:26:50 +00005543 if (!LHSUnsigned) {
5544 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5545 // and large values.
5546 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5547 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5548 APFloat::rmNearestTiesToEven);
5549 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5550 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5551 Pred == ICmpInst::ICMP_SLE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005552 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5553 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005554 }
5555 } else {
5556 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5557 // +INF and large values.
5558 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5559 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5560 APFloat::rmNearestTiesToEven);
5561 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5562 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5563 Pred == ICmpInst::ICMP_ULE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005564 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5565 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005566 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005567 }
5568
Bill Wendling20636df2008-11-09 04:26:50 +00005569 if (!LHSUnsigned) {
5570 // See if the RHS value is < SignedMin.
5571 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5572 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5573 APFloat::rmNearestTiesToEven);
5574 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5575 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5576 Pred == ICmpInst::ICMP_SGE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005577 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005579 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005580 }
5581
Bill Wendling20636df2008-11-09 04:26:50 +00005582 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5583 // [0, UMAX], but it may still be fractional. See if it is fractional by
5584 // casting the FP value to the integer value and back, checking for equality.
5585 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005586 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5587 if (!RHS.isZero() &&
5588 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendling20636df2008-11-09 04:26:50 +00005589 // If we had a comparison against a fractional value, we have to adjust the
5590 // compare predicate and sometimes the value. RHSC is rounded towards zero
5591 // at this point.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005592 switch (Pred) {
5593 default: assert(0 && "Unexpected integer comparison!");
5594 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedmanc9c96242008-11-30 22:48:49 +00005595 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005596 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedmanc9c96242008-11-30 22:48:49 +00005597 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005598 case ICmpInst::ICMP_ULE:
5599 // (float)int <= 4.4 --> int <= 4
5600 // (float)int <= -4.4 --> false
5601 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005602 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005603 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005604 case ICmpInst::ICMP_SLE:
5605 // (float)int <= 4.4 --> int <= 4
5606 // (float)int <= -4.4 --> int < -4
5607 if (RHS.isNegative())
5608 Pred = ICmpInst::ICMP_SLT;
5609 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005610 case ICmpInst::ICMP_ULT:
5611 // (float)int < -4.4 --> false
5612 // (float)int < 4.4 --> int <= 4
5613 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005614 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005615 Pred = ICmpInst::ICMP_ULE;
5616 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005617 case ICmpInst::ICMP_SLT:
5618 // (float)int < -4.4 --> int < -4
5619 // (float)int < 4.4 --> int <= 4
5620 if (!RHS.isNegative())
5621 Pred = ICmpInst::ICMP_SLE;
5622 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005623 case ICmpInst::ICMP_UGT:
5624 // (float)int > 4.4 --> int > 4
5625 // (float)int > -4.4 --> true
5626 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005627 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005628 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005629 case ICmpInst::ICMP_SGT:
5630 // (float)int > 4.4 --> int > 4
5631 // (float)int > -4.4 --> int >= -4
5632 if (RHS.isNegative())
5633 Pred = ICmpInst::ICMP_SGE;
5634 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005635 case ICmpInst::ICMP_UGE:
5636 // (float)int >= -4.4 --> true
5637 // (float)int >= 4.4 --> int > 4
5638 if (!RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005639 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005640 Pred = ICmpInst::ICMP_UGT;
5641 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005642 case ICmpInst::ICMP_SGE:
5643 // (float)int >= -4.4 --> int >= -4
5644 // (float)int >= 4.4 --> int > 4
5645 if (!RHS.isNegative())
5646 Pred = ICmpInst::ICMP_SGT;
5647 break;
5648 }
5649 }
5650
5651 // Lower this FP comparison into an appropriate integer version of the
5652 // comparison.
5653 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5654}
5655
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005656Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5657 bool Changed = SimplifyCompare(I);
5658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5659
5660 // Fold trivial predicates.
5661 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005662 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005663 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005664 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005665
5666 // Simplify 'fcmp pred X, X'
5667 if (Op0 == Op1) {
5668 switch (I.getPredicate()) {
5669 default: assert(0 && "Unknown predicate!");
5670 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5671 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5672 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005673 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005674 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5675 case FCmpInst::FCMP_OLT: // True if ordered and less than
5676 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005677 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005678
5679 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5680 case FCmpInst::FCMP_ULT: // True if unordered or less than
5681 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5682 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5683 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5684 I.setPredicate(FCmpInst::FCMP_UNO);
5685 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5686 return &I;
5687
5688 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5689 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5690 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5691 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5692 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5693 I.setPredicate(FCmpInst::FCMP_ORD);
5694 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5695 return &I;
5696 }
5697 }
5698
5699 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5700 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5701
5702 // Handle fcmp with constant RHS
5703 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005704 // If the constant is a nan, see if we can fold the comparison based on it.
5705 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5706 if (CFP->getValueAPF().isNaN()) {
5707 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedmanc9c96242008-11-30 22:48:49 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005709 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5710 "Comparison must be either ordered or unordered!");
5711 // True if unordered.
Eli Friedmanc9c96242008-11-30 22:48:49 +00005712 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005713 }
5714 }
5715
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5717 switch (LHSI->getOpcode()) {
5718 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005719 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5720 // block. If in the same block, we're encouraging jump threading. If
5721 // not, we are just pessimizing the code by making an i1 phi.
5722 if (LHSI->getParent() == I.getParent())
5723 if (Instruction *NV = FoldOpIntoPhi(I))
5724 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005725 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005726 case Instruction::SIToFP:
5727 case Instruction::UIToFP:
5728 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5729 return NV;
5730 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005731 case Instruction::Select:
5732 // If either operand of the select is a constant, we can fold the
5733 // comparison into the select arms, which will cause one to be
5734 // constant folded and the select turned into a bitwise or.
5735 Value *Op1 = 0, *Op2 = 0;
5736 if (LHSI->hasOneUse()) {
5737 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5738 // Fold the known value into the constant operand.
5739 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5740 // Insert a new FCmp of the other select operand.
5741 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5742 LHSI->getOperand(2), RHSC,
5743 I.getName()), I);
5744 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5745 // Fold the known value into the constant operand.
5746 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5747 // Insert a new FCmp of the other select operand.
5748 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5749 LHSI->getOperand(1), RHSC,
5750 I.getName()), I);
5751 }
5752 }
5753
5754 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005755 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005756 break;
5757 }
5758 }
5759
5760 return Changed ? &I : 0;
5761}
5762
5763Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5764 bool Changed = SimplifyCompare(I);
5765 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5766 const Type *Ty = Op0->getType();
5767
5768 // icmp X, X
5769 if (Op0 == Op1)
5770 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005771 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005772
5773 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5774 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005775
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005776 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5777 // addresses never equal each other! We already know that Op0 != Op1.
5778 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5779 isa<ConstantPointerNull>(Op0)) &&
5780 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5781 isa<ConstantPointerNull>(Op1)))
5782 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005783 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005784
5785 // icmp's with boolean values can always be turned into bitwise operations
5786 if (Ty == Type::Int1Ty) {
5787 switch (I.getPredicate()) {
5788 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005789 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005790 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005791 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005792 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005793 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005794 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005795 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005796
5797 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005798 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005799 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005800 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005801 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005802 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005803 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005804 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005805 case ICmpInst::ICMP_SGT:
5806 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005807 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005808 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5809 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5810 InsertNewInstBefore(Not, I);
5811 return BinaryOperator::CreateAnd(Not, Op0);
5812 }
5813 case ICmpInst::ICMP_UGE:
5814 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5815 // FALL THROUGH
5816 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005817 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005818 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005819 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005820 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005821 case ICmpInst::ICMP_SGE:
5822 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5823 // FALL THROUGH
5824 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5825 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5826 InsertNewInstBefore(Not, I);
5827 return BinaryOperator::CreateOr(Not, Op0);
5828 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005829 }
5830 }
5831
Dan Gohman58c09632008-09-16 18:46:06 +00005832 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005833 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005834 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005835
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005836 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5837 if (I.isEquality() && CI->isNullValue() &&
5838 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5839 // (icmp cond A B) if cond is equality
5840 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005841 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005842
Dan Gohman58c09632008-09-16 18:46:06 +00005843 // If we have an icmp le or icmp ge instruction, turn it into the
5844 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5845 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005846 switch (I.getPredicate()) {
5847 default: break;
5848 case ICmpInst::ICMP_ULE:
5849 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5850 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5851 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5852 case ICmpInst::ICMP_SLE:
5853 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5854 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5855 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5856 case ICmpInst::ICMP_UGE:
5857 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5858 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5859 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5860 case ICmpInst::ICMP_SGE:
5861 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5862 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5863 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5864 }
5865
Chris Lattnera1308652008-07-11 05:40:05 +00005866 // See if we can fold the comparison based on range information we can get
5867 // by checking whether bits are known to be zero or one in the input.
5868 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5869 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5870
5871 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005872 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005873 bool UnusedBit;
5874 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5875
Chris Lattner676c78e2009-01-31 08:15:18 +00005876 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005877 isSignBit ? APInt::getSignBit(BitWidth)
5878 : APInt::getAllOnesValue(BitWidth),
5879 KnownZero, KnownOne, 0))
5880 return &I;
5881
5882 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00005883 // in. Compute the Min, Max and RHS values based on the known bits. For the
5884 // EQ and NE we use unsigned values.
5885 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner62d0f232008-07-11 05:08:55 +00005886 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5887 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5888 else
5889 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5890
Chris Lattnera1308652008-07-11 05:40:05 +00005891 // If Min and Max are known to be the same, then SimplifyDemandedBits
5892 // figured out that the LHS is a constant. Just constant fold this now so
5893 // that code below can assume that Min != Max.
5894 if (Min == Max)
5895 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5896 ConstantInt::get(Min),
5897 CI));
5898
5899 // Based on the range information we know about the LHS, see if we can
5900 // simplify this comparison. For example, (x&4) < 8 is always true.
5901 const APInt &RHSVal = CI->getValue();
Chris Lattner62d0f232008-07-11 05:08:55 +00005902 switch (I.getPredicate()) { // LE/GE have been folded already.
5903 default: assert(0 && "Unknown icmp opcode!");
5904 case ICmpInst::ICMP_EQ:
5905 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5906 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5907 break;
5908 case ICmpInst::ICMP_NE:
5909 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5910 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5911 break;
5912 case ICmpInst::ICMP_ULT:
Chris Lattnera1308652008-07-11 05:40:05 +00005913 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005915 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005916 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005917 if (RHSVal == Max) // A <u MAX -> A != MAX
5918 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5919 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5920 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5921
5922 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5923 if (CI->isMinValue(true))
5924 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5925 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005926 break;
5927 case ICmpInst::ICMP_UGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005928 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005929 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005930 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005931 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005932
5933 if (RHSVal == Min) // A >u MIN -> A != MIN
5934 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5935 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5936 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5937
5938 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5939 if (CI->isMaxValue(true))
5940 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5941 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005942 break;
5943 case ICmpInst::ICMP_SLT:
Chris Lattnera1308652008-07-11 05:40:05 +00005944 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005945 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner611b43e2008-07-11 06:40:29 +00005946 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005947 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005948 if (RHSVal == Max) // A <s MAX -> A != MAX
5949 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattner3496f3e2008-07-11 06:36:01 +00005950 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner55ab3152008-07-11 06:38:16 +00005951 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005952 break;
5953 case ICmpInst::ICMP_SGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005954 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005955 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005956 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005958
5959 if (RHSVal == Min) // A >s MIN -> A != MIN
5960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5961 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5962 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005963 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005964 }
Dan Gohman58c09632008-09-16 18:46:06 +00005965 }
5966
5967 // Test if the ICmpInst instruction is used exclusively by a select as
5968 // part of a minimum or maximum operation. If so, refrain from doing
5969 // any other folding. This helps out other analyses which understand
5970 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5971 // and CodeGen. And in this case, at least one of the comparison
5972 // operands has at least one user besides the compare (the select),
5973 // which would often largely negate the benefit of folding anyway.
5974 if (I.hasOneUse())
5975 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5976 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5977 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5978 return 0;
5979
5980 // See if we are doing a comparison between a constant and an instruction that
5981 // can be folded into the comparison.
5982 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005983 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5984 // instruction, see if that instruction also has constants so that the
5985 // instruction can be folded into the icmp
5986 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5988 return Res;
5989 }
5990
5991 // Handle icmp with constant (but not simple integer constant) RHS
5992 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5993 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5994 switch (LHSI->getOpcode()) {
5995 case Instruction::GetElementPtr:
5996 if (RHSC->isNullValue()) {
5997 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5998 bool isAllZeros = true;
5999 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6000 if (!isa<Constant>(LHSI->getOperand(i)) ||
6001 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6002 isAllZeros = false;
6003 break;
6004 }
6005 if (isAllZeros)
6006 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6007 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6008 }
6009 break;
6010
6011 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006012 // Only fold icmp into the PHI if the phi and fcmp are in the same
6013 // block. If in the same block, we're encouraging jump threading. If
6014 // not, we are just pessimizing the code by making an i1 phi.
6015 if (LHSI->getParent() == I.getParent())
6016 if (Instruction *NV = FoldOpIntoPhi(I))
6017 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006018 break;
6019 case Instruction::Select: {
6020 // If either operand of the select is a constant, we can fold the
6021 // comparison into the select arms, which will cause one to be
6022 // constant folded and the select turned into a bitwise or.
6023 Value *Op1 = 0, *Op2 = 0;
6024 if (LHSI->hasOneUse()) {
6025 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6026 // Fold the known value into the constant operand.
6027 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6028 // Insert a new ICmp of the other select operand.
6029 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6030 LHSI->getOperand(2), RHSC,
6031 I.getName()), I);
6032 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6033 // Fold the known value into the constant operand.
6034 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6035 // Insert a new ICmp of the other select operand.
6036 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6037 LHSI->getOperand(1), RHSC,
6038 I.getName()), I);
6039 }
6040 }
6041
6042 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006043 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006044 break;
6045 }
6046 case Instruction::Malloc:
6047 // If we have (malloc != null), and if the malloc has a single use, we
6048 // can assume it is successful and remove the malloc.
6049 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6050 AddToWorkList(LHSI);
6051 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006052 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006053 }
6054 break;
6055 }
6056 }
6057
6058 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6059 if (User *GEP = dyn_castGetElementPtr(Op0))
6060 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6061 return NI;
6062 if (User *GEP = dyn_castGetElementPtr(Op1))
6063 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6064 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6065 return NI;
6066
6067 // Test to see if the operands of the icmp are casted versions of other
6068 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6069 // now.
6070 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6071 if (isa<PointerType>(Op0->getType()) &&
6072 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6073 // We keep moving the cast from the left operand over to the right
6074 // operand, where it can often be eliminated completely.
6075 Op0 = CI->getOperand(0);
6076
6077 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6078 // so eliminate it as well.
6079 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6080 Op1 = CI2->getOperand(0);
6081
6082 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006083 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006084 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6085 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6086 } else {
6087 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006088 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006089 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006090 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006091 return new ICmpInst(I.getPredicate(), Op0, Op1);
6092 }
6093 }
6094
6095 if (isa<CastInst>(Op0)) {
6096 // Handle the special case of: icmp (cast bool to X), <cst>
6097 // This comes up when you have code like
6098 // int X = A < B;
6099 // if (X) ...
6100 // For generality, we handle any zero-extension of any operand comparison
6101 // with a constant or another cast from the same type.
6102 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6103 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6104 return R;
6105 }
6106
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006107 // See if it's the same type of instruction on the left and right.
6108 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6109 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006110 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006111 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006112 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006113 default: break;
6114 case Instruction::Add:
6115 case Instruction::Sub:
6116 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006117 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewyckydac84332009-01-31 21:30:05 +00006118 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6119 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006120 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6121 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6122 if (CI->getValue().isSignBit()) {
6123 ICmpInst::Predicate Pred = I.isSignedPredicate()
6124 ? I.getUnsignedPredicate()
6125 : I.getSignedPredicate();
6126 return new ICmpInst(Pred, Op0I->getOperand(0),
6127 Op1I->getOperand(0));
6128 }
6129
6130 if (CI->getValue().isMaxSignedValue()) {
6131 ICmpInst::Predicate Pred = I.isSignedPredicate()
6132 ? I.getUnsignedPredicate()
6133 : I.getSignedPredicate();
6134 Pred = I.getSwappedPredicate(Pred);
6135 return new ICmpInst(Pred, Op0I->getOperand(0),
6136 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006137 }
6138 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006139 break;
6140 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006141 if (!I.isEquality())
6142 break;
6143
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006144 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6145 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6146 // Mask = -1 >> count-trailing-zeros(Cst).
6147 if (!CI->isZero() && !CI->isOne()) {
6148 const APInt &AP = CI->getValue();
6149 ConstantInt *Mask = ConstantInt::get(
6150 APInt::getLowBitsSet(AP.getBitWidth(),
6151 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006152 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006153 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6154 Mask);
6155 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6156 Mask);
6157 InsertNewInstBefore(And1, I);
6158 InsertNewInstBefore(And2, I);
6159 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006160 }
6161 }
6162 break;
6163 }
6164 }
6165 }
6166 }
6167
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006168 // ~x < ~y --> y < x
6169 { Value *A, *B;
6170 if (match(Op0, m_Not(m_Value(A))) &&
6171 match(Op1, m_Not(m_Value(B))))
6172 return new ICmpInst(I.getPredicate(), B, A);
6173 }
6174
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006175 if (I.isEquality()) {
6176 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006177
6178 // -x == -y --> x == y
6179 if (match(Op0, m_Neg(m_Value(A))) &&
6180 match(Op1, m_Neg(m_Value(B))))
6181 return new ICmpInst(I.getPredicate(), A, B);
6182
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006183 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6184 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6185 Value *OtherVal = A == Op1 ? B : A;
6186 return new ICmpInst(I.getPredicate(), OtherVal,
6187 Constant::getNullValue(A->getType()));
6188 }
6189
6190 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6191 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006192 ConstantInt *C1, *C2;
6193 if (match(B, m_ConstantInt(C1)) &&
6194 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6195 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6196 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6197 return new ICmpInst(I.getPredicate(), A,
6198 InsertNewInstBefore(Xor, I));
6199 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006200
6201 // A^B == A^D -> B == D
6202 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6203 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6204 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6205 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6206 }
6207 }
6208
6209 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6210 (A == Op0 || B == Op0)) {
6211 // A == (A^B) -> B == 0
6212 Value *OtherVal = A == Op0 ? B : A;
6213 return new ICmpInst(I.getPredicate(), OtherVal,
6214 Constant::getNullValue(A->getType()));
6215 }
Chris Lattner3b874082008-11-16 05:38:51 +00006216
6217 // (A-B) == A -> B == 0
6218 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6219 return new ICmpInst(I.getPredicate(), B,
6220 Constant::getNullValue(B->getType()));
6221
6222 // A == (A-B) -> B == 0
6223 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006224 return new ICmpInst(I.getPredicate(), B,
6225 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006226
6227 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6228 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6229 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6230 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6231 Value *X = 0, *Y = 0, *Z = 0;
6232
6233 if (A == C) {
6234 X = B; Y = D; Z = A;
6235 } else if (A == D) {
6236 X = B; Y = C; Z = A;
6237 } else if (B == C) {
6238 X = A; Y = D; Z = B;
6239 } else if (B == D) {
6240 X = A; Y = C; Z = B;
6241 }
6242
6243 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006244 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6245 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006246 I.setOperand(0, Op1);
6247 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6248 return &I;
6249 }
6250 }
6251 }
6252 return Changed ? &I : 0;
6253}
6254
6255
6256/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6257/// and CmpRHS are both known to be integer constants.
6258Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6259 ConstantInt *DivRHS) {
6260 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6261 const APInt &CmpRHSV = CmpRHS->getValue();
6262
6263 // FIXME: If the operand types don't match the type of the divide
6264 // then don't attempt this transform. The code below doesn't have the
6265 // logic to deal with a signed divide and an unsigned compare (and
6266 // vice versa). This is because (x /s C1) <s C2 produces different
6267 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6268 // (x /u C1) <u C2. Simply casting the operands and result won't
6269 // work. :( The if statement below tests that condition and bails
6270 // if it finds it.
6271 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6272 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6273 return 0;
6274 if (DivRHS->isZero())
6275 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006276 if (DivIsSigned && DivRHS->isAllOnesValue())
6277 return 0; // The overflow computation also screws up here
6278 if (DivRHS->isOne())
6279 return 0; // Not worth bothering, and eliminates some funny cases
6280 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006281
6282 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6283 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6284 // C2 (CI). By solving for X we can turn this into a range check
6285 // instead of computing a divide.
6286 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6287
6288 // Determine if the product overflows by seeing if the product is
6289 // not equal to the divide. Make sure we do the same kind of divide
6290 // as in the LHS instruction that we're folding.
6291 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6292 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6293
6294 // Get the ICmp opcode
6295 ICmpInst::Predicate Pred = ICI.getPredicate();
6296
6297 // Figure out the interval that is being checked. For example, a comparison
6298 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6299 // Compute this interval based on the constants involved and the signedness of
6300 // the compare/divide. This computes a half-open interval, keeping track of
6301 // whether either value in the interval overflows. After analysis each
6302 // overflow variable is set to 0 if it's corresponding bound variable is valid
6303 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6304 int LoOverflow = 0, HiOverflow = 0;
6305 ConstantInt *LoBound = 0, *HiBound = 0;
6306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006307 if (!DivIsSigned) { // udiv
6308 // e.g. X/5 op 3 --> [15, 20)
6309 LoBound = Prod;
6310 HiOverflow = LoOverflow = ProdOV;
6311 if (!HiOverflow)
6312 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006313 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006314 if (CmpRHSV == 0) { // (X / pos) op 0
6315 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6316 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6317 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006318 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006319 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6320 HiOverflow = LoOverflow = ProdOV;
6321 if (!HiOverflow)
6322 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6323 } else { // (X / pos) op neg
6324 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006325 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006326 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6327 if (!LoOverflow) {
6328 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6329 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6330 true) ? -1 : 0;
6331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006332 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006333 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006334 if (CmpRHSV == 0) { // (X / neg) op 0
6335 // e.g. X/-5 op 0 --> [-4, 5)
6336 LoBound = AddOne(DivRHS);
6337 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6338 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6339 HiOverflow = 1; // [INTMIN+1, overflow)
6340 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6341 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006342 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006343 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006344 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006345 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6346 if (!LoOverflow)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006347 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006348 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006349 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6350 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006351 if (!HiOverflow)
6352 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006353 }
6354
6355 // Dividing by a negative swaps the condition. LT <-> GT
6356 Pred = ICmpInst::getSwappedPredicate(Pred);
6357 }
6358
6359 Value *X = DivI->getOperand(0);
6360 switch (Pred) {
6361 default: assert(0 && "Unhandled icmp opcode!");
6362 case ICmpInst::ICMP_EQ:
6363 if (LoOverflow && HiOverflow)
6364 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6365 else if (HiOverflow)
6366 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6367 ICmpInst::ICMP_UGE, X, LoBound);
6368 else if (LoOverflow)
6369 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6370 ICmpInst::ICMP_ULT, X, HiBound);
6371 else
6372 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6373 case ICmpInst::ICMP_NE:
6374 if (LoOverflow && HiOverflow)
6375 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6376 else if (HiOverflow)
6377 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6378 ICmpInst::ICMP_ULT, X, LoBound);
6379 else if (LoOverflow)
6380 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6381 ICmpInst::ICMP_UGE, X, HiBound);
6382 else
6383 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6384 case ICmpInst::ICMP_ULT:
6385 case ICmpInst::ICMP_SLT:
6386 if (LoOverflow == +1) // Low bound is greater than input range.
6387 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6388 if (LoOverflow == -1) // Low bound is less than input range.
6389 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6390 return new ICmpInst(Pred, X, LoBound);
6391 case ICmpInst::ICMP_UGT:
6392 case ICmpInst::ICMP_SGT:
6393 if (HiOverflow == +1) // High bound greater than input range.
6394 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6395 else if (HiOverflow == -1) // High bound less than input range.
6396 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6397 if (Pred == ICmpInst::ICMP_UGT)
6398 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6399 else
6400 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6401 }
6402}
6403
6404
6405/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6406///
6407Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6408 Instruction *LHSI,
6409 ConstantInt *RHS) {
6410 const APInt &RHSV = RHS->getValue();
6411
6412 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006413 case Instruction::Trunc:
6414 if (ICI.isEquality() && LHSI->hasOneUse()) {
6415 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6416 // of the high bits truncated out of x are known.
6417 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6418 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6419 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6420 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6421 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6422
6423 // If all the high bits are known, we can do this xform.
6424 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6425 // Pull in the high bits from known-ones set.
6426 APInt NewRHS(RHS->getValue());
6427 NewRHS.zext(SrcBits);
6428 NewRHS |= KnownOne;
6429 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6430 ConstantInt::get(NewRHS));
6431 }
6432 }
6433 break;
6434
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006435 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6436 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6437 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6438 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006439 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6440 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006441 Value *CompareVal = LHSI->getOperand(0);
6442
6443 // If the sign bit of the XorCST is not set, there is no change to
6444 // the operation, just stop using the Xor.
6445 if (!XorCST->getValue().isNegative()) {
6446 ICI.setOperand(0, CompareVal);
6447 AddToWorkList(LHSI);
6448 return &ICI;
6449 }
6450
6451 // Was the old condition true if the operand is positive?
6452 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6453
6454 // If so, the new one isn't.
6455 isTrueIfPositive ^= true;
6456
6457 if (isTrueIfPositive)
6458 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6459 else
6460 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6461 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006462
6463 if (LHSI->hasOneUse()) {
6464 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6465 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6466 const APInt &SignBit = XorCST->getValue();
6467 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6468 ? ICI.getUnsignedPredicate()
6469 : ICI.getSignedPredicate();
6470 return new ICmpInst(Pred, LHSI->getOperand(0),
6471 ConstantInt::get(RHSV ^ SignBit));
6472 }
6473
6474 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006475 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006476 const APInt &NotSignBit = XorCST->getValue();
6477 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6478 ? ICI.getUnsignedPredicate()
6479 : ICI.getSignedPredicate();
6480 Pred = ICI.getSwappedPredicate(Pred);
6481 return new ICmpInst(Pred, LHSI->getOperand(0),
6482 ConstantInt::get(RHSV ^ NotSignBit));
6483 }
6484 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006485 }
6486 break;
6487 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6488 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6489 LHSI->getOperand(0)->hasOneUse()) {
6490 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6491
6492 // If the LHS is an AND of a truncating cast, we can widen the
6493 // and/compare to be the input width without changing the value
6494 // produced, eliminating a cast.
6495 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6496 // We can do this transformation if either the AND constant does not
6497 // have its sign bit set or if it is an equality comparison.
6498 // Extending a relational comparison when we're checking the sign
6499 // bit would not work.
6500 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006501 (ICI.isEquality() ||
6502 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006503 uint32_t BitWidth =
6504 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6505 APInt NewCST = AndCST->getValue();
6506 NewCST.zext(BitWidth);
6507 APInt NewCI = RHSV;
6508 NewCI.zext(BitWidth);
6509 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006510 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511 ConstantInt::get(NewCST),LHSI->getName());
6512 InsertNewInstBefore(NewAnd, ICI);
6513 return new ICmpInst(ICI.getPredicate(), NewAnd,
6514 ConstantInt::get(NewCI));
6515 }
6516 }
6517
6518 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6519 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6520 // happens a LOT in code produced by the C front-end, for bitfield
6521 // access.
6522 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6523 if (Shift && !Shift->isShift())
6524 Shift = 0;
6525
6526 ConstantInt *ShAmt;
6527 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6528 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6529 const Type *AndTy = AndCST->getType(); // Type of the and.
6530
6531 // We can fold this as long as we can't shift unknown bits
6532 // into the mask. This can only happen with signed shift
6533 // rights, as they sign-extend.
6534 if (ShAmt) {
6535 bool CanFold = Shift->isLogicalShift();
6536 if (!CanFold) {
6537 // To test for the bad case of the signed shr, see if any
6538 // of the bits shifted in could be tested after the mask.
6539 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6540 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6541
6542 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6543 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6544 AndCST->getValue()) == 0)
6545 CanFold = true;
6546 }
6547
6548 if (CanFold) {
6549 Constant *NewCst;
6550 if (Shift->getOpcode() == Instruction::Shl)
6551 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6552 else
6553 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6554
6555 // Check to see if we are shifting out any of the bits being
6556 // compared.
6557 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6558 // If we shifted bits out, the fold is not going to work out.
6559 // As a special case, check to see if this means that the
6560 // result is always true or false now.
6561 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6562 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6563 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6564 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6565 } else {
6566 ICI.setOperand(1, NewCst);
6567 Constant *NewAndCST;
6568 if (Shift->getOpcode() == Instruction::Shl)
6569 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6570 else
6571 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6572 LHSI->setOperand(1, NewAndCST);
6573 LHSI->setOperand(0, Shift->getOperand(0));
6574 AddToWorkList(Shift); // Shift is dead.
6575 AddUsesToWorkList(ICI);
6576 return &ICI;
6577 }
6578 }
6579 }
6580
6581 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6582 // preferable because it allows the C<<Y expression to be hoisted out
6583 // of a loop if Y is invariant and X is not.
6584 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattner8f64dc52009-03-24 23:48:25 +00006585 ICI.isEquality() && !Shift->isArithmeticShift()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006586 // Compute C << Y.
6587 Value *NS;
6588 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006589 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590 Shift->getOperand(1), "tmp");
6591 } else {
6592 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006593 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006594 Shift->getOperand(1), "tmp");
6595 }
6596 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6597
6598 // Compute X & (C << Y).
6599 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006600 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 InsertNewInstBefore(NewAnd, ICI);
6602
6603 ICI.setOperand(0, NewAnd);
6604 return &ICI;
6605 }
6606 }
6607 break;
6608
6609 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6610 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6611 if (!ShAmt) break;
6612
6613 uint32_t TypeBits = RHSV.getBitWidth();
6614
6615 // Check that the shift amount is in range. If not, don't perform
6616 // undefined shifts. When the shift is visited it will be
6617 // simplified.
6618 if (ShAmt->uge(TypeBits))
6619 break;
6620
6621 if (ICI.isEquality()) {
6622 // If we are comparing against bits always shifted out, the
6623 // comparison cannot succeed.
6624 Constant *Comp =
6625 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6626 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6627 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6628 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6629 return ReplaceInstUsesWith(ICI, Cst);
6630 }
6631
6632 if (LHSI->hasOneUse()) {
6633 // Otherwise strength reduce the shift into an and.
6634 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6635 Constant *Mask =
6636 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6637
6638 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006639 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 Mask, LHSI->getName()+".mask");
6641 Value *And = InsertNewInstBefore(AndI, ICI);
6642 return new ICmpInst(ICI.getPredicate(), And,
6643 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6644 }
6645 }
6646
6647 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6648 bool TrueIfSigned = false;
6649 if (LHSI->hasOneUse() &&
6650 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6651 // (X << 31) <s 0 --> (X&1) != 0
6652 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6653 (TypeBits-ShAmt->getZExtValue()-1));
6654 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006655 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 Mask, LHSI->getName()+".mask");
6657 Value *And = InsertNewInstBefore(AndI, ICI);
6658
6659 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6660 And, Constant::getNullValue(And->getType()));
6661 }
6662 break;
6663 }
6664
6665 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6666 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006667 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006669 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670
Chris Lattner5ee84f82008-03-21 05:19:58 +00006671 // Check that the shift amount is in range. If not, don't perform
6672 // undefined shifts. When the shift is visited it will be
6673 // simplified.
6674 uint32_t TypeBits = RHSV.getBitWidth();
6675 if (ShAmt->uge(TypeBits))
6676 break;
6677
6678 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006679
Chris Lattner5ee84f82008-03-21 05:19:58 +00006680 // If we are comparing against bits always shifted out, the
6681 // comparison cannot succeed.
6682 APInt Comp = RHSV << ShAmtVal;
6683 if (LHSI->getOpcode() == Instruction::LShr)
6684 Comp = Comp.lshr(ShAmtVal);
6685 else
6686 Comp = Comp.ashr(ShAmtVal);
6687
6688 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6689 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6690 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6691 return ReplaceInstUsesWith(ICI, Cst);
6692 }
6693
6694 // Otherwise, check to see if the bits shifted out are known to be zero.
6695 // If so, we can compare against the unshifted value:
6696 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006697 if (LHSI->hasOneUse() &&
6698 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006699 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6700 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6701 ConstantExpr::getShl(RHS, ShAmt));
6702 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006703
Evan Chengfb9292a2008-04-23 00:38:06 +00006704 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006705 // Otherwise strength reduce the shift into an and.
6706 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6707 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006708
Chris Lattner5ee84f82008-03-21 05:19:58 +00006709 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006710 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006711 Mask, LHSI->getName()+".mask");
6712 Value *And = InsertNewInstBefore(AndI, ICI);
6713 return new ICmpInst(ICI.getPredicate(), And,
6714 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006715 }
6716 break;
6717 }
6718
6719 case Instruction::SDiv:
6720 case Instruction::UDiv:
6721 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6722 // Fold this div into the comparison, producing a range check.
6723 // Determine, based on the divide type, what the range is being
6724 // checked. If there is an overflow on the low or high side, remember
6725 // it, otherwise compute the range [low, hi) bounding the new value.
6726 // See: InsertRangeTest above for the kinds of replacements possible.
6727 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6728 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6729 DivRHS))
6730 return R;
6731 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006732
6733 case Instruction::Add:
6734 // Fold: icmp pred (add, X, C1), C2
6735
6736 if (!ICI.isEquality()) {
6737 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6738 if (!LHSC) break;
6739 const APInt &LHSV = LHSC->getValue();
6740
6741 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6742 .subtract(LHSV);
6743
6744 if (ICI.isSignedPredicate()) {
6745 if (CR.getLower().isSignBit()) {
6746 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6747 ConstantInt::get(CR.getUpper()));
6748 } else if (CR.getUpper().isSignBit()) {
6749 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6750 ConstantInt::get(CR.getLower()));
6751 }
6752 } else {
6753 if (CR.getLower().isMinValue()) {
6754 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6755 ConstantInt::get(CR.getUpper()));
6756 } else if (CR.getUpper().isMinValue()) {
6757 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6758 ConstantInt::get(CR.getLower()));
6759 }
6760 }
6761 }
6762 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006763 }
6764
6765 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6766 if (ICI.isEquality()) {
6767 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6768
6769 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6770 // the second operand is a constant, simplify a bit.
6771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6772 switch (BO->getOpcode()) {
6773 case Instruction::SRem:
6774 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6775 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6776 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6777 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6778 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006779 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006780 BO->getName());
6781 InsertNewInstBefore(NewRem, ICI);
6782 return new ICmpInst(ICI.getPredicate(), NewRem,
6783 Constant::getNullValue(BO->getType()));
6784 }
6785 }
6786 break;
6787 case Instruction::Add:
6788 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6789 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6790 if (BO->hasOneUse())
6791 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6792 Subtract(RHS, BOp1C));
6793 } else if (RHSV == 0) {
6794 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6795 // efficiently invertible, or if the add has just this one use.
6796 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6797
6798 if (Value *NegVal = dyn_castNegVal(BOp1))
6799 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6800 else if (Value *NegVal = dyn_castNegVal(BOp0))
6801 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6802 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006803 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804 InsertNewInstBefore(Neg, ICI);
6805 Neg->takeName(BO);
6806 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6807 }
6808 }
6809 break;
6810 case Instruction::Xor:
6811 // For the xor case, we can xor two constants together, eliminating
6812 // the explicit xor.
6813 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6814 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6815 ConstantExpr::getXor(RHS, BOC));
6816
6817 // FALLTHROUGH
6818 case Instruction::Sub:
6819 // Replace (([sub|xor] A, B) != 0) with (A != B)
6820 if (RHSV == 0)
6821 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6822 BO->getOperand(1));
6823 break;
6824
6825 case Instruction::Or:
6826 // If bits are being or'd in that are not present in the constant we
6827 // are comparing against, then the comparison could never succeed!
6828 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6829 Constant *NotCI = ConstantExpr::getNot(RHS);
6830 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6831 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6832 isICMP_NE));
6833 }
6834 break;
6835
6836 case Instruction::And:
6837 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6838 // If bits are being compared against that are and'd out, then the
6839 // comparison can never succeed!
6840 if ((RHSV & ~BOC->getValue()) != 0)
6841 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6842 isICMP_NE));
6843
6844 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6845 if (RHS == BOC && RHSV.isPowerOf2())
6846 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6847 ICmpInst::ICMP_NE, LHSI,
6848 Constant::getNullValue(RHS->getType()));
6849
6850 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006851 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006852 Value *X = BO->getOperand(0);
6853 Constant *Zero = Constant::getNullValue(X->getType());
6854 ICmpInst::Predicate pred = isICMP_NE ?
6855 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6856 return new ICmpInst(pred, X, Zero);
6857 }
6858
6859 // ((X & ~7) == 0) --> X < 8
6860 if (RHSV == 0 && isHighOnes(BOC)) {
6861 Value *X = BO->getOperand(0);
6862 Constant *NegX = ConstantExpr::getNeg(BOC);
6863 ICmpInst::Predicate pred = isICMP_NE ?
6864 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6865 return new ICmpInst(pred, X, NegX);
6866 }
6867 }
6868 default: break;
6869 }
6870 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6871 // Handle icmp {eq|ne} <intrinsic>, intcst.
6872 if (II->getIntrinsicID() == Intrinsic::bswap) {
6873 AddToWorkList(II);
6874 ICI.setOperand(0, II->getOperand(1));
6875 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6876 return &ICI;
6877 }
6878 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 }
6880 return 0;
6881}
6882
6883/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6884/// We only handle extending casts so far.
6885///
6886Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6887 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6888 Value *LHSCIOp = LHSCI->getOperand(0);
6889 const Type *SrcTy = LHSCIOp->getType();
6890 const Type *DestTy = LHSCI->getType();
6891 Value *RHSCIOp;
6892
6893 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6894 // integer type is the same size as the pointer type.
6895 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6896 getTargetData().getPointerSizeInBits() ==
6897 cast<IntegerType>(DestTy)->getBitWidth()) {
6898 Value *RHSOp = 0;
6899 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6900 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6901 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6902 RHSOp = RHSC->getOperand(0);
6903 // If the pointer types don't match, insert a bitcast.
6904 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006905 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006906 }
6907
6908 if (RHSOp)
6909 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6910 }
6911
6912 // The code below only handles extension cast instructions, so far.
6913 // Enforce this.
6914 if (LHSCI->getOpcode() != Instruction::ZExt &&
6915 LHSCI->getOpcode() != Instruction::SExt)
6916 return 0;
6917
6918 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6919 bool isSignedCmp = ICI.isSignedPredicate();
6920
6921 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6922 // Not an extension from the same type?
6923 RHSCIOp = CI->getOperand(0);
6924 if (RHSCIOp->getType() != LHSCIOp->getType())
6925 return 0;
6926
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006927 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006928 // and the other is a zext), then we can't handle this.
6929 if (CI->getOpcode() != LHSCI->getOpcode())
6930 return 0;
6931
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006932 // Deal with equality cases early.
6933 if (ICI.isEquality())
6934 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6935
6936 // A signed comparison of sign extended values simplifies into a
6937 // signed comparison.
6938 if (isSignedCmp && isSignedExt)
6939 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6940
6941 // The other three cases all fold into an unsigned comparison.
6942 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006943 }
6944
6945 // If we aren't dealing with a constant on the RHS, exit early
6946 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6947 if (!CI)
6948 return 0;
6949
6950 // Compute the constant that would happen if we truncated to SrcTy then
6951 // reextended to DestTy.
6952 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6953 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6954
6955 // If the re-extended constant didn't change...
6956 if (Res2 == CI) {
6957 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6958 // For example, we might have:
6959 // %A = sext short %X to uint
6960 // %B = icmp ugt uint %A, 1330
6961 // It is incorrect to transform this into
6962 // %B = icmp ugt short %X, 1330
6963 // because %A may have negative value.
6964 //
Chris Lattner3d816532008-07-11 04:09:09 +00006965 // However, we allow this when the compare is EQ/NE, because they are
6966 // signless.
6967 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006968 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00006969 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006970 }
6971
6972 // The re-extended constant changed so the constant cannot be represented
6973 // in the shorter type. Consequently, we cannot emit a simple comparison.
6974
6975 // First, handle some easy cases. We know the result cannot be equal at this
6976 // point so handle the ICI.isEquality() cases
6977 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6978 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6979 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6980 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6981
6982 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6983 // should have been folded away previously and not enter in here.
6984 Value *Result;
6985 if (isSignedCmp) {
6986 // We're performing a signed comparison.
6987 if (cast<ConstantInt>(CI)->getValue().isNegative())
6988 Result = ConstantInt::getFalse(); // X < (small) --> false
6989 else
6990 Result = ConstantInt::getTrue(); // X < (large) --> true
6991 } else {
6992 // We're performing an unsigned comparison.
6993 if (isSignedExt) {
6994 // We're performing an unsigned comp with a sign extended value.
6995 // This is true if the input is >= 0. [aka >s -1]
6996 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6997 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6998 NegOne, ICI.getName()), ICI);
6999 } else {
7000 // Unsigned extend & unsigned compare -> always true.
7001 Result = ConstantInt::getTrue();
7002 }
7003 }
7004
7005 // Finally, return the value computed.
7006 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007007 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007008 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007009
7010 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7011 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7012 "ICmp should be folded!");
7013 if (Constant *CI = dyn_cast<Constant>(Result))
7014 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7015 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007016}
7017
7018Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7019 return commonShiftTransforms(I);
7020}
7021
7022Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7023 return commonShiftTransforms(I);
7024}
7025
7026Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007027 if (Instruction *R = commonShiftTransforms(I))
7028 return R;
7029
7030 Value *Op0 = I.getOperand(0);
7031
7032 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7033 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7034 if (CSI->isAllOnesValue())
7035 return ReplaceInstUsesWith(I, CSI);
7036
7037 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnercd25ebd2009-03-18 16:32:19 +00007038 if (!isa<VectorType>(I.getType())) {
7039 if (MaskedValueIsZero(Op0,
Chris Lattnere3c504f2007-12-06 01:59:46 +00007040 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Chris Lattnercd25ebd2009-03-18 16:32:19 +00007041 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Dan Gohman843649e2009-02-24 02:00:40 +00007042
Chris Lattnercd25ebd2009-03-18 16:32:19 +00007043 // Arithmetic shifting an all-sign-bit value is a no-op.
7044 unsigned NumSignBits = ComputeNumSignBits(Op0);
7045 if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7046 return ReplaceInstUsesWith(I, Op0);
7047 }
Dan Gohman843649e2009-02-24 02:00:40 +00007048
Chris Lattnere3c504f2007-12-06 01:59:46 +00007049 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050}
7051
7052Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7053 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7055
7056 // shl X, 0 == X and shr X, 0 == X
7057 // shl 0, X == 0 and shr 0, X == 0
7058 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7059 Op0 == Constant::getNullValue(Op0->getType()))
7060 return ReplaceInstUsesWith(I, Op0);
7061
7062 if (isa<UndefValue>(Op0)) {
7063 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7064 return ReplaceInstUsesWith(I, Op0);
7065 else // undef << X -> 0, undef >>u X -> 0
7066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7067 }
7068 if (isa<UndefValue>(Op1)) {
7069 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7070 return ReplaceInstUsesWith(I, Op0);
7071 else // X << undef, X >>u undef -> 0
7072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7073 }
7074
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007075 // Try to fold constant and into select arguments.
7076 if (isa<Constant>(Op0))
7077 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7078 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7079 return R;
7080
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007081 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7082 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7083 return Res;
7084 return 0;
7085}
7086
7087Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7088 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007089 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007090
7091 // See if we can simplify any instructions used by the instruction whose sole
7092 // purpose is to compute bits we don't care about.
7093 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +00007094 if (SimplifyDemandedInstructionBits(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007095 return &I;
7096
7097 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7098 // of a signed value.
7099 //
7100 if (Op1->uge(TypeBits)) {
7101 if (I.getOpcode() != Instruction::AShr)
7102 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7103 else {
7104 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7105 return &I;
7106 }
7107 }
7108
7109 // ((X*C1) << C2) == (X * (C1 << C2))
7110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7111 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7112 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007113 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007114 ConstantExpr::getShl(BOOp, Op1));
7115
7116 // Try to fold constant and into select arguments.
7117 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7118 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7119 return R;
7120 if (isa<PHINode>(Op0))
7121 if (Instruction *NV = FoldOpIntoPhi(I))
7122 return NV;
7123
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007124 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7125 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7126 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7127 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7128 // place. Don't try to do this transformation in this case. Also, we
7129 // require that the input operand is a shift-by-constant so that we have
7130 // confidence that the shifts will get folded together. We could do this
7131 // xform in more cases, but it is unlikely to be profitable.
7132 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7133 isa<ConstantInt>(TrOp->getOperand(1))) {
7134 // Okay, we'll do this xform. Make the shift of shift.
7135 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007136 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007137 I.getName());
7138 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7139
7140 // For logical shifts, the truncation has the effect of making the high
7141 // part of the register be zeros. Emulate this by inserting an AND to
7142 // clear the top bits as needed. This 'and' will usually be zapped by
7143 // other xforms later if dead.
7144 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7145 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7146 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7147
7148 // The mask we constructed says what the trunc would do if occurring
7149 // between the shifts. We want to know the effect *after* the second
7150 // shift. We know that it is a logical shift by a constant, so adjust the
7151 // mask as appropriate.
7152 if (I.getOpcode() == Instruction::Shl)
7153 MaskV <<= Op1->getZExtValue();
7154 else {
7155 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7156 MaskV = MaskV.lshr(Op1->getZExtValue());
7157 }
7158
Gabor Greifa645dd32008-05-16 19:29:10 +00007159 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007160 TI->getName());
7161 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7162
7163 // Return the value truncated to the interesting size.
7164 return new TruncInst(And, I.getType());
7165 }
7166 }
7167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007168 if (Op0->hasOneUse()) {
7169 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7170 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7171 Value *V1, *V2;
7172 ConstantInt *CC;
7173 switch (Op0BO->getOpcode()) {
7174 default: break;
7175 case Instruction::Add:
7176 case Instruction::And:
7177 case Instruction::Or:
7178 case Instruction::Xor: {
7179 // These operators commute.
7180 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7181 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007182 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007183 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007184 Op0BO->getOperand(0), Op1,
7185 Op0BO->getName());
7186 InsertNewInstBefore(YS, I); // (Y << C)
7187 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007188 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007189 Op0BO->getOperand(1)->getName());
7190 InsertNewInstBefore(X, I); // (X + (Y << C))
7191 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007192 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007193 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7194 }
7195
7196 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7197 Value *Op0BOOp1 = Op0BO->getOperand(1);
7198 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7199 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007200 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7201 m_ConstantInt(CC))) &&
7202 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007203 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007204 Op0BO->getOperand(0), Op1,
7205 Op0BO->getName());
7206 InsertNewInstBefore(YS, I); // (Y << C)
7207 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007208 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007209 V1->getName()+".mask");
7210 InsertNewInstBefore(XM, I); // X & (CC << C)
7211
Gabor Greifa645dd32008-05-16 19:29:10 +00007212 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007213 }
7214 }
7215
7216 // FALL THROUGH.
7217 case Instruction::Sub: {
7218 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7219 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007220 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007221 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222 Op0BO->getOperand(1), Op1,
7223 Op0BO->getName());
7224 InsertNewInstBefore(YS, I); // (Y << C)
7225 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007226 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007227 Op0BO->getOperand(0)->getName());
7228 InsertNewInstBefore(X, I); // (X + (Y << C))
7229 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007230 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007231 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7232 }
7233
7234 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7235 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7236 match(Op0BO->getOperand(0),
7237 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7238 m_ConstantInt(CC))) && V2 == Op1 &&
7239 cast<BinaryOperator>(Op0BO->getOperand(0))
7240 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007241 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007242 Op0BO->getOperand(1), Op1,
7243 Op0BO->getName());
7244 InsertNewInstBefore(YS, I); // (Y << C)
7245 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007246 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007247 V1->getName()+".mask");
7248 InsertNewInstBefore(XM, I); // X & (CC << C)
7249
Gabor Greifa645dd32008-05-16 19:29:10 +00007250 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007251 }
7252
7253 break;
7254 }
7255 }
7256
7257
7258 // If the operand is an bitwise operator with a constant RHS, and the
7259 // shift is the only use, we can pull it out of the shift.
7260 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7261 bool isValid = true; // Valid only for And, Or, Xor
7262 bool highBitSet = false; // Transform if high bit of constant set?
7263
7264 switch (Op0BO->getOpcode()) {
7265 default: isValid = false; break; // Do not perform transform!
7266 case Instruction::Add:
7267 isValid = isLeftShift;
7268 break;
7269 case Instruction::Or:
7270 case Instruction::Xor:
7271 highBitSet = false;
7272 break;
7273 case Instruction::And:
7274 highBitSet = true;
7275 break;
7276 }
7277
7278 // If this is a signed shift right, and the high bit is modified
7279 // by the logical operation, do not perform the transformation.
7280 // The highBitSet boolean indicates the value of the high bit of
7281 // the constant which would cause it to be modified for this
7282 // operation.
7283 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007284 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007285 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286
7287 if (isValid) {
7288 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7289
7290 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007291 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007292 InsertNewInstBefore(NewShift, I);
7293 NewShift->takeName(Op0BO);
7294
Gabor Greifa645dd32008-05-16 19:29:10 +00007295 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 NewRHS);
7297 }
7298 }
7299 }
7300 }
7301
7302 // Find out if this is a shift of a shift by a constant.
7303 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7304 if (ShiftOp && !ShiftOp->isShift())
7305 ShiftOp = 0;
7306
7307 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7308 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7309 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7310 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7311 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7312 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7313 Value *X = ShiftOp->getOperand(0);
7314
7315 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007316
7317 const IntegerType *Ty = cast<IntegerType>(I.getType());
7318
7319 // Check for (X << c1) << c2 and (X >> c1) >> c2
7320 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007321 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7322 // saturates.
7323 if (AmtSum >= TypeBits) {
7324 if (I.getOpcode() != Instruction::AShr)
7325 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7326 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7327 }
7328
Gabor Greifa645dd32008-05-16 19:29:10 +00007329 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007330 ConstantInt::get(Ty, AmtSum));
7331 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7332 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007333 if (AmtSum >= TypeBits)
7334 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7335
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007336 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007337 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007338 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7339 I.getOpcode() == Instruction::LShr) {
7340 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007341 if (AmtSum >= TypeBits)
7342 AmtSum = TypeBits-1;
7343
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007344 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007345 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007346 InsertNewInstBefore(Shift, I);
7347
7348 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007349 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007350 }
7351
7352 // Okay, if we get here, one shift must be left, and the other shift must be
7353 // right. See if the amounts are equal.
7354 if (ShiftAmt1 == ShiftAmt2) {
7355 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7356 if (I.getOpcode() == Instruction::Shl) {
7357 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007358 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007359 }
7360 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7361 if (I.getOpcode() == Instruction::LShr) {
7362 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007363 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364 }
7365 // We can simplify ((X << C) >>s C) into a trunc + sext.
7366 // NOTE: we could do this for any C, but that would make 'unusual' integer
7367 // types. For now, just stick to ones well-supported by the code
7368 // generators.
7369 const Type *SExtType = 0;
7370 switch (Ty->getBitWidth() - ShiftAmt1) {
7371 case 1 :
7372 case 8 :
7373 case 16 :
7374 case 32 :
7375 case 64 :
7376 case 128:
7377 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7378 break;
7379 default: break;
7380 }
7381 if (SExtType) {
7382 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7383 InsertNewInstBefore(NewTrunc, I);
7384 return new SExtInst(NewTrunc, Ty);
7385 }
7386 // Otherwise, we can't handle it yet.
7387 } else if (ShiftAmt1 < ShiftAmt2) {
7388 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7389
7390 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7391 if (I.getOpcode() == Instruction::Shl) {
7392 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7393 ShiftOp->getOpcode() == Instruction::AShr);
7394 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007395 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396 InsertNewInstBefore(Shift, I);
7397
7398 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007399 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007400 }
7401
7402 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7403 if (I.getOpcode() == Instruction::LShr) {
7404 assert(ShiftOp->getOpcode() == Instruction::Shl);
7405 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007406 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007407 InsertNewInstBefore(Shift, I);
7408
7409 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007410 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007411 }
7412
7413 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7414 } else {
7415 assert(ShiftAmt2 < ShiftAmt1);
7416 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7417
7418 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7419 if (I.getOpcode() == Instruction::Shl) {
7420 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7421 ShiftOp->getOpcode() == Instruction::AShr);
7422 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007423 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007424 ConstantInt::get(Ty, ShiftDiff));
7425 InsertNewInstBefore(Shift, I);
7426
7427 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007428 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007429 }
7430
7431 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7432 if (I.getOpcode() == Instruction::LShr) {
7433 assert(ShiftOp->getOpcode() == Instruction::Shl);
7434 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007435 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007436 InsertNewInstBefore(Shift, I);
7437
7438 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007439 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007440 }
7441
7442 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7443 }
7444 }
7445 return 0;
7446}
7447
7448
7449/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7450/// expression. If so, decompose it, returning some value X, such that Val is
7451/// X*Scale+Offset.
7452///
7453static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7454 int &Offset) {
7455 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7456 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7457 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007458 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007459 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007460 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7461 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7462 if (I->getOpcode() == Instruction::Shl) {
7463 // This is a value scaled by '1 << the shift amt'.
7464 Scale = 1U << RHS->getZExtValue();
7465 Offset = 0;
7466 return I->getOperand(0);
7467 } else if (I->getOpcode() == Instruction::Mul) {
7468 // This value is scaled by 'RHS'.
7469 Scale = RHS->getZExtValue();
7470 Offset = 0;
7471 return I->getOperand(0);
7472 } else if (I->getOpcode() == Instruction::Add) {
7473 // We have X+C. Check to see if we really have (X*C2)+C1,
7474 // where C1 is divisible by C2.
7475 unsigned SubScale;
7476 Value *SubVal =
7477 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7478 Offset += RHS->getZExtValue();
7479 Scale = SubScale;
7480 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007481 }
7482 }
7483 }
7484
7485 // Otherwise, we can't look past this.
7486 Scale = 1;
7487 Offset = 0;
7488 return Val;
7489}
7490
7491
7492/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7493/// try to eliminate the cast by moving the type information into the alloc.
7494Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7495 AllocationInst &AI) {
7496 const PointerType *PTy = cast<PointerType>(CI.getType());
7497
7498 // Remove any uses of AI that are dead.
7499 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7500
7501 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7502 Instruction *User = cast<Instruction>(*UI++);
7503 if (isInstructionTriviallyDead(User)) {
7504 while (UI != E && *UI == User)
7505 ++UI; // If this instruction uses AI more than once, don't break UI.
7506
7507 ++NumDeadInst;
7508 DOUT << "IC: DCE: " << *User;
7509 EraseInstFromFunction(*User);
7510 }
7511 }
7512
7513 // Get the type really allocated and the type casted to.
7514 const Type *AllocElTy = AI.getAllocatedType();
7515 const Type *CastElTy = PTy->getElementType();
7516 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7517
7518 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7519 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7520 if (CastElTyAlign < AllocElTyAlign) return 0;
7521
7522 // If the allocation has multiple uses, only promote it if we are strictly
7523 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007524 // same, we open the door to infinite loops of various kinds. (A reference
7525 // from a dbg.declare doesn't count as a use for this purpose.)
7526 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7527 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007528
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007529 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7530 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7532
7533 // See if we can satisfy the modulus by pulling a scale out of the array
7534 // size argument.
7535 unsigned ArraySizeScale;
7536 int ArrayOffset;
7537 Value *NumElements = // See if the array size is a decomposable linear expr.
7538 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7539
7540 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7541 // do the xform.
7542 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7543 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7544
7545 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7546 Value *Amt = 0;
7547 if (Scale == 1) {
7548 Amt = NumElements;
7549 } else {
7550 // If the allocation size is constant, form a constant mul expression
7551 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7552 if (isa<ConstantInt>(NumElements))
7553 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7554 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007555 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007556 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007557 Amt = InsertNewInstBefore(Tmp, AI);
7558 }
7559 }
7560
7561 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7562 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007563 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007564 Amt = InsertNewInstBefore(Tmp, AI);
7565 }
7566
7567 AllocationInst *New;
7568 if (isa<MallocInst>(AI))
7569 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7570 else
7571 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7572 InsertNewInstBefore(New, AI);
7573 New->takeName(&AI);
7574
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007575 // If the allocation has one real use plus a dbg.declare, just remove the
7576 // declare.
7577 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7578 EraseInstFromFunction(*DI);
7579 }
7580 // If the allocation has multiple real uses, insert a cast and change all
7581 // things that used it to use the new cast. This will also hack on CI, but it
7582 // will die soon.
7583 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007584 AddUsesToWorkList(AI);
7585 // New is the allocation instruction, pointer typed. AI is the original
7586 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7587 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7588 InsertNewInstBefore(NewCast, AI);
7589 AI.replaceAllUsesWith(NewCast);
7590 }
7591 return ReplaceInstUsesWith(CI, New);
7592}
7593
7594/// CanEvaluateInDifferentType - Return true if we can take the specified value
7595/// and return it as type Ty without inserting any new casts and without
7596/// changing the computed value. This is used by code that tries to decide
7597/// whether promoting or shrinking integer operations to wider or smaller types
7598/// will allow us to eliminate a truncate or extend.
7599///
7600/// This is a truncation operation if Ty is smaller than V->getType(), or an
7601/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007602///
7603/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7604/// should return true if trunc(V) can be computed by computing V in the smaller
7605/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7606/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7607/// efficiently truncated.
7608///
7609/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7610/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7611/// the final result.
Evan Cheng814a00c2009-01-16 02:11:43 +00007612bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7613 unsigned CastOpc,
7614 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007615 // We can always evaluate constants in another type.
7616 if (isa<ConstantInt>(V))
7617 return true;
7618
7619 Instruction *I = dyn_cast<Instruction>(V);
7620 if (!I) return false;
7621
7622 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7623
Chris Lattneref70bb82007-08-02 06:11:14 +00007624 // If this is an extension or truncate, we can often eliminate it.
7625 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7626 // If this is a cast from the destination type, we can trivially eliminate
7627 // it, and this will remove a cast overall.
7628 if (I->getOperand(0)->getType() == Ty) {
7629 // If the first operand is itself a cast, and is eliminable, do not count
7630 // this as an eliminable cast. We would prefer to eliminate those two
7631 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007632 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007633 ++NumCastsRemoved;
7634 return true;
7635 }
7636 }
7637
7638 // We can't extend or shrink something that has multiple uses: doing so would
7639 // require duplicating the instruction in general, which isn't profitable.
7640 if (!I->hasOneUse()) return false;
7641
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007642 unsigned Opc = I->getOpcode();
7643 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007644 case Instruction::Add:
7645 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007646 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 case Instruction::And:
7648 case Instruction::Or:
7649 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007650 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007651 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007652 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007653 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007654 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655
7656 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007657 // If we are truncating the result of this SHL, and if it's a shift of a
7658 // constant amount, we can always perform a SHL in a smaller type.
7659 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7660 uint32_t BitWidth = Ty->getBitWidth();
7661 if (BitWidth < OrigTy->getBitWidth() &&
7662 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007663 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007664 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007665 }
7666 break;
7667 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007668 // If this is a truncate of a logical shr, we can truncate it to a smaller
7669 // lshr iff we know that the bits we would otherwise be shifting in are
7670 // already zeros.
7671 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7672 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7673 uint32_t BitWidth = Ty->getBitWidth();
7674 if (BitWidth < OrigBitWidth &&
7675 MaskedValueIsZero(I->getOperand(0),
7676 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7677 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007678 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007679 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007680 }
7681 }
7682 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007683 case Instruction::ZExt:
7684 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007685 case Instruction::Trunc:
7686 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007687 // can safely replace it. Note that replacing it does not reduce the number
7688 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007689 if (Opc == CastOpc)
7690 return true;
7691
7692 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007693 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007694 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007695 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007696 case Instruction::Select: {
7697 SelectInst *SI = cast<SelectInst>(I);
7698 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007699 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007700 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007701 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007702 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007703 case Instruction::PHI: {
7704 // We can change a phi if we can change all operands.
7705 PHINode *PN = cast<PHINode>(I);
7706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7707 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007708 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007709 return false;
7710 return true;
7711 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007712 default:
7713 // TODO: Can handle more cases here.
7714 break;
7715 }
7716
7717 return false;
7718}
7719
7720/// EvaluateInDifferentType - Given an expression that
7721/// CanEvaluateInDifferentType returns true for, actually insert the code to
7722/// evaluate the expression.
7723Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7724 bool isSigned) {
7725 if (Constant *C = dyn_cast<Constant>(V))
7726 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7727
7728 // Otherwise, it must be an instruction.
7729 Instruction *I = cast<Instruction>(V);
7730 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007731 unsigned Opc = I->getOpcode();
7732 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007733 case Instruction::Add:
7734 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007735 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007736 case Instruction::And:
7737 case Instruction::Or:
7738 case Instruction::Xor:
7739 case Instruction::AShr:
7740 case Instruction::LShr:
7741 case Instruction::Shl: {
7742 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7743 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007744 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007745 break;
7746 }
7747 case Instruction::Trunc:
7748 case Instruction::ZExt:
7749 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007750 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007751 // just return the source. There's no need to insert it because it is not
7752 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007753 if (I->getOperand(0)->getType() == Ty)
7754 return I->getOperand(0);
7755
Chris Lattner4200c2062008-06-18 04:00:49 +00007756 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007757 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007758 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007759 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007760 case Instruction::Select: {
7761 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7762 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7763 Res = SelectInst::Create(I->getOperand(0), True, False);
7764 break;
7765 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007766 case Instruction::PHI: {
7767 PHINode *OPN = cast<PHINode>(I);
7768 PHINode *NPN = PHINode::Create(Ty);
7769 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7770 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7771 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7772 }
7773 Res = NPN;
7774 break;
7775 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007776 default:
7777 // TODO: Can handle more cases here.
7778 assert(0 && "Unreachable!");
7779 break;
7780 }
7781
Chris Lattner4200c2062008-06-18 04:00:49 +00007782 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007783 return InsertNewInstBefore(Res, *I);
7784}
7785
7786/// @brief Implement the transforms common to all CastInst visitors.
7787Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7788 Value *Src = CI.getOperand(0);
7789
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007790 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7791 // eliminate it now.
7792 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7793 if (Instruction::CastOps opc =
7794 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7795 // The first cast (CSrc) is eliminable so we need to fix up or replace
7796 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007797 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007798 }
7799 }
7800
7801 // If we are casting a select then fold the cast into the select
7802 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7803 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7804 return NV;
7805
7806 // If we are casting a PHI then fold the cast into the PHI
7807 if (isa<PHINode>(Src))
7808 if (Instruction *NV = FoldOpIntoPhi(CI))
7809 return NV;
7810
7811 return 0;
7812}
7813
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007814/// FindElementAtOffset - Given a type and a constant offset, determine whether
7815/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00007816/// the specified offset. If so, fill them into NewIndices and return the
7817/// resultant element type, otherwise return null.
7818static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7819 SmallVectorImpl<Value*> &NewIndices,
7820 const TargetData *TD) {
7821 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007822
7823 // Start with the index over the outer type. Note that the type size
7824 // might be zero (even if the offset isn't zero) if the indexed type
7825 // is something like [0 x {int, int}]
7826 const Type *IntPtrTy = TD->getIntPtrType();
7827 int64_t FirstIdx = 0;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007828 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007829 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00007830 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007831
Chris Lattnerce48c462009-01-11 20:15:20 +00007832 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007833 if (Offset < 0) {
7834 --FirstIdx;
7835 Offset += TySize;
7836 assert(Offset >= 0);
7837 }
7838 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7839 }
7840
7841 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7842
7843 // Index into the types. If we fail, set OrigBase to null.
7844 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00007845 // Indexing into tail padding between struct/array elements.
7846 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00007847 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00007848
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007849 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7850 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00007851 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7852 "Offset must stay within the indexed type");
7853
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007854 unsigned Elt = SL->getElementContainingOffset(Offset);
7855 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7856
7857 Offset -= SL->getElementOffset(Elt);
7858 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007859 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007860 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00007861 assert(EltSize && "Cannot index into a zero-sized array");
7862 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7863 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007864 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007865 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00007866 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00007867 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007868 }
7869 }
7870
Chris Lattner54dddc72009-01-24 01:00:13 +00007871 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007872}
7873
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007874/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7875Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7876 Value *Src = CI.getOperand(0);
7877
7878 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7879 // If casting the result of a getelementptr instruction with no offset, turn
7880 // this into a cast of the original pointer!
7881 if (GEP->hasAllZeroIndices()) {
7882 // Changing the cast operand is usually not a good idea but it is safe
7883 // here because the pointer operand is being replaced with another
7884 // pointer operand so the opcode doesn't need to change.
7885 AddToWorkList(GEP);
7886 CI.setOperand(0, GEP->getOperand(0));
7887 return &CI;
7888 }
7889
7890 // If the GEP has a single use, and the base pointer is a bitcast, and the
7891 // GEP computes a constant offset, see if we can convert these three
7892 // instructions into fewer. This typically happens with unions and other
7893 // non-type-safe code.
7894 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7895 if (GEP->hasAllConstantIndices()) {
7896 // We are guaranteed to get a constant from EmitGEPOffset.
7897 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7898 int64_t Offset = OffsetV->getSExtValue();
7899
7900 // Get the base pointer input of the bitcast, and the type it points to.
7901 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7902 const Type *GEPIdxTy =
7903 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007904 SmallVector<Value*, 8> NewIndices;
7905 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7906 // If we were able to index down into an element, create the GEP
7907 // and bitcast the result. This eliminates one bitcast, potentially
7908 // two.
7909 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7910 NewIndices.begin(),
7911 NewIndices.end(), "");
7912 InsertNewInstBefore(NGEP, CI);
7913 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007914
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007915 if (isa<BitCastInst>(CI))
7916 return new BitCastInst(NGEP, CI.getType());
7917 assert(isa<PtrToIntInst>(CI));
7918 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007919 }
7920 }
7921 }
7922 }
7923
7924 return commonCastTransforms(CI);
7925}
7926
7927
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7929/// integer types. This function implements the common transforms for all those
7930/// cases.
7931/// @brief Implement the transforms common to CastInst with integer operands
7932Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7933 if (Instruction *Result = commonCastTransforms(CI))
7934 return Result;
7935
7936 Value *Src = CI.getOperand(0);
7937 const Type *SrcTy = Src->getType();
7938 const Type *DestTy = CI.getType();
7939 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7940 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7941
7942 // See if we can simplify any instructions used by the LHS whose sole
7943 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00007944 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007945 return &CI;
7946
7947 // If the source isn't an instruction or has more than one use then we
7948 // can't do anything more.
7949 Instruction *SrcI = dyn_cast<Instruction>(Src);
7950 if (!SrcI || !Src->hasOneUse())
7951 return 0;
7952
7953 // Attempt to propagate the cast into the instruction for int->int casts.
7954 int NumCastsRemoved = 0;
7955 if (!isa<BitCastInst>(CI) &&
7956 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng814a00c2009-01-16 02:11:43 +00007957 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007958 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007959 // eliminates the cast, so it is always a win. If this is a zero-extension,
7960 // we need to do an AND to maintain the clear top-part of the computation,
7961 // so we require that the input have eliminated at least one cast. If this
7962 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007963 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007964 bool DoXForm = false;
7965 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007966 switch (CI.getOpcode()) {
7967 default:
7968 // All the others use floating point so we shouldn't actually
7969 // get here because of the check above.
7970 assert(0 && "Unknown cast type");
7971 case Instruction::Trunc:
7972 DoXForm = true;
7973 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007974 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00007976 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00007977 // If it's unnecessary to issue an AND to clear the high bits, it's
7978 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00007979 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00007980 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7981 if (MaskedValueIsZero(TryRes, Mask))
7982 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00007983
7984 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00007985 if (TryI->use_empty())
7986 EraseInstFromFunction(*TryI);
7987 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007988 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007989 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007990 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007991 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00007992 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00007993 // If we do not have to emit the truncate + sext pair, then it's always
7994 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007995 //
7996 // It's not safe to eliminate the trunc + sext pair if one of the
7997 // eliminated cast is a truncate. e.g.
7998 // t2 = trunc i32 t1 to i16
7999 // t3 = sext i16 t2 to i32
8000 // !=
8001 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008002 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008003 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8004 if (NumSignBits > (DestBitSize - SrcBitSize))
8005 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008006
8007 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008008 if (TryI->use_empty())
8009 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008011 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008012 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008014
8015 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008016 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8017 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008018 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8019 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008020 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008021 // Just replace this cast with the result.
8022 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008024 assert(Res->getType() == DestTy);
8025 switch (CI.getOpcode()) {
8026 default: assert(0 && "Unknown cast type!");
8027 case Instruction::Trunc:
8028 case Instruction::BitCast:
8029 // Just replace this cast with the result.
8030 return ReplaceInstUsesWith(CI, Res);
8031 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008032 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008033
8034 // If the high bits are already zero, just replace this cast with the
8035 // result.
8036 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8037 if (MaskedValueIsZero(Res, Mask))
8038 return ReplaceInstUsesWith(CI, Res);
8039
8040 // We need to emit an AND to clear the high bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008041 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8042 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008043 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008044 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008045 case Instruction::SExt: {
8046 // If the high bits are already filled with sign bit, just replace this
8047 // cast with the result.
8048 unsigned NumSignBits = ComputeNumSignBits(Res);
8049 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008050 return ReplaceInstUsesWith(CI, Res);
8051
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008052 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008053 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008054 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8055 CI), DestTy);
8056 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008057 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008058 }
8059 }
8060
8061 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8062 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8063
8064 switch (SrcI->getOpcode()) {
8065 case Instruction::Add:
8066 case Instruction::Mul:
8067 case Instruction::And:
8068 case Instruction::Or:
8069 case Instruction::Xor:
8070 // If we are discarding information, rewrite.
8071 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8072 // Don't insert two casts if they cannot be eliminated. We allow
8073 // two casts to be inserted if the sizes are the same. This could
8074 // only be converting signedness, which is a noop.
8075 if (DestBitSize == SrcBitSize ||
8076 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8077 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8078 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00008079 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8080 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008081 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008082 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8083 }
8084 }
8085
8086 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8087 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8088 SrcI->getOpcode() == Instruction::Xor &&
8089 Op1 == ConstantInt::getTrue() &&
8090 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008091 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008092 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008093 }
8094 break;
8095 case Instruction::SDiv:
8096 case Instruction::UDiv:
8097 case Instruction::SRem:
8098 case Instruction::URem:
8099 // If we are just changing the sign, rewrite.
8100 if (DestBitSize == SrcBitSize) {
8101 // Don't insert two casts if they cannot be eliminated. We allow
8102 // two casts to be inserted if the sizes are the same. This could
8103 // only be converting signedness, which is a noop.
8104 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8105 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008106 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8107 Op0, DestTy, *SrcI);
8108 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8109 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008110 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008111 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8112 }
8113 }
8114 break;
8115
8116 case Instruction::Shl:
8117 // Allow changing the sign of the source operand. Do not allow
8118 // changing the size of the shift, UNLESS the shift amount is a
8119 // constant. We must not change variable sized shifts to a smaller
8120 // size, because it is undefined to shift more bits out than exist
8121 // in the value.
8122 if (DestBitSize == SrcBitSize ||
8123 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8124 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8125 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00008126 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8127 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008128 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 }
8130 break;
8131 case Instruction::AShr:
8132 // If this is a signed shr, and if all bits shifted in are about to be
8133 // truncated off, turn it into an unsigned shr to allow greater
8134 // simplifications.
8135 if (DestBitSize < SrcBitSize &&
8136 isa<ConstantInt>(Op1)) {
8137 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8138 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8139 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00008140 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008141 }
8142 }
8143 break;
8144 }
8145 return 0;
8146}
8147
8148Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8149 if (Instruction *Result = commonIntCastTransforms(CI))
8150 return Result;
8151
8152 Value *Src = CI.getOperand(0);
8153 const Type *Ty = CI.getType();
8154 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8155 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner32177f82009-03-24 18:15:30 +00008156
8157 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8158 if (DestBitWidth == 1) {
8159 Constant *One = ConstantInt::get(Src->getType(), 1);
8160 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8161 Value *Zero = Constant::getNullValue(Src->getType());
8162 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8163 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008164
Chris Lattner32177f82009-03-24 18:15:30 +00008165 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8166 ConstantInt *ShAmtV = 0;
8167 Value *ShiftOp = 0;
8168 if (Src->hasOneUse() &&
8169 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8170 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8171
8172 // Get a mask for the bits shifting in.
8173 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8174 if (MaskedValueIsZero(ShiftOp, Mask)) {
8175 if (ShAmt >= DestBitWidth) // All zeros.
8176 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8177
8178 // Okay, we can shrink this. Truncate the input, then return a new
8179 // shift.
8180 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8181 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8182 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183 }
8184 }
8185
8186 return 0;
8187}
8188
Evan Chenge3779cf2008-03-24 00:21:34 +00008189/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8190/// in order to eliminate the icmp.
8191Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8192 bool DoXform) {
8193 // If we are just checking for a icmp eq of a single bit and zext'ing it
8194 // to an integer, then shift the bit to the appropriate place and then
8195 // cast to integer to avoid the comparison.
8196 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8197 const APInt &Op1CV = Op1C->getValue();
8198
8199 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8200 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8201 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8202 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8203 if (!DoXform) return ICI;
8204
8205 Value *In = ICI->getOperand(0);
8206 Value *Sh = ConstantInt::get(In->getType(),
8207 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008208 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008209 In->getName()+".lobit"),
8210 CI);
8211 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008212 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008213 false/*ZExt*/, "tmp", &CI);
8214
8215 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8216 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008217 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008218 In->getName()+".not"),
8219 CI);
8220 }
8221
8222 return ReplaceInstUsesWith(CI, In);
8223 }
8224
8225
8226
8227 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8228 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8229 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8230 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8231 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8232 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8233 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8234 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8235 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8236 // This only works for EQ and NE
8237 ICI->isEquality()) {
8238 // If Op1C some other power of two, convert:
8239 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8240 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8241 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8242 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8243
8244 APInt KnownZeroMask(~KnownZero);
8245 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8246 if (!DoXform) return ICI;
8247
8248 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8249 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8250 // (X&4) == 2 --> false
8251 // (X&4) != 2 --> true
8252 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8253 Res = ConstantExpr::getZExt(Res, CI.getType());
8254 return ReplaceInstUsesWith(CI, Res);
8255 }
8256
8257 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8258 Value *In = ICI->getOperand(0);
8259 if (ShiftAmt) {
8260 // Perform a logical shr by shiftamt.
8261 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008262 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008263 ConstantInt::get(In->getType(), ShiftAmt),
8264 In->getName()+".lobit"), CI);
8265 }
8266
8267 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8268 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008269 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008270 InsertNewInstBefore(cast<Instruction>(In), CI);
8271 }
8272
8273 if (CI.getType() == In->getType())
8274 return ReplaceInstUsesWith(CI, In);
8275 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008276 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008277 }
8278 }
8279 }
8280
8281 return 0;
8282}
8283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8285 // If one of the common conversion will work ..
8286 if (Instruction *Result = commonIntCastTransforms(CI))
8287 return Result;
8288
8289 Value *Src = CI.getOperand(0);
8290
Chris Lattner215d56e2009-02-17 20:47:23 +00008291 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8292 // types and if the sizes are just right we can convert this into a logical
8293 // 'and' which will be much cheaper than the pair of casts.
8294 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8295 // Get the sizes of the types involved. We know that the intermediate type
8296 // will be smaller than A or C, but don't know the relation between A and C.
8297 Value *A = CSrc->getOperand(0);
8298 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8299 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8300 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8301 // If we're actually extending zero bits, then if
8302 // SrcSize < DstSize: zext(a & mask)
8303 // SrcSize == DstSize: a & mask
8304 // SrcSize > DstSize: trunc(a) & mask
8305 if (SrcSize < DstSize) {
8306 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8307 Constant *AndConst = ConstantInt::get(AndValue);
8308 Instruction *And =
8309 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8310 InsertNewInstBefore(And, CI);
8311 return new ZExtInst(And, CI.getType());
8312 } else if (SrcSize == DstSize) {
8313 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8314 return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8315 } else if (SrcSize > DstSize) {
8316 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8317 InsertNewInstBefore(Trunc, CI);
8318 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8319 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008320 }
8321 }
8322
Evan Chenge3779cf2008-03-24 00:21:34 +00008323 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8324 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325
Evan Chenge3779cf2008-03-24 00:21:34 +00008326 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8327 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8328 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8329 // of the (zext icmp) will be transformed.
8330 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8331 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8332 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8333 (transformZExtICmp(LHS, CI, false) ||
8334 transformZExtICmp(RHS, CI, false))) {
8335 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8336 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008337 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008338 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008339 }
8340
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341 return 0;
8342}
8343
8344Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8345 if (Instruction *I = commonIntCastTransforms(CI))
8346 return I;
8347
8348 Value *Src = CI.getOperand(0);
8349
Dan Gohman35b76162008-10-30 20:40:10 +00008350 // Canonicalize sign-extend from i1 to a select.
8351 if (Src->getType() == Type::Int1Ty)
8352 return SelectInst::Create(Src,
8353 ConstantInt::getAllOnesValue(CI.getType()),
8354 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008355
8356 // See if the value being truncated is already sign extended. If so, just
8357 // eliminate the trunc/sext pair.
8358 if (getOpcode(Src) == Instruction::Trunc) {
8359 Value *Op = cast<User>(Src)->getOperand(0);
8360 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8361 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8362 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8363 unsigned NumSignBits = ComputeNumSignBits(Op);
8364
8365 if (OpBits == DestBits) {
8366 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8367 // bits, it is already ready.
8368 if (NumSignBits > DestBits-MidBits)
8369 return ReplaceInstUsesWith(CI, Op);
8370 } else if (OpBits < DestBits) {
8371 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8372 // bits, just sext from i32.
8373 if (NumSignBits > OpBits-MidBits)
8374 return new SExtInst(Op, CI.getType(), "tmp");
8375 } else {
8376 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8377 // bits, just truncate to i32.
8378 if (NumSignBits > OpBits-MidBits)
8379 return new TruncInst(Op, CI.getType(), "tmp");
8380 }
8381 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008382
8383 // If the input is a shl/ashr pair of a same constant, then this is a sign
8384 // extension from a smaller value. If we could trust arbitrary bitwidth
8385 // integers, we could turn this into a truncate to the smaller bit and then
8386 // use a sext for the whole extension. Since we don't, look deeper and check
8387 // for a truncate. If the source and dest are the same type, eliminate the
8388 // trunc and extend and just do shifts. For example, turn:
8389 // %a = trunc i32 %i to i8
8390 // %b = shl i8 %a, 6
8391 // %c = ashr i8 %b, 6
8392 // %d = sext i8 %c to i32
8393 // into:
8394 // %a = shl i32 %i, 30
8395 // %d = ashr i32 %a, 30
8396 Value *A = 0;
8397 ConstantInt *BA = 0, *CA = 0;
8398 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8399 m_ConstantInt(CA))) &&
8400 BA == CA && isa<TruncInst>(A)) {
8401 Value *I = cast<TruncInst>(A)->getOperand(0);
8402 if (I->getType() == CI.getType()) {
8403 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8404 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8405 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8406 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8407 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8408 CI.getName()), CI);
8409 return BinaryOperator::CreateAShr(I, ShAmtV);
8410 }
8411 }
8412
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 return 0;
8414}
8415
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008416/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8417/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008418static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008419 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008420 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008421 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8422 if (!losesInfo)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008423 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008424 return 0;
8425}
8426
8427/// LookThroughFPExtensions - If this is an fp extension instruction, look
8428/// through it until we get the source value.
8429static Value *LookThroughFPExtensions(Value *V) {
8430 if (Instruction *I = dyn_cast<Instruction>(V))
8431 if (I->getOpcode() == Instruction::FPExt)
8432 return LookThroughFPExtensions(I->getOperand(0));
8433
8434 // If this value is a constant, return the constant in the smallest FP type
8435 // that can accurately represent it. This allows us to turn
8436 // (float)((double)X+2.0) into x+2.0f.
8437 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8438 if (CFP->getType() == Type::PPC_FP128Ty)
8439 return V; // No constant folding of this.
8440 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008441 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008442 return V;
8443 if (CFP->getType() == Type::DoubleTy)
8444 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008445 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008446 return V;
8447 // Don't try to shrink to various long double types.
8448 }
8449
8450 return V;
8451}
8452
8453Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8454 if (Instruction *I = commonCastTransforms(CI))
8455 return I;
8456
8457 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8458 // smaller than the destination type, we can eliminate the truncate by doing
8459 // the add as the smaller type. This applies to add/sub/mul/div as well as
8460 // many builtins (sqrt, etc).
8461 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8462 if (OpI && OpI->hasOneUse()) {
8463 switch (OpI->getOpcode()) {
8464 default: break;
8465 case Instruction::Add:
8466 case Instruction::Sub:
8467 case Instruction::Mul:
8468 case Instruction::FDiv:
8469 case Instruction::FRem:
8470 const Type *SrcTy = OpI->getType();
8471 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8472 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8473 if (LHSTrunc->getType() != SrcTy &&
8474 RHSTrunc->getType() != SrcTy) {
8475 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8476 // If the source types were both smaller than the destination type of
8477 // the cast, do this xform.
8478 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8479 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8480 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8481 CI.getType(), CI);
8482 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8483 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008484 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008485 }
8486 }
8487 break;
8488 }
8489 }
8490 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008491}
8492
8493Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8494 return commonCastTransforms(CI);
8495}
8496
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008497Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008498 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8499 if (OpI == 0)
8500 return commonCastTransforms(FI);
8501
8502 // fptoui(uitofp(X)) --> X
8503 // fptoui(sitofp(X)) --> X
8504 // This is safe if the intermediate type has enough bits in its mantissa to
8505 // accurately represent all values of X. For example, do not do this with
8506 // i64->float->i64. This is also safe for sitofp case, because any negative
8507 // 'X' value would cause an undefined result for the fptoui.
8508 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8509 OpI->getOperand(0)->getType() == FI.getType() &&
8510 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8511 OpI->getType()->getFPMantissaWidth())
8512 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008513
8514 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008515}
8516
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008517Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008518 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8519 if (OpI == 0)
8520 return commonCastTransforms(FI);
8521
8522 // fptosi(sitofp(X)) --> X
8523 // fptosi(uitofp(X)) --> X
8524 // This is safe if the intermediate type has enough bits in its mantissa to
8525 // accurately represent all values of X. For example, do not do this with
8526 // i64->float->i64. This is also safe for sitofp case, because any negative
8527 // 'X' value would cause an undefined result for the fptoui.
8528 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8529 OpI->getOperand(0)->getType() == FI.getType() &&
8530 (int)FI.getType()->getPrimitiveSizeInBits() <=
8531 OpI->getType()->getFPMantissaWidth())
8532 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008533
8534 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008535}
8536
8537Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8538 return commonCastTransforms(CI);
8539}
8540
8541Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8542 return commonCastTransforms(CI);
8543}
8544
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008545Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8546 // If the destination integer type is smaller than the intptr_t type for
8547 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8548 // trunc to be exposed to other transforms. Don't do this for extending
8549 // ptrtoint's, because we don't know if the target sign or zero extends its
8550 // pointers.
8551 if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8552 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8553 TD->getIntPtrType(),
8554 "tmp"), CI);
8555 return new TruncInst(P, CI.getType());
8556 }
8557
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008558 return commonPointerCastTransforms(CI);
8559}
8560
Chris Lattner7c1626482008-01-08 07:23:51 +00008561Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008562 // If the source integer type is larger than the intptr_t type for
8563 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8564 // allows the trunc to be exposed to other transforms. Don't do this for
8565 // extending inttoptr's, because we don't know if the target sign or zero
8566 // extends to pointers.
8567 if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8568 TD->getPointerSizeInBits()) {
8569 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8570 TD->getIntPtrType(),
8571 "tmp"), CI);
8572 return new IntToPtrInst(P, CI.getType());
8573 }
8574
Chris Lattner7c1626482008-01-08 07:23:51 +00008575 if (Instruction *I = commonCastTransforms(CI))
8576 return I;
8577
8578 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8579 if (!DestPointee->isSized()) return 0;
8580
8581 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8582 ConstantInt *Cst;
8583 Value *X;
8584 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8585 m_ConstantInt(Cst)))) {
8586 // If the source and destination operands have the same type, see if this
8587 // is a single-index GEP.
8588 if (X->getType() == CI.getType()) {
8589 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008590 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008591
8592 // Convert the constant to intptr type.
8593 APInt Offset = Cst->getValue();
8594 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8595
8596 // If Offset is evenly divisible by Size, we can do this xform.
8597 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8598 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008599 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008600 }
8601 }
8602 // TODO: Could handle other cases, e.g. where add is indexing into field of
8603 // struct etc.
8604 } else if (CI.getOperand(0)->hasOneUse() &&
8605 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8606 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8607 // "inttoptr+GEP" instead of "add+intptr".
8608
8609 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008610 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008611
8612 // Convert the constant to intptr type.
8613 APInt Offset = Cst->getValue();
8614 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8615
8616 // If Offset is evenly divisible by Size, we can do this xform.
8617 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8618 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8619
8620 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8621 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008622 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008623 }
8624 }
8625 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008626}
8627
8628Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8629 // If the operands are integer typed then apply the integer transforms,
8630 // otherwise just apply the common ones.
8631 Value *Src = CI.getOperand(0);
8632 const Type *SrcTy = Src->getType();
8633 const Type *DestTy = CI.getType();
8634
8635 if (SrcTy->isInteger() && DestTy->isInteger()) {
8636 if (Instruction *Result = commonIntCastTransforms(CI))
8637 return Result;
8638 } else if (isa<PointerType>(SrcTy)) {
8639 if (Instruction *I = commonPointerCastTransforms(CI))
8640 return I;
8641 } else {
8642 if (Instruction *Result = commonCastTransforms(CI))
8643 return Result;
8644 }
8645
8646
8647 // Get rid of casts from one type to the same type. These are useless and can
8648 // be replaced by the operand.
8649 if (DestTy == Src->getType())
8650 return ReplaceInstUsesWith(CI, Src);
8651
8652 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8653 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8654 const Type *DstElTy = DstPTy->getElementType();
8655 const Type *SrcElTy = SrcPTy->getElementType();
8656
Nate Begemandf5b3612008-03-31 00:22:16 +00008657 // If the address spaces don't match, don't eliminate the bitcast, which is
8658 // required for changing types.
8659 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8660 return 0;
8661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008662 // If we are casting a malloc or alloca to a pointer to a type of the same
8663 // size, rewrite the allocation instruction to allocate the "right" type.
8664 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8665 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8666 return V;
8667
8668 // If the source and destination are pointers, and this cast is equivalent
8669 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8670 // This can enhance SROA and other transforms that want type-safe pointers.
8671 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8672 unsigned NumZeros = 0;
8673 while (SrcElTy != DstElTy &&
8674 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8675 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8676 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8677 ++NumZeros;
8678 }
8679
8680 // If we found a path from the src to dest, create the getelementptr now.
8681 if (SrcElTy == DstElTy) {
8682 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008683 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8684 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008685 }
8686 }
8687
8688 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8689 if (SVI->hasOneUse()) {
8690 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8691 // a bitconvert to a vector with the same # elts.
8692 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008693 cast<VectorType>(DestTy)->getNumElements() ==
8694 SVI->getType()->getNumElements() &&
8695 SVI->getType()->getNumElements() ==
8696 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008697 CastInst *Tmp;
8698 // If either of the operands is a cast from CI.getType(), then
8699 // evaluating the shuffle in the casted destination's type will allow
8700 // us to eliminate at least one cast.
8701 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8702 Tmp->getOperand(0)->getType() == DestTy) ||
8703 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8704 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008705 Value *LHS = InsertCastBefore(Instruction::BitCast,
8706 SVI->getOperand(0), DestTy, CI);
8707 Value *RHS = InsertCastBefore(Instruction::BitCast,
8708 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008709 // Return a new shuffle vector. Use the same element ID's, as we
8710 // know the vector types match #elts.
8711 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8712 }
8713 }
8714 }
8715 }
8716 return 0;
8717}
8718
8719/// GetSelectFoldableOperands - We want to turn code that looks like this:
8720/// %C = or %A, %B
8721/// %D = select %cond, %C, %A
8722/// into:
8723/// %C = select %cond, %B, 0
8724/// %D = or %A, %C
8725///
8726/// Assuming that the specified instruction is an operand to the select, return
8727/// a bitmask indicating which operands of this instruction are foldable if they
8728/// equal the other incoming value of the select.
8729///
8730static unsigned GetSelectFoldableOperands(Instruction *I) {
8731 switch (I->getOpcode()) {
8732 case Instruction::Add:
8733 case Instruction::Mul:
8734 case Instruction::And:
8735 case Instruction::Or:
8736 case Instruction::Xor:
8737 return 3; // Can fold through either operand.
8738 case Instruction::Sub: // Can only fold on the amount subtracted.
8739 case Instruction::Shl: // Can only fold on the shift amount.
8740 case Instruction::LShr:
8741 case Instruction::AShr:
8742 return 1;
8743 default:
8744 return 0; // Cannot fold
8745 }
8746}
8747
8748/// GetSelectFoldableConstant - For the same transformation as the previous
8749/// function, return the identity constant that goes into the select.
8750static Constant *GetSelectFoldableConstant(Instruction *I) {
8751 switch (I->getOpcode()) {
8752 default: assert(0 && "This cannot happen!"); abort();
8753 case Instruction::Add:
8754 case Instruction::Sub:
8755 case Instruction::Or:
8756 case Instruction::Xor:
8757 case Instruction::Shl:
8758 case Instruction::LShr:
8759 case Instruction::AShr:
8760 return Constant::getNullValue(I->getType());
8761 case Instruction::And:
8762 return Constant::getAllOnesValue(I->getType());
8763 case Instruction::Mul:
8764 return ConstantInt::get(I->getType(), 1);
8765 }
8766}
8767
8768/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8769/// have the same opcode and only one use each. Try to simplify this.
8770Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8771 Instruction *FI) {
8772 if (TI->getNumOperands() == 1) {
8773 // If this is a non-volatile load or a cast from the same type,
8774 // merge.
8775 if (TI->isCast()) {
8776 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8777 return 0;
8778 } else {
8779 return 0; // unknown unary op.
8780 }
8781
8782 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008783 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8784 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008785 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008786 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008787 TI->getType());
8788 }
8789
8790 // Only handle binary operators here.
8791 if (!isa<BinaryOperator>(TI))
8792 return 0;
8793
8794 // Figure out if the operations have any operands in common.
8795 Value *MatchOp, *OtherOpT, *OtherOpF;
8796 bool MatchIsOpZero;
8797 if (TI->getOperand(0) == FI->getOperand(0)) {
8798 MatchOp = TI->getOperand(0);
8799 OtherOpT = TI->getOperand(1);
8800 OtherOpF = FI->getOperand(1);
8801 MatchIsOpZero = true;
8802 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8803 MatchOp = TI->getOperand(1);
8804 OtherOpT = TI->getOperand(0);
8805 OtherOpF = FI->getOperand(0);
8806 MatchIsOpZero = false;
8807 } else if (!TI->isCommutative()) {
8808 return 0;
8809 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8810 MatchOp = TI->getOperand(0);
8811 OtherOpT = TI->getOperand(1);
8812 OtherOpF = FI->getOperand(0);
8813 MatchIsOpZero = true;
8814 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8815 MatchOp = TI->getOperand(1);
8816 OtherOpT = TI->getOperand(0);
8817 OtherOpF = FI->getOperand(1);
8818 MatchIsOpZero = true;
8819 } else {
8820 return 0;
8821 }
8822
8823 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008824 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8825 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008826 InsertNewInstBefore(NewSI, SI);
8827
8828 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8829 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008830 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008831 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008832 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008833 }
8834 assert(0 && "Shouldn't get here");
8835 return 0;
8836}
8837
Dan Gohman58c09632008-09-16 18:46:06 +00008838/// visitSelectInstWithICmp - Visit a SelectInst that has an
8839/// ICmpInst as its first operand.
8840///
8841Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8842 ICmpInst *ICI) {
8843 bool Changed = false;
8844 ICmpInst::Predicate Pred = ICI->getPredicate();
8845 Value *CmpLHS = ICI->getOperand(0);
8846 Value *CmpRHS = ICI->getOperand(1);
8847 Value *TrueVal = SI.getTrueValue();
8848 Value *FalseVal = SI.getFalseValue();
8849
8850 // Check cases where the comparison is with a constant that
8851 // can be adjusted to fit the min/max idiom. We may edit ICI in
8852 // place here, so make sure the select is the only user.
8853 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00008854 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00008855 switch (Pred) {
8856 default: break;
8857 case ICmpInst::ICMP_ULT:
8858 case ICmpInst::ICMP_SLT: {
8859 // X < MIN ? T : F --> F
8860 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8861 return ReplaceInstUsesWith(SI, FalseVal);
8862 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8863 Constant *AdjustedRHS = SubOne(CI);
8864 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8865 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8866 Pred = ICmpInst::getSwappedPredicate(Pred);
8867 CmpRHS = AdjustedRHS;
8868 std::swap(FalseVal, TrueVal);
8869 ICI->setPredicate(Pred);
8870 ICI->setOperand(1, CmpRHS);
8871 SI.setOperand(1, TrueVal);
8872 SI.setOperand(2, FalseVal);
8873 Changed = true;
8874 }
8875 break;
8876 }
8877 case ICmpInst::ICMP_UGT:
8878 case ICmpInst::ICMP_SGT: {
8879 // X > MAX ? T : F --> F
8880 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8881 return ReplaceInstUsesWith(SI, FalseVal);
8882 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8883 Constant *AdjustedRHS = AddOne(CI);
8884 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8885 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8886 Pred = ICmpInst::getSwappedPredicate(Pred);
8887 CmpRHS = AdjustedRHS;
8888 std::swap(FalseVal, TrueVal);
8889 ICI->setPredicate(Pred);
8890 ICI->setOperand(1, CmpRHS);
8891 SI.setOperand(1, TrueVal);
8892 SI.setOperand(2, FalseVal);
8893 Changed = true;
8894 }
8895 break;
8896 }
8897 }
8898
Dan Gohman35b76162008-10-30 20:40:10 +00008899 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8900 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00008901 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008902 if (match(TrueVal, m_ConstantInt<-1>()) &&
8903 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008904 Pred = ICI->getPredicate();
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008905 else if (match(TrueVal, m_ConstantInt<0>()) &&
8906 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008907 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8908
Dan Gohman35b76162008-10-30 20:40:10 +00008909 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8910 // If we are just checking for a icmp eq of a single bit and zext'ing it
8911 // to an integer, then shift the bit to the appropriate place and then
8912 // cast to integer to avoid the comparison.
8913 const APInt &Op1CV = CI->getValue();
8914
8915 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8916 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8917 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00008918 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00008919 Value *In = ICI->getOperand(0);
8920 Value *Sh = ConstantInt::get(In->getType(),
8921 In->getType()->getPrimitiveSizeInBits()-1);
8922 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8923 In->getName()+".lobit"),
8924 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00008925 if (In->getType() != SI.getType())
8926 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00008927 true/*SExt*/, "tmp", ICI);
8928
8929 if (Pred == ICmpInst::ICMP_SGT)
8930 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8931 In->getName()+".not"), *ICI);
8932
8933 return ReplaceInstUsesWith(SI, In);
8934 }
8935 }
8936 }
8937
Dan Gohman58c09632008-09-16 18:46:06 +00008938 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8939 // Transform (X == Y) ? X : Y -> Y
8940 if (Pred == ICmpInst::ICMP_EQ)
8941 return ReplaceInstUsesWith(SI, FalseVal);
8942 // Transform (X != Y) ? X : Y -> X
8943 if (Pred == ICmpInst::ICMP_NE)
8944 return ReplaceInstUsesWith(SI, TrueVal);
8945 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8946
8947 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8948 // Transform (X == Y) ? Y : X -> X
8949 if (Pred == ICmpInst::ICMP_EQ)
8950 return ReplaceInstUsesWith(SI, FalseVal);
8951 // Transform (X != Y) ? Y : X -> Y
8952 if (Pred == ICmpInst::ICMP_NE)
8953 return ReplaceInstUsesWith(SI, TrueVal);
8954 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8955 }
8956
8957 /// NOTE: if we wanted to, this is where to detect integer ABS
8958
8959 return Changed ? &SI : 0;
8960}
8961
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008962Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8963 Value *CondVal = SI.getCondition();
8964 Value *TrueVal = SI.getTrueValue();
8965 Value *FalseVal = SI.getFalseValue();
8966
8967 // select true, X, Y -> X
8968 // select false, X, Y -> Y
8969 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8970 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8971
8972 // select C, X, X -> X
8973 if (TrueVal == FalseVal)
8974 return ReplaceInstUsesWith(SI, TrueVal);
8975
8976 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8977 return ReplaceInstUsesWith(SI, FalseVal);
8978 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8979 return ReplaceInstUsesWith(SI, TrueVal);
8980 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8981 if (isa<Constant>(TrueVal))
8982 return ReplaceInstUsesWith(SI, TrueVal);
8983 else
8984 return ReplaceInstUsesWith(SI, FalseVal);
8985 }
8986
8987 if (SI.getType() == Type::Int1Ty) {
8988 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8989 if (C->getZExtValue()) {
8990 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008991 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008992 } else {
8993 // Change: A = select B, false, C --> A = and !B, C
8994 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008995 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008996 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008997 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008998 }
8999 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9000 if (C->getZExtValue() == false) {
9001 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009002 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009003 } else {
9004 // Change: A = select B, C, true --> A = or !B, C
9005 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009006 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009007 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009008 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009009 }
9010 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009011
9012 // select a, b, a -> a&b
9013 // select a, a, b -> a|b
9014 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009015 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009016 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009017 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009018 }
9019
9020 // Selecting between two integer constants?
9021 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9022 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9023 // select C, 1, 0 -> zext C to int
9024 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009025 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009026 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9027 // select C, 0, 1 -> zext !C to int
9028 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009029 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009030 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009031 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009032 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009033
9034 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9035
9036 // (x <s 0) ? -1 : 0 -> ashr x, 31
9037 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9038 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9039 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9040 // The comparison constant and the result are not neccessarily the
9041 // same width. Make an all-ones value by inserting a AShr.
9042 Value *X = IC->getOperand(0);
9043 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9044 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00009045 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009046 ShAmt, "ones");
9047 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00009048
9049 // Then cast to the appropriate width.
9050 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009051 }
9052 }
9053
9054
9055 // If one of the constants is zero (we know they can't both be) and we
9056 // have an icmp instruction with zero, and we have an 'and' with the
9057 // non-constant value, eliminate this whole mess. This corresponds to
9058 // cases like this: ((X & 27) ? 27 : 0)
9059 if (TrueValC->isZero() || FalseValC->isZero())
9060 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9061 cast<Constant>(IC->getOperand(1))->isNullValue())
9062 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9063 if (ICA->getOpcode() == Instruction::And &&
9064 isa<ConstantInt>(ICA->getOperand(1)) &&
9065 (ICA->getOperand(1) == TrueValC ||
9066 ICA->getOperand(1) == FalseValC) &&
9067 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9068 // Okay, now we know that everything is set up, we just don't
9069 // know whether we have a icmp_ne or icmp_eq and whether the
9070 // true or false val is the zero.
9071 bool ShouldNotVal = !TrueValC->isZero();
9072 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9073 Value *V = ICA;
9074 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009075 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 Instruction::Xor, V, ICA->getOperand(1)), SI);
9077 return ReplaceInstUsesWith(SI, V);
9078 }
9079 }
9080 }
9081
9082 // See if we are selecting two values based on a comparison of the two values.
9083 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9084 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9085 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009086 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9087 // This is not safe in general for floating point:
9088 // consider X== -0, Y== +0.
9089 // It becomes safe if either operand is a nonzero constant.
9090 ConstantFP *CFPt, *CFPf;
9091 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9092 !CFPt->getValueAPF().isZero()) ||
9093 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9094 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009095 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009096 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009097 // Transform (X != Y) ? X : Y -> X
9098 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9099 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009100 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009101
9102 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9103 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009104 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9105 // This is not safe in general for floating point:
9106 // consider X== -0, Y== +0.
9107 // It becomes safe if either operand is a nonzero constant.
9108 ConstantFP *CFPt, *CFPf;
9109 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9110 !CFPt->getValueAPF().isZero()) ||
9111 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9112 !CFPf->getValueAPF().isZero()))
9113 return ReplaceInstUsesWith(SI, FalseVal);
9114 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009115 // Transform (X != Y) ? Y : X -> Y
9116 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9117 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009118 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009119 }
Dan Gohman58c09632008-09-16 18:46:06 +00009120 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121 }
9122
9123 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009124 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9125 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9126 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009127
9128 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9129 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9130 if (TI->hasOneUse() && FI->hasOneUse()) {
9131 Instruction *AddOp = 0, *SubOp = 0;
9132
9133 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9134 if (TI->getOpcode() == FI->getOpcode())
9135 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9136 return IV;
9137
9138 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9139 // even legal for FP.
9140 if (TI->getOpcode() == Instruction::Sub &&
9141 FI->getOpcode() == Instruction::Add) {
9142 AddOp = FI; SubOp = TI;
9143 } else if (FI->getOpcode() == Instruction::Sub &&
9144 TI->getOpcode() == Instruction::Add) {
9145 AddOp = TI; SubOp = FI;
9146 }
9147
9148 if (AddOp) {
9149 Value *OtherAddOp = 0;
9150 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9151 OtherAddOp = AddOp->getOperand(1);
9152 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9153 OtherAddOp = AddOp->getOperand(0);
9154 }
9155
9156 if (OtherAddOp) {
9157 // So at this point we know we have (Y -> OtherAddOp):
9158 // select C, (add X, Y), (sub X, Z)
9159 Value *NegVal; // Compute -Z
9160 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9161 NegVal = ConstantExpr::getNeg(C);
9162 } else {
9163 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009164 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009165 }
9166
9167 Value *NewTrueOp = OtherAddOp;
9168 Value *NewFalseOp = NegVal;
9169 if (AddOp != TI)
9170 std::swap(NewTrueOp, NewFalseOp);
9171 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009172 SelectInst::Create(CondVal, NewTrueOp,
9173 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174
9175 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009176 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009177 }
9178 }
9179 }
9180
9181 // See if we can fold the select into one of our operands.
9182 if (SI.getType()->isInteger()) {
9183 // See the comment above GetSelectFoldableOperands for a description of the
9184 // transformation we are doing here.
9185 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9186 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9187 !isa<Constant>(FalseVal))
9188 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9189 unsigned OpToFold = 0;
9190 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9191 OpToFold = 1;
9192 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9193 OpToFold = 2;
9194 }
9195
9196 if (OpToFold) {
9197 Constant *C = GetSelectFoldableConstant(TVI);
9198 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009199 SelectInst::Create(SI.getCondition(),
9200 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009201 InsertNewInstBefore(NewSel, SI);
9202 NewSel->takeName(TVI);
9203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009204 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009205 else {
9206 assert(0 && "Unknown instruction!!");
9207 }
9208 }
9209 }
9210
9211 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9212 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9213 !isa<Constant>(TrueVal))
9214 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9215 unsigned OpToFold = 0;
9216 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9217 OpToFold = 1;
9218 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9219 OpToFold = 2;
9220 }
9221
9222 if (OpToFold) {
9223 Constant *C = GetSelectFoldableConstant(FVI);
9224 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009225 SelectInst::Create(SI.getCondition(), C,
9226 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009227 InsertNewInstBefore(NewSel, SI);
9228 NewSel->takeName(FVI);
9229 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009230 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009231 else
9232 assert(0 && "Unknown instruction!!");
9233 }
9234 }
9235 }
9236
9237 if (BinaryOperator::isNot(CondVal)) {
9238 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9239 SI.setOperand(1, FalseVal);
9240 SI.setOperand(2, TrueVal);
9241 return &SI;
9242 }
9243
9244 return 0;
9245}
9246
Dan Gohman2d648bb2008-04-10 18:43:06 +00009247/// EnforceKnownAlignment - If the specified pointer points to an object that
9248/// we control, modify the object's alignment to PrefAlign. This isn't
9249/// often possible though. If alignment is important, a more reliable approach
9250/// is to simply align all global variables and allocation instructions to
9251/// their preferred alignment from the beginning.
9252///
9253static unsigned EnforceKnownAlignment(Value *V,
9254 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009255
Dan Gohman2d648bb2008-04-10 18:43:06 +00009256 User *U = dyn_cast<User>(V);
9257 if (!U) return Align;
9258
9259 switch (getOpcode(U)) {
9260 default: break;
9261 case Instruction::BitCast:
9262 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9263 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009264 // If all indexes are zero, it is just the alignment of the base pointer.
9265 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009266 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009267 if (!isa<Constant>(*i) ||
9268 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009269 AllZeroOperands = false;
9270 break;
9271 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009272
9273 if (AllZeroOperands) {
9274 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009275 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009276 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009277 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009278 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009279 }
9280
9281 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9282 // If there is a large requested alignment and we can, bump up the alignment
9283 // of the global.
9284 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009285 if (GV->getAlignment() >= PrefAlign)
9286 Align = GV->getAlignment();
9287 else {
9288 GV->setAlignment(PrefAlign);
9289 Align = PrefAlign;
9290 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009291 }
9292 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9293 // If there is a requested alignment and if this is an alloca, round up. We
9294 // don't do this for malloc, because some systems can't respect the request.
9295 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009296 if (AI->getAlignment() >= PrefAlign)
9297 Align = AI->getAlignment();
9298 else {
9299 AI->setAlignment(PrefAlign);
9300 Align = PrefAlign;
9301 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009302 }
9303 }
9304
9305 return Align;
9306}
9307
9308/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9309/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9310/// and it is more than the alignment of the ultimate object, see if we can
9311/// increase the alignment of the ultimate object, making this check succeed.
9312unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9313 unsigned PrefAlign) {
9314 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9315 sizeof(PrefAlign) * CHAR_BIT;
9316 APInt Mask = APInt::getAllOnesValue(BitWidth);
9317 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9318 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9319 unsigned TrailZ = KnownZero.countTrailingOnes();
9320 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9321
9322 if (PrefAlign > Align)
9323 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9324
9325 // We don't need to make any adjustment.
9326 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009327}
9328
Chris Lattner00ae5132008-01-13 23:50:23 +00009329Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009330 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009331 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009332 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009333 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009334
9335 if (CopyAlign < MinAlign) {
Chris Lattner3947da72009-03-08 03:59:00 +00009336 MI->setAlignment(MinAlign);
Chris Lattner00ae5132008-01-13 23:50:23 +00009337 return MI;
9338 }
9339
9340 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9341 // load/store.
9342 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9343 if (MemOpLength == 0) return 0;
9344
Chris Lattnerc669fb62008-01-14 00:28:35 +00009345 // Source and destination pointer types are always "i8*" for intrinsic. See
9346 // if the size is something we can handle with a single primitive load/store.
9347 // A single load+store correctly handles overlapping memory in the memmove
9348 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009349 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009350 if (Size == 0) return MI; // Delete this mem transfer.
9351
9352 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009353 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009354
Chris Lattnerc669fb62008-01-14 00:28:35 +00009355 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009356 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009357
9358 // Memcpy forces the use of i8* for the source and destination. That means
9359 // that if you're using memcpy to move one double around, you'll get a cast
9360 // from double* to i8*. We'd much rather use a double load+store rather than
9361 // an i64 load+store, here because this improves the odds that the source or
9362 // dest address will be promotable. See if we can find a better type than the
9363 // integer datatype.
9364 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9365 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9366 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9367 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9368 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009369 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009370 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9371 if (STy->getNumElements() == 1)
9372 SrcETy = STy->getElementType(0);
9373 else
9374 break;
9375 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9376 if (ATy->getNumElements() == 1)
9377 SrcETy = ATy->getElementType();
9378 else
9379 break;
9380 } else
9381 break;
9382 }
9383
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009384 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009385 NewPtrTy = PointerType::getUnqual(SrcETy);
9386 }
9387 }
9388
9389
Chris Lattner00ae5132008-01-13 23:50:23 +00009390 // If the memcpy/memmove provides better alignment info than we can
9391 // infer, use it.
9392 SrcAlign = std::max(SrcAlign, CopyAlign);
9393 DstAlign = std::max(DstAlign, CopyAlign);
9394
9395 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9396 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009397 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9398 InsertNewInstBefore(L, *MI);
9399 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9400
9401 // Set the size of the copy to 0, it will be deleted on the next iteration.
9402 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9403 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009404}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009405
Chris Lattner5af8a912008-04-30 06:39:11 +00009406Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9407 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009408 if (MI->getAlignment() < Alignment) {
9409 MI->setAlignment(Alignment);
Chris Lattner5af8a912008-04-30 06:39:11 +00009410 return MI;
9411 }
9412
9413 // Extract the length and alignment and fill if they are constant.
9414 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9415 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9416 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9417 return 0;
9418 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009419 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009420
9421 // If the length is zero, this is a no-op
9422 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9423
9424 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9425 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9426 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9427
9428 Value *Dest = MI->getDest();
9429 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9430
9431 // Alignment 0 is identity for alignment 1 for memset, but not store.
9432 if (Alignment == 0) Alignment = 1;
9433
9434 // Extract the fill value and store.
9435 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9436 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9437 Alignment), *MI);
9438
9439 // Set the size of the copy to 0, it will be deleted on the next iteration.
9440 MI->setLength(Constant::getNullValue(LenC->getType()));
9441 return MI;
9442 }
9443
9444 return 0;
9445}
9446
9447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009448/// visitCallInst - CallInst simplification. This mostly only handles folding
9449/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9450/// the heavy lifting.
9451///
9452Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9453 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9454 if (!II) return visitCallSite(&CI);
9455
9456 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9457 // visitCallSite.
9458 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9459 bool Changed = false;
9460
9461 // memmove/cpy/set of zero bytes is a noop.
9462 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9463 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9464
9465 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9466 if (CI->getZExtValue() == 1) {
9467 // Replace the instruction with just byte operations. We would
9468 // transform other cases to loads/stores, but we don't know if
9469 // alignment is sufficient.
9470 }
9471 }
9472
9473 // If we have a memmove and the source operation is a constant global,
9474 // then the source and dest pointers can't alias, so we can change this
9475 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009476 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9478 if (GVSrc->isConstant()) {
9479 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009480 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9481 const Type *Tys[1];
9482 Tys[0] = CI.getOperand(3)->getType();
9483 CI.setOperand(0,
9484 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009485 Changed = true;
9486 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009487
9488 // memmove(x,x,size) -> noop.
9489 if (MMI->getSource() == MMI->getDest())
9490 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009491 }
9492
9493 // If we can determine a pointer alignment that is bigger than currently
9494 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009495 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009496 if (Instruction *I = SimplifyMemTransfer(MI))
9497 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009498 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9499 if (Instruction *I = SimplifyMemSet(MSI))
9500 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009501 }
9502
9503 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009504 }
9505
9506 switch (II->getIntrinsicID()) {
9507 default: break;
9508 case Intrinsic::bswap:
9509 // bswap(bswap(x)) -> x
9510 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9511 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9512 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9513 break;
9514 case Intrinsic::ppc_altivec_lvx:
9515 case Intrinsic::ppc_altivec_lvxl:
9516 case Intrinsic::x86_sse_loadu_ps:
9517 case Intrinsic::x86_sse2_loadu_pd:
9518 case Intrinsic::x86_sse2_loadu_dq:
9519 // Turn PPC lvx -> load if the pointer is known aligned.
9520 // Turn X86 loadups -> load if the pointer is known aligned.
9521 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9522 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9523 PointerType::getUnqual(II->getType()),
9524 CI);
9525 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 }
Chris Lattner989ba312008-06-18 04:33:20 +00009527 break;
9528 case Intrinsic::ppc_altivec_stvx:
9529 case Intrinsic::ppc_altivec_stvxl:
9530 // Turn stvx -> store if the pointer is known aligned.
9531 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9532 const Type *OpPtrTy =
9533 PointerType::getUnqual(II->getOperand(1)->getType());
9534 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9535 return new StoreInst(II->getOperand(1), Ptr);
9536 }
9537 break;
9538 case Intrinsic::x86_sse_storeu_ps:
9539 case Intrinsic::x86_sse2_storeu_pd:
9540 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009541 // Turn X86 storeu -> store if the pointer is known aligned.
9542 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9543 const Type *OpPtrTy =
9544 PointerType::getUnqual(II->getOperand(2)->getType());
9545 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9546 return new StoreInst(II->getOperand(2), Ptr);
9547 }
9548 break;
9549
9550 case Intrinsic::x86_sse_cvttss2si: {
9551 // These intrinsics only demands the 0th element of its input vector. If
9552 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009553 unsigned VWidth =
9554 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9555 APInt DemandedElts(VWidth, 1);
9556 APInt UndefElts(VWidth, 0);
9557 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009558 UndefElts)) {
9559 II->setOperand(1, V);
9560 return II;
9561 }
9562 break;
9563 }
9564
9565 case Intrinsic::ppc_altivec_vperm:
9566 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9567 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9568 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009569
Chris Lattner989ba312008-06-18 04:33:20 +00009570 // Check that all of the elements are integer constants or undefs.
9571 bool AllEltsOk = true;
9572 for (unsigned i = 0; i != 16; ++i) {
9573 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9574 !isa<UndefValue>(Mask->getOperand(i))) {
9575 AllEltsOk = false;
9576 break;
9577 }
9578 }
9579
9580 if (AllEltsOk) {
9581 // Cast the input vectors to byte vectors.
9582 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9583 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9584 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009585
Chris Lattner989ba312008-06-18 04:33:20 +00009586 // Only extract each element once.
9587 Value *ExtractedElts[32];
9588 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9589
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009590 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009591 if (isa<UndefValue>(Mask->getOperand(i)))
9592 continue;
9593 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9594 Idx &= 31; // Match the hardware behavior.
9595
9596 if (ExtractedElts[Idx] == 0) {
9597 Instruction *Elt =
9598 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9599 InsertNewInstBefore(Elt, CI);
9600 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009601 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009602
Chris Lattner989ba312008-06-18 04:33:20 +00009603 // Insert this value into the result vector.
9604 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9605 i, "tmp");
9606 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009607 }
Chris Lattner989ba312008-06-18 04:33:20 +00009608 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009609 }
Chris Lattner989ba312008-06-18 04:33:20 +00009610 }
9611 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009612
Chris Lattner989ba312008-06-18 04:33:20 +00009613 case Intrinsic::stackrestore: {
9614 // If the save is right next to the restore, remove the restore. This can
9615 // happen when variable allocas are DCE'd.
9616 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9617 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9618 BasicBlock::iterator BI = SS;
9619 if (&*++BI == II)
9620 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009621 }
Chris Lattner989ba312008-06-18 04:33:20 +00009622 }
9623
9624 // Scan down this block to see if there is another stack restore in the
9625 // same block without an intervening call/alloca.
9626 BasicBlock::iterator BI = II;
9627 TerminatorInst *TI = II->getParent()->getTerminator();
9628 bool CannotRemove = false;
9629 for (++BI; &*BI != TI; ++BI) {
9630 if (isa<AllocaInst>(BI)) {
9631 CannotRemove = true;
9632 break;
9633 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009634 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9635 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9636 // If there is a stackrestore below this one, remove this one.
9637 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9638 return EraseInstFromFunction(CI);
9639 // Otherwise, ignore the intrinsic.
9640 } else {
9641 // If we found a non-intrinsic call, we can't remove the stack
9642 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009643 CannotRemove = true;
9644 break;
9645 }
Chris Lattner989ba312008-06-18 04:33:20 +00009646 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009647 }
Chris Lattner989ba312008-06-18 04:33:20 +00009648
9649 // If the stack restore is in a return/unwind block and if there are no
9650 // allocas or calls between the restore and the return, nuke the restore.
9651 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9652 return EraseInstFromFunction(CI);
9653 break;
9654 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009655 }
9656
9657 return visitCallSite(II);
9658}
9659
9660// InvokeInst simplification
9661//
9662Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9663 return visitCallSite(&II);
9664}
9665
Dale Johannesen96021832008-04-25 21:16:07 +00009666/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9667/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009668static bool isSafeToEliminateVarargsCast(const CallSite CS,
9669 const CastInst * const CI,
9670 const TargetData * const TD,
9671 const int ix) {
9672 if (!CI->isLosslessCast())
9673 return false;
9674
9675 // The size of ByVal arguments is derived from the type, so we
9676 // can't change to a type with a different size. If the size were
9677 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009678 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009679 return true;
9680
9681 const Type* SrcTy =
9682 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9683 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9684 if (!SrcTy->isSized() || !DstTy->isSized())
9685 return false;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00009686 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009687 return false;
9688 return true;
9689}
9690
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009691// visitCallSite - Improvements for call and invoke instructions.
9692//
9693Instruction *InstCombiner::visitCallSite(CallSite CS) {
9694 bool Changed = false;
9695
9696 // If the callee is a constexpr cast of a function, attempt to move the cast
9697 // to the arguments of the call/invoke.
9698 if (transformConstExprCastCall(CS)) return 0;
9699
9700 Value *Callee = CS.getCalledValue();
9701
9702 if (Function *CalleeF = dyn_cast<Function>(Callee))
9703 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9704 Instruction *OldCall = CS.getInstruction();
9705 // If the call and callee calling conventions don't match, this call must
9706 // be unreachable, as the call is undefined.
9707 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009708 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9709 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009710 if (!OldCall->use_empty())
9711 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9712 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9713 return EraseInstFromFunction(*OldCall);
9714 return 0;
9715 }
9716
9717 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9718 // This instruction is not reachable, just remove it. We insert a store to
9719 // undef so that we know that this code is not reachable, despite the fact
9720 // that we can't modify the CFG here.
9721 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009722 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009723 CS.getInstruction());
9724
9725 if (!CS.getInstruction()->use_empty())
9726 CS.getInstruction()->
9727 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9728
9729 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9730 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009731 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9732 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009733 }
9734 return EraseInstFromFunction(*CS.getInstruction());
9735 }
9736
Duncan Sands74833f22007-09-17 10:26:40 +00009737 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9738 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9739 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9740 return transformCallThroughTrampoline(CS);
9741
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009742 const PointerType *PTy = cast<PointerType>(Callee->getType());
9743 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9744 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009745 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009746 // See if we can optimize any arguments passed through the varargs area of
9747 // the call.
9748 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009749 E = CS.arg_end(); I != E; ++I, ++ix) {
9750 CastInst *CI = dyn_cast<CastInst>(*I);
9751 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9752 *I = CI->getOperand(0);
9753 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009754 }
Dale Johannesen35615462008-04-23 18:34:37 +00009755 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009756 }
9757
Duncan Sands2937e352007-12-19 21:13:37 +00009758 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009759 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009760 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009761 Changed = true;
9762 }
9763
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009764 return Changed ? CS.getInstruction() : 0;
9765}
9766
9767// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9768// attempt to move the cast to the arguments of the call/invoke.
9769//
9770bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9771 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9772 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9773 if (CE->getOpcode() != Instruction::BitCast ||
9774 !isa<Function>(CE->getOperand(0)))
9775 return false;
9776 Function *Callee = cast<Function>(CE->getOperand(0));
9777 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00009778 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009779
9780 // Okay, this is a cast from a function to a different type. Unless doing so
9781 // would cause a type conversion of one of our arguments, change this call to
9782 // be a direct call with arguments casted to the appropriate types.
9783 //
9784 const FunctionType *FT = Callee->getFunctionType();
9785 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009786 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009787
Duncan Sands7901ce12008-06-01 07:38:42 +00009788 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009789 return false; // TODO: Handle multiple return values.
9790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009791 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009792 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009793 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009794 // Conversion is ok if changing from one pointer type to another or from
9795 // a pointer to an integer of the same size.
9796 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00009797 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009798 return false; // Cannot transform this return value.
9799
Duncan Sands5c489582008-01-06 10:12:28 +00009800 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009801 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00009802 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009803 return false; // Cannot transform this return value.
9804
Chris Lattner1c8733e2008-03-12 17:45:29 +00009805 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00009806 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00009807 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009808 return false; // Attribute not compatible with transformed value.
9809 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009810
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009811 // If the callsite is an invoke instruction, and the return value is used by
9812 // a PHI node in a successor, we cannot change the return type of the call
9813 // because there is no place to put the cast instruction (without breaking
9814 // the critical edge). Bail out in this case.
9815 if (!Caller->use_empty())
9816 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9817 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9818 UI != E; ++UI)
9819 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9820 if (PN->getParent() == II->getNormalDest() ||
9821 PN->getParent() == II->getUnwindDest())
9822 return false;
9823 }
9824
9825 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9826 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9827
9828 CallSite::arg_iterator AI = CS.arg_begin();
9829 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9830 const Type *ParamTy = FT->getParamType(i);
9831 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009832
9833 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009834 return false; // Cannot transform this parameter value.
9835
Devang Patelf2a4a922008-09-26 22:53:05 +00009836 if (CallerPAL.getParamAttributes(i + 1)
9837 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00009838 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009839
Duncan Sands7901ce12008-06-01 07:38:42 +00009840 // Converting from one pointer type to another or between a pointer and an
9841 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009842 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00009843 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9844 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009845 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009846 }
9847
9848 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9849 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009850 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009851
Chris Lattner1c8733e2008-03-12 17:45:29 +00009852 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9853 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009854 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009855 // won't be dropping them. Check that these extra arguments have attributes
9856 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009857 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9858 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009859 break;
Devang Patele480dfa2008-09-23 23:03:40 +00009860 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00009861 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00009862 return false;
9863 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009864
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009865 // Okay, we decided that this is a safe thing to do: go ahead and start
9866 // inserting cast instructions as necessary...
9867 std::vector<Value*> Args;
9868 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00009869 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009870 attrVec.reserve(NumCommonArgs);
9871
9872 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009873 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00009874
9875 // If the return value is not being used, the type may not be compatible
9876 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00009877 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00009878
9879 // Add the new return attributes.
9880 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00009881 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009882
9883 AI = CS.arg_begin();
9884 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9885 const Type *ParamTy = FT->getParamType(i);
9886 if ((*AI)->getType() == ParamTy) {
9887 Args.push_back(*AI);
9888 } else {
9889 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9890 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009891 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009892 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9893 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009894
9895 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009896 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009897 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009898 }
9899
9900 // If the function takes more arguments than the call was taking, add them
9901 // now...
9902 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9903 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9904
9905 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009906 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009907 if (!FT->isVarArg()) {
9908 cerr << "WARNING: While resolving call to function '"
9909 << Callee->getName() << "' arguments were dropped!\n";
9910 } else {
9911 // Add all of the arguments in their promoted form to the arg list...
9912 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9913 const Type *PTy = getPromotedType((*AI)->getType());
9914 if (PTy != (*AI)->getType()) {
9915 // Must promote to pass through va_arg area!
9916 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9917 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009918 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009919 InsertNewInstBefore(Cast, *Caller);
9920 Args.push_back(Cast);
9921 } else {
9922 Args.push_back(*AI);
9923 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009924
Duncan Sands4ced1f82008-01-13 08:02:44 +00009925 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009926 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009927 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00009928 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009929 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009930 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009931
Devang Patelf2a4a922008-09-26 22:53:05 +00009932 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9933 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9934
Duncan Sands7901ce12008-06-01 07:38:42 +00009935 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009936 Caller->setName(""); // Void type should not have a name.
9937
Devang Pateld222f862008-09-25 21:00:45 +00009938 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009939
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009940 Instruction *NC;
9941 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009942 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009943 Args.begin(), Args.end(),
9944 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009945 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009946 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009947 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009948 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9949 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009950 CallInst *CI = cast<CallInst>(Caller);
9951 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009952 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009953 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009954 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009955 }
9956
9957 // Insert a cast of the return type as necessary.
9958 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009959 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009961 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009962 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009963 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009964
9965 // If this is an invoke instruction, we should insert it after the first
9966 // non-phi, instruction in the normal successor block.
9967 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009968 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009969 InsertNewInstBefore(NC, *I);
9970 } else {
9971 // Otherwise, it's a call, just insert cast right after the call instr
9972 InsertNewInstBefore(NC, *Caller);
9973 }
9974 AddUsersToWorkList(*Caller);
9975 } else {
9976 NV = UndefValue::get(Caller->getType());
9977 }
9978 }
9979
9980 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9981 Caller->replaceAllUsesWith(NV);
9982 Caller->eraseFromParent();
9983 RemoveFromWorkList(Caller);
9984 return true;
9985}
9986
Duncan Sands74833f22007-09-17 10:26:40 +00009987// transformCallThroughTrampoline - Turn a call to a function created by the
9988// init_trampoline intrinsic into a direct call to the underlying function.
9989//
9990Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9991 Value *Callee = CS.getCalledValue();
9992 const PointerType *PTy = cast<PointerType>(Callee->getType());
9993 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00009994 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00009995
9996 // If the call already has the 'nest' attribute somewhere then give up -
9997 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00009998 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009999 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010000
10001 IntrinsicInst *Tramp =
10002 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10003
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010004 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010005 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10006 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10007
Devang Pateld222f862008-09-25 21:00:45 +000010008 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010009 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010010 unsigned NestIdx = 1;
10011 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010012 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010013
10014 // Look for a parameter marked with the 'nest' attribute.
10015 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10016 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010017 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010018 // Record the parameter type and any other attributes.
10019 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010020 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010021 break;
10022 }
10023
10024 if (NestTy) {
10025 Instruction *Caller = CS.getInstruction();
10026 std::vector<Value*> NewArgs;
10027 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10028
Devang Pateld222f862008-09-25 21:00:45 +000010029 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010030 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010031
Duncan Sands74833f22007-09-17 10:26:40 +000010032 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010033 // mean appending it. Likewise for attributes.
10034
Devang Patelf2a4a922008-09-26 22:53:05 +000010035 // Add any result attributes.
10036 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010037 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010038
Duncan Sands74833f22007-09-17 10:26:40 +000010039 {
10040 unsigned Idx = 1;
10041 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10042 do {
10043 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010044 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010045 Value *NestVal = Tramp->getOperand(3);
10046 if (NestVal->getType() != NestTy)
10047 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10048 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010049 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010050 }
10051
10052 if (I == E)
10053 break;
10054
Duncan Sands48b81112008-01-14 19:52:09 +000010055 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010056 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010057 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010058 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010059 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010060
10061 ++Idx, ++I;
10062 } while (1);
10063 }
10064
Devang Patelf2a4a922008-09-26 22:53:05 +000010065 // Add any function attributes.
10066 if (Attributes Attr = Attrs.getFnAttributes())
10067 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10068
Duncan Sands74833f22007-09-17 10:26:40 +000010069 // The trampoline may have been bitcast to a bogus type (FTy).
10070 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010071 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010072
Duncan Sands74833f22007-09-17 10:26:40 +000010073 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010074 NewTypes.reserve(FTy->getNumParams()+1);
10075
Duncan Sands74833f22007-09-17 10:26:40 +000010076 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010077 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010078 {
10079 unsigned Idx = 1;
10080 FunctionType::param_iterator I = FTy->param_begin(),
10081 E = FTy->param_end();
10082
10083 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010084 if (Idx == NestIdx)
10085 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010086 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010087
10088 if (I == E)
10089 break;
10090
Duncan Sands48b81112008-01-14 19:52:09 +000010091 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010092 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010093
10094 ++Idx, ++I;
10095 } while (1);
10096 }
10097
10098 // Replace the trampoline call with a direct call. Let the generic
10099 // code sort out any function type mismatches.
10100 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010101 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +000010102 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10103 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +000010104 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010105
10106 Instruction *NewCaller;
10107 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010108 NewCaller = InvokeInst::Create(NewCallee,
10109 II->getNormalDest(), II->getUnwindDest(),
10110 NewArgs.begin(), NewArgs.end(),
10111 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010112 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010113 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010114 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010115 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10116 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010117 if (cast<CallInst>(Caller)->isTailCall())
10118 cast<CallInst>(NewCaller)->setTailCall();
10119 cast<CallInst>(NewCaller)->
10120 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010121 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010122 }
10123 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10124 Caller->replaceAllUsesWith(NewCaller);
10125 Caller->eraseFromParent();
10126 RemoveFromWorkList(Caller);
10127 return 0;
10128 }
10129 }
10130
10131 // Replace the trampoline call with a direct call. Since there is no 'nest'
10132 // parameter, there is no need to adjust the argument list. Let the generic
10133 // code sort out any function type mismatches.
10134 Constant *NewCallee =
10135 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10136 CS.setCalledFunction(NewCallee);
10137 return CS.getInstruction();
10138}
10139
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10141/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10142/// and a single binop.
10143Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10144 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010145 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146 unsigned Opc = FirstInst->getOpcode();
10147 Value *LHSVal = FirstInst->getOperand(0);
10148 Value *RHSVal = FirstInst->getOperand(1);
10149
10150 const Type *LHSType = LHSVal->getType();
10151 const Type *RHSType = RHSVal->getType();
10152
10153 // Scan to see if all operands are the same opcode, all have one use, and all
10154 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010155 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10157 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10158 // Verify type of the LHS matches so we don't fold cmp's of different
10159 // types or GEP's with different index types.
10160 I->getOperand(0)->getType() != LHSType ||
10161 I->getOperand(1)->getType() != RHSType)
10162 return 0;
10163
10164 // If they are CmpInst instructions, check their predicates
10165 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10166 if (cast<CmpInst>(I)->getPredicate() !=
10167 cast<CmpInst>(FirstInst)->getPredicate())
10168 return 0;
10169
10170 // Keep track of which operand needs a phi node.
10171 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10172 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10173 }
10174
Chris Lattner30078012008-12-01 03:42:51 +000010175 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010176
10177 Value *InLHS = FirstInst->getOperand(0);
10178 Value *InRHS = FirstInst->getOperand(1);
10179 PHINode *NewLHS = 0, *NewRHS = 0;
10180 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010181 NewLHS = PHINode::Create(LHSType,
10182 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010183 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10184 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10185 InsertNewInstBefore(NewLHS, PN);
10186 LHSVal = NewLHS;
10187 }
10188
10189 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010190 NewRHS = PHINode::Create(RHSType,
10191 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010192 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10193 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10194 InsertNewInstBefore(NewRHS, PN);
10195 RHSVal = NewRHS;
10196 }
10197
10198 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010199 if (NewLHS || NewRHS) {
10200 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10201 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10202 if (NewLHS) {
10203 Value *NewInLHS = InInst->getOperand(0);
10204 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10205 }
10206 if (NewRHS) {
10207 Value *NewInRHS = InInst->getOperand(1);
10208 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10209 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010210 }
10211 }
10212
10213 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010214 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010215 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10216 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10217 RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010218}
10219
Chris Lattner9e1916e2008-12-01 02:34:36 +000010220Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10221 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10222
10223 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10224 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010225 // This is true if all GEP bases are allocas and if all indices into them are
10226 // constants.
10227 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010228
10229 // Scan to see if all operands are the same opcode, all have one use, and all
10230 // kill their operands (i.e. the operands have one use).
10231 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10232 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10233 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10234 GEP->getNumOperands() != FirstInst->getNumOperands())
10235 return 0;
10236
Chris Lattneradf354b2009-02-21 00:46:50 +000010237 // Keep track of whether or not all GEPs are of alloca pointers.
10238 if (AllBasePointersAreAllocas &&
10239 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10240 !GEP->hasAllConstantIndices()))
10241 AllBasePointersAreAllocas = false;
10242
Chris Lattner9e1916e2008-12-01 02:34:36 +000010243 // Compare the operand lists.
10244 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10245 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10246 continue;
10247
10248 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10249 // if one of the PHIs has a constant for the index. The index may be
10250 // substantially cheaper to compute for the constants, so making it a
10251 // variable index could pessimize the path. This also handles the case
10252 // for struct indices, which must always be constant.
10253 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10254 isa<ConstantInt>(GEP->getOperand(op)))
10255 return 0;
10256
10257 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10258 return 0;
10259 FixedOperands[op] = 0; // Needs a PHI.
10260 }
10261 }
10262
Chris Lattneradf354b2009-02-21 00:46:50 +000010263 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010264 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010265 // offset calculation, but all the predecessors will have to materialize the
10266 // stack address into a register anyway. We'd actually rather *clone* the
10267 // load up into the predecessors so that we have a load of a gep of an alloca,
10268 // which can usually all be folded into the load.
10269 if (AllBasePointersAreAllocas)
10270 return 0;
10271
Chris Lattner9e1916e2008-12-01 02:34:36 +000010272 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10273 // that is variable.
10274 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10275
10276 bool HasAnyPHIs = false;
10277 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10278 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10279 Value *FirstOp = FirstInst->getOperand(i);
10280 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10281 FirstOp->getName()+".pn");
10282 InsertNewInstBefore(NewPN, PN);
10283
10284 NewPN->reserveOperandSpace(e);
10285 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10286 OperandPhis[i] = NewPN;
10287 FixedOperands[i] = NewPN;
10288 HasAnyPHIs = true;
10289 }
10290
10291
10292 // Add all operands to the new PHIs.
10293 if (HasAnyPHIs) {
10294 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10295 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10296 BasicBlock *InBB = PN.getIncomingBlock(i);
10297
10298 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10299 if (PHINode *OpPhi = OperandPhis[op])
10300 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10301 }
10302 }
10303
10304 Value *Base = FixedOperands[0];
10305 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10306 FixedOperands.end());
10307}
10308
10309
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010310/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10311/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010312/// obvious the value of the load is not changed from the point of the load to
10313/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010314///
10315/// Finally, it is safe, but not profitable, to sink a load targetting a
10316/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10317/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010318static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010319 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10320
10321 for (++BBI; BBI != E; ++BBI)
10322 if (BBI->mayWriteToMemory())
10323 return false;
10324
10325 // Check for non-address taken alloca. If not address-taken already, it isn't
10326 // profitable to do this xform.
10327 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10328 bool isAddressTaken = false;
10329 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10330 UI != E; ++UI) {
10331 if (isa<LoadInst>(UI)) continue;
10332 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10333 // If storing TO the alloca, then the address isn't taken.
10334 if (SI->getOperand(1) == AI) continue;
10335 }
10336 isAddressTaken = true;
10337 break;
10338 }
10339
Chris Lattneradf354b2009-02-21 00:46:50 +000010340 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010341 return false;
10342 }
10343
Chris Lattneradf354b2009-02-21 00:46:50 +000010344 // If this load is a load from a GEP with a constant offset from an alloca,
10345 // then we don't want to sink it. In its present form, it will be
10346 // load [constant stack offset]. Sinking it will cause us to have to
10347 // materialize the stack addresses in each predecessor in a register only to
10348 // do a shared load from register in the successor.
10349 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10350 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10351 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10352 return false;
10353
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010354 return true;
10355}
10356
10357
10358// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10359// operator and they all are only used by the PHI, PHI together their
10360// inputs, and do the operation once, to the result of the PHI.
10361Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10362 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10363
10364 // Scan the instruction, looking for input operations that can be folded away.
10365 // If all input operands to the phi are the same instruction (e.g. a cast from
10366 // the same type or "+42") we can pull the operation through the PHI, reducing
10367 // code size and simplifying code.
10368 Constant *ConstantOp = 0;
10369 const Type *CastSrcTy = 0;
10370 bool isVolatile = false;
10371 if (isa<CastInst>(FirstInst)) {
10372 CastSrcTy = FirstInst->getOperand(0)->getType();
10373 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10374 // Can fold binop, compare or shift here if the RHS is a constant,
10375 // otherwise call FoldPHIArgBinOpIntoPHI.
10376 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10377 if (ConstantOp == 0)
10378 return FoldPHIArgBinOpIntoPHI(PN);
10379 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10380 isVolatile = LI->isVolatile();
10381 // We can't sink the load if the loaded value could be modified between the
10382 // load and the PHI.
10383 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010384 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010385 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010386
10387 // If the PHI is of volatile loads and the load block has multiple
10388 // successors, sinking it would remove a load of the volatile value from
10389 // the path through the other successor.
10390 if (isVolatile &&
10391 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10392 return 0;
10393
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010394 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010395 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010396 } else {
10397 return 0; // Cannot fold this operation.
10398 }
10399
10400 // Check to see if all arguments are the same operation.
10401 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10402 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10403 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10404 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10405 return 0;
10406 if (CastSrcTy) {
10407 if (I->getOperand(0)->getType() != CastSrcTy)
10408 return 0; // Cast operation must match.
10409 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10410 // We can't sink the load if the loaded value could be modified between
10411 // the load and the PHI.
10412 if (LI->isVolatile() != isVolatile ||
10413 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010414 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010415 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010416
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010417 // If the PHI is of volatile loads and the load block has multiple
10418 // successors, sinking it would remove a load of the volatile value from
10419 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010420 if (isVolatile &&
10421 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10422 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010423
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010424 } else if (I->getOperand(1) != ConstantOp) {
10425 return 0;
10426 }
10427 }
10428
10429 // Okay, they are all the same operation. Create a new PHI node of the
10430 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010431 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10432 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010433 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10434
10435 Value *InVal = FirstInst->getOperand(0);
10436 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10437
10438 // Add all operands to the new PHI.
10439 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10440 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10441 if (NewInVal != InVal)
10442 InVal = 0;
10443 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10444 }
10445
10446 Value *PhiVal;
10447 if (InVal) {
10448 // The new PHI unions all of the same values together. This is really
10449 // common, so we handle it intelligently here for compile-time speed.
10450 PhiVal = InVal;
10451 delete NewPN;
10452 } else {
10453 InsertNewInstBefore(NewPN, PN);
10454 PhiVal = NewPN;
10455 }
10456
10457 // Insert and return the new operation.
10458 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010459 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010460 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010461 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010462 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010463 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010464 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010465 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10466
10467 // If this was a volatile load that we are merging, make sure to loop through
10468 // and mark all the input loads as non-volatile. If we don't do this, we will
10469 // insert a new volatile load and the old ones will not be deletable.
10470 if (isVolatile)
10471 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10472 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10473
10474 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010475}
10476
10477/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10478/// that is dead.
10479static bool DeadPHICycle(PHINode *PN,
10480 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10481 if (PN->use_empty()) return true;
10482 if (!PN->hasOneUse()) return false;
10483
10484 // Remember this node, and if we find the cycle, return.
10485 if (!PotentiallyDeadPHIs.insert(PN))
10486 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010487
10488 // Don't scan crazily complex things.
10489 if (PotentiallyDeadPHIs.size() == 16)
10490 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010491
10492 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10493 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10494
10495 return false;
10496}
10497
Chris Lattner27b695d2007-11-06 21:52:06 +000010498/// PHIsEqualValue - Return true if this phi node is always equal to
10499/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10500/// z = some value; x = phi (y, z); y = phi (x, z)
10501static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10502 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10503 // See if we already saw this PHI node.
10504 if (!ValueEqualPHIs.insert(PN))
10505 return true;
10506
10507 // Don't scan crazily complex things.
10508 if (ValueEqualPHIs.size() == 16)
10509 return false;
10510
10511 // Scan the operands to see if they are either phi nodes or are equal to
10512 // the value.
10513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10514 Value *Op = PN->getIncomingValue(i);
10515 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10516 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10517 return false;
10518 } else if (Op != NonPhiInVal)
10519 return false;
10520 }
10521
10522 return true;
10523}
10524
10525
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010526// PHINode simplification
10527//
10528Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10529 // If LCSSA is around, don't mess with Phi nodes
10530 if (MustPreserveLCSSA) return 0;
10531
10532 if (Value *V = PN.hasConstantValue())
10533 return ReplaceInstUsesWith(PN, V);
10534
10535 // If all PHI operands are the same operation, pull them through the PHI,
10536 // reducing code size.
10537 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010538 isa<Instruction>(PN.getIncomingValue(1)) &&
10539 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10540 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10541 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10542 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010543 PN.getIncomingValue(0)->hasOneUse())
10544 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10545 return Result;
10546
10547 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10548 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10549 // PHI)... break the cycle.
10550 if (PN.hasOneUse()) {
10551 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10552 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10553 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10554 PotentiallyDeadPHIs.insert(&PN);
10555 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10556 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10557 }
10558
10559 // If this phi has a single use, and if that use just computes a value for
10560 // the next iteration of a loop, delete the phi. This occurs with unused
10561 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10562 // common case here is good because the only other things that catch this
10563 // are induction variable analysis (sometimes) and ADCE, which is only run
10564 // late.
10565 if (PHIUser->hasOneUse() &&
10566 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10567 PHIUser->use_back() == &PN) {
10568 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10569 }
10570 }
10571
Chris Lattner27b695d2007-11-06 21:52:06 +000010572 // We sometimes end up with phi cycles that non-obviously end up being the
10573 // same value, for example:
10574 // z = some value; x = phi (y, z); y = phi (x, z)
10575 // where the phi nodes don't necessarily need to be in the same block. Do a
10576 // quick check to see if the PHI node only contains a single non-phi value, if
10577 // so, scan to see if the phi cycle is actually equal to that value.
10578 {
10579 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10580 // Scan for the first non-phi operand.
10581 while (InValNo != NumOperandVals &&
10582 isa<PHINode>(PN.getIncomingValue(InValNo)))
10583 ++InValNo;
10584
10585 if (InValNo != NumOperandVals) {
10586 Value *NonPhiInVal = PN.getOperand(InValNo);
10587
10588 // Scan the rest of the operands to see if there are any conflicts, if so
10589 // there is no need to recursively scan other phis.
10590 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10591 Value *OpVal = PN.getIncomingValue(InValNo);
10592 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10593 break;
10594 }
10595
10596 // If we scanned over all operands, then we have one unique value plus
10597 // phi values. Scan PHI nodes to see if they all merge in each other or
10598 // the value.
10599 if (InValNo == NumOperandVals) {
10600 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10601 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10602 return ReplaceInstUsesWith(PN, NonPhiInVal);
10603 }
10604 }
10605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010606 return 0;
10607}
10608
10609static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10610 Instruction *InsertPoint,
10611 InstCombiner *IC) {
10612 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10613 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10614 // We must cast correctly to the pointer type. Ensure that we
10615 // sign extend the integer value if it is smaller as this is
10616 // used for address computation.
10617 Instruction::CastOps opcode =
10618 (VTySize < PtrSize ? Instruction::SExt :
10619 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10620 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10621}
10622
10623
10624Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10625 Value *PtrOp = GEP.getOperand(0);
10626 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10627 // If so, eliminate the noop.
10628 if (GEP.getNumOperands() == 1)
10629 return ReplaceInstUsesWith(GEP, PtrOp);
10630
10631 if (isa<UndefValue>(GEP.getOperand(0)))
10632 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10633
10634 bool HasZeroPointerIndex = false;
10635 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10636 HasZeroPointerIndex = C->isNullValue();
10637
10638 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10639 return ReplaceInstUsesWith(GEP, PtrOp);
10640
10641 // Eliminate unneeded casts for indices.
10642 bool MadeChange = false;
10643
10644 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010645 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10646 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010647 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000010648 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010649 if (CI->getOpcode() == Instruction::ZExt ||
10650 CI->getOpcode() == Instruction::SExt) {
10651 const Type *SrcTy = CI->getOperand(0)->getType();
10652 // We can eliminate a cast from i32 to i64 iff the target
10653 // is a 32-bit pointer target.
10654 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10655 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000010656 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010657 }
10658 }
10659 }
10660 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000010661 // to what we need. If narrower, sign-extend it to what we need.
10662 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010663 // insert it. This explicit cast can make subsequent optimizations more
10664 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000010665 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010666 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010667 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +000010668 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010669 MadeChange = true;
10670 } else {
10671 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10672 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010673 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010674 MadeChange = true;
10675 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000010676 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10677 if (Constant *C = dyn_cast<Constant>(Op)) {
10678 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10679 MadeChange = true;
10680 } else {
10681 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10682 GEP);
10683 *i = Op;
10684 MadeChange = true;
10685 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010687 }
10688 }
10689 if (MadeChange) return &GEP;
10690
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010691 // Combine Indices - If the source pointer to this getelementptr instruction
10692 // is a getelementptr instruction, combine the indices of the two
10693 // getelementptr instructions into a single instruction.
10694 //
10695 SmallVector<Value*, 8> SrcGEPOperands;
10696 if (User *Src = dyn_castGetElementPtr(PtrOp))
10697 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10698
10699 if (!SrcGEPOperands.empty()) {
10700 // Note that if our source is a gep chain itself that we wait for that
10701 // chain to be resolved before we perform this transformation. This
10702 // avoids us creating a TON of code in some cases.
10703 //
10704 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10705 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10706 return 0; // Wait until our source is folded to completion.
10707
10708 SmallVector<Value*, 8> Indices;
10709
10710 // Find out whether the last index in the source GEP is a sequential idx.
10711 bool EndsWithSequential = false;
10712 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10713 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10714 EndsWithSequential = !isa<StructType>(*I);
10715
10716 // Can we combine the two pointer arithmetics offsets?
10717 if (EndsWithSequential) {
10718 // Replace: gep (gep %P, long B), long A, ...
10719 // With: T = long A+B; gep %P, T, ...
10720 //
10721 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10722 if (SO1 == Constant::getNullValue(SO1->getType())) {
10723 Sum = GO1;
10724 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10725 Sum = SO1;
10726 } else {
10727 // If they aren't the same type, convert both to an integer of the
10728 // target's pointer size.
10729 if (SO1->getType() != GO1->getType()) {
10730 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10731 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10732 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10733 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10734 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010735 unsigned PS = TD->getPointerSizeInBits();
10736 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010737 // Convert GO1 to SO1's type.
10738 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10739
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010740 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010741 // Convert SO1 to GO1's type.
10742 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10743 } else {
10744 const Type *PT = TD->getIntPtrType();
10745 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10746 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10747 }
10748 }
10749 }
10750 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10751 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10752 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010753 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010754 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10755 }
10756 }
10757
10758 // Recycle the GEP we already have if possible.
10759 if (SrcGEPOperands.size() == 2) {
10760 GEP.setOperand(0, SrcGEPOperands[0]);
10761 GEP.setOperand(1, Sum);
10762 return &GEP;
10763 } else {
10764 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10765 SrcGEPOperands.end()-1);
10766 Indices.push_back(Sum);
10767 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10768 }
10769 } else if (isa<Constant>(*GEP.idx_begin()) &&
10770 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10771 SrcGEPOperands.size() != 1) {
10772 // Otherwise we can do the fold if the first index of the GEP is a zero
10773 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10774 SrcGEPOperands.end());
10775 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10776 }
10777
10778 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010779 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10780 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010781
10782 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10783 // GEP of global variable. If all of the indices for this GEP are
10784 // constants, we can promote this to a constexpr instead of an instruction.
10785
10786 // Scan for nonconstants...
10787 SmallVector<Constant*, 8> Indices;
10788 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10789 for (; I != E && isa<Constant>(*I); ++I)
10790 Indices.push_back(cast<Constant>(*I));
10791
10792 if (I == E) { // If they are all constants...
10793 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10794 &Indices[0],Indices.size());
10795
10796 // Replace all uses of the GEP with the new constexpr...
10797 return ReplaceInstUsesWith(GEP, CE);
10798 }
10799 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10800 if (!isa<PointerType>(X->getType())) {
10801 // Not interesting. Source pointer must be a cast from pointer.
10802 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010803 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10804 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010805 //
Duncan Sandscf866e62009-03-02 09:18:21 +000010806 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10807 // into : GEP i8* X, ...
10808 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010809 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010810 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10811 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000010812 if (const ArrayType *CATy =
10813 dyn_cast<ArrayType>(CPTy->getElementType())) {
10814 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10815 if (CATy->getElementType() == XTy->getElementType()) {
10816 // -> GEP i8* X, ...
10817 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10818 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10819 GEP.getName());
10820 } else if (const ArrayType *XATy =
10821 dyn_cast<ArrayType>(XTy->getElementType())) {
10822 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010823 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000010824 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010825 // At this point, we know that the cast source type is a pointer
10826 // to an array of the same type as the destination pointer
10827 // array. Because the array type is never stepped over (there
10828 // is a leading zero) we can fold the cast into this GEP.
10829 GEP.setOperand(0, X);
10830 return &GEP;
10831 }
Duncan Sandscf866e62009-03-02 09:18:21 +000010832 }
10833 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010834 } else if (GEP.getNumOperands() == 2) {
10835 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010836 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10837 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010838 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10839 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10840 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010841 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10842 TD->getTypePaddedSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010843 Value *Idx[2];
10844 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10845 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010846 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010847 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010848 // V and GEP are both pointer types --> BitCast
10849 return new BitCastInst(V, GEP.getType());
10850 }
10851
10852 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010853 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010854 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010855 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010856
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010857 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010858 uint64_t ArrayEltSize =
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010859 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010860
10861 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10862 // allow either a mul, shift, or constant here.
10863 Value *NewIdx = 0;
10864 ConstantInt *Scale = 0;
10865 if (ArrayEltSize == 1) {
10866 NewIdx = GEP.getOperand(1);
10867 Scale = ConstantInt::get(NewIdx->getType(), 1);
10868 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10869 NewIdx = ConstantInt::get(CI->getType(), 1);
10870 Scale = CI;
10871 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10872 if (Inst->getOpcode() == Instruction::Shl &&
10873 isa<ConstantInt>(Inst->getOperand(1))) {
10874 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10875 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10876 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10877 NewIdx = Inst->getOperand(0);
10878 } else if (Inst->getOpcode() == Instruction::Mul &&
10879 isa<ConstantInt>(Inst->getOperand(1))) {
10880 Scale = cast<ConstantInt>(Inst->getOperand(1));
10881 NewIdx = Inst->getOperand(0);
10882 }
10883 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010884
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010885 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010886 // out, perform the transformation. Note, we don't know whether Scale is
10887 // signed or not. We'll use unsigned version of division/modulo
10888 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000010889 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010890 Scale->getZExtValue() % ArrayEltSize == 0) {
10891 Scale = ConstantInt::get(Scale->getType(),
10892 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010893 if (Scale->getZExtValue() != 1) {
10894 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010895 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010896 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010897 NewIdx = InsertNewInstBefore(Sc, GEP);
10898 }
10899
10900 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010901 Value *Idx[2];
10902 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10903 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010904 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010905 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010906 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10907 // The NewGEP must be pointer typed, so must the old one -> BitCast
10908 return new BitCastInst(NewGEP, GEP.getType());
10909 }
10910 }
10911 }
10912 }
Chris Lattner111ea772009-01-09 04:53:57 +000010913
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010914 /// See if we can simplify:
10915 /// X = bitcast A to B*
10916 /// Y = gep X, <...constant indices...>
10917 /// into a gep of the original struct. This is important for SROA and alias
10918 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000010919 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010920 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10921 // Determine how much the GEP moves the pointer. We are guaranteed to get
10922 // a constant back from EmitGEPOffset.
10923 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10924 int64_t Offset = OffsetV->getSExtValue();
10925
10926 // If this GEP instruction doesn't move the pointer, just replace the GEP
10927 // with a bitcast of the real input to the dest type.
10928 if (Offset == 0) {
10929 // If the bitcast is of an allocation, and the allocation will be
10930 // converted to match the type of the cast, don't touch this.
10931 if (isa<AllocationInst>(BCI->getOperand(0))) {
10932 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10933 if (Instruction *I = visitBitCast(*BCI)) {
10934 if (I != BCI) {
10935 I->takeName(BCI);
10936 BCI->getParent()->getInstList().insert(BCI, I);
10937 ReplaceInstUsesWith(*BCI, I);
10938 }
10939 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000010940 }
Chris Lattner111ea772009-01-09 04:53:57 +000010941 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010942 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000010943 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010944
10945 // Otherwise, if the offset is non-zero, we need to find out if there is a
10946 // field at Offset in 'A's type. If so, we can pull the cast through the
10947 // GEP.
10948 SmallVector<Value*, 8> NewIndices;
10949 const Type *InTy =
10950 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10951 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10952 Instruction *NGEP =
10953 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10954 NewIndices.end());
10955 if (NGEP->getType() == GEP.getType()) return NGEP;
10956 InsertNewInstBefore(NGEP, GEP);
10957 NGEP->takeName(&GEP);
10958 return new BitCastInst(NGEP, GEP.getType());
10959 }
Chris Lattner111ea772009-01-09 04:53:57 +000010960 }
10961 }
10962
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010963 return 0;
10964}
10965
10966Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10967 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010968 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010969 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10970 const Type *NewTy =
10971 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10972 AllocationInst *New = 0;
10973
10974 // Create and insert the replacement instruction...
10975 if (isa<MallocInst>(AI))
10976 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10977 else {
10978 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10979 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10980 }
10981
10982 InsertNewInstBefore(New, AI);
10983
10984 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000010985 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010986 //
10987 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000010988 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010989
10990 // Now that I is pointing to the first non-allocation-inst in the block,
10991 // insert our getelementptr instruction...
10992 //
10993 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010994 Value *Idx[2];
10995 Idx[0] = NullIdx;
10996 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010997 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10998 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010999
11000 // Now make everything use the getelementptr instead of the original
11001 // allocation.
11002 return ReplaceInstUsesWith(AI, V);
11003 } else if (isa<UndefValue>(AI.getArraySize())) {
11004 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11005 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011006 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011007
Dan Gohman28e78f02009-01-13 20:18:38 +000011008 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11009 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011010 // Note that we only do this for alloca's, because malloc should allocate
11011 // and return a unique pointer, even for a zero byte allocation.
Dan Gohman28e78f02009-01-13 20:18:38 +000011012 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
11013 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11014
11015 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11016 if (AI.getAlignment() == 0)
11017 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11018 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011019
11020 return 0;
11021}
11022
11023Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11024 Value *Op = FI.getOperand(0);
11025
11026 // free undef -> unreachable.
11027 if (isa<UndefValue>(Op)) {
11028 // Insert a new store to null because we cannot modify the CFG here.
11029 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000011030 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031 return EraseInstFromFunction(FI);
11032 }
11033
11034 // If we have 'free null' delete the instruction. This can happen in stl code
11035 // when lots of inlining happens.
11036 if (isa<ConstantPointerNull>(Op))
11037 return EraseInstFromFunction(FI);
11038
11039 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11040 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11041 FI.setOperand(0, CI->getOperand(0));
11042 return &FI;
11043 }
11044
11045 // Change free (gep X, 0,0,0,0) into free(X)
11046 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11047 if (GEPI->hasAllZeroIndices()) {
11048 AddToWorkList(GEPI);
11049 FI.setOperand(0, GEPI->getOperand(0));
11050 return &FI;
11051 }
11052 }
11053
11054 // Change free(malloc) into nothing, if the malloc has a single use.
11055 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11056 if (MI->hasOneUse()) {
11057 EraseInstFromFunction(FI);
11058 return EraseInstFromFunction(*MI);
11059 }
11060
11061 return 0;
11062}
11063
11064
11065/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011066static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011067 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011068 User *CI = cast<User>(LI.getOperand(0));
11069 Value *CastOp = CI->getOperand(0);
11070
Devang Patela0f8ea82007-10-18 19:52:32 +000011071 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11072 // Instead of loading constant c string, use corresponding integer value
11073 // directly if string length is small enough.
Bill Wendlingf3f16e82009-03-13 04:39:26 +000011074 std::string Str;
11075 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11076 unsigned len = Str.length();
Devang Patela0f8ea82007-10-18 19:52:32 +000011077 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11078 unsigned numBits = Ty->getPrimitiveSizeInBits();
11079 // Replace LI with immediate integer store.
11080 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000011081 APInt StrVal(numBits, 0);
11082 APInt SingleChar(numBits, 0);
11083 if (TD->isLittleEndian()) {
11084 for (signed i = len-1; i >= 0; i--) {
Nick Lewycky1803a022009-02-21 20:50:42 +000011085 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011086 StrVal = (StrVal << 8) | SingleChar;
11087 }
11088 } else {
11089 for (unsigned i = 0; i < len; i++) {
Nick Lewycky1803a022009-02-21 20:50:42 +000011090 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011091 StrVal = (StrVal << 8) | SingleChar;
11092 }
11093 // Append NULL at the end.
11094 SingleChar = 0;
11095 StrVal = (StrVal << 8) | SingleChar;
11096 }
11097 Value *NL = ConstantInt::get(StrVal);
11098 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000011099 }
11100 }
11101 }
11102
Mon P Wangbd05ed82009-02-07 22:19:29 +000011103 const PointerType *DestTy = cast<PointerType>(CI->getType());
11104 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011105 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011106
11107 // If the address spaces don't match, don't eliminate the cast.
11108 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11109 return 0;
11110
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011111 const Type *SrcPTy = SrcTy->getElementType();
11112
11113 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11114 isa<VectorType>(DestPTy)) {
11115 // If the source is an array, the code below will not succeed. Check to
11116 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11117 // constants.
11118 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11119 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11120 if (ASrcTy->getNumElements() != 0) {
11121 Value *Idxs[2];
11122 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11123 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11124 SrcTy = cast<PointerType>(CastOp->getType());
11125 SrcPTy = SrcTy->getElementType();
11126 }
11127
11128 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11129 isa<VectorType>(SrcPTy)) &&
11130 // Do not allow turning this into a load of an integer, which is then
11131 // casted to a pointer, this pessimizes pointer analysis a lot.
11132 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11133 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11134 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11135
11136 // Okay, we are casting from one integer or pointer type to another of
11137 // the same size. Instead of casting the pointer before the load, cast
11138 // the result of the loaded value.
11139 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11140 CI->getName(),
11141 LI.isVolatile()),LI);
11142 // Now cast the result of the load.
11143 return new BitCastInst(NewLoad, LI.getType());
11144 }
11145 }
11146 }
11147 return 0;
11148}
11149
11150/// isSafeToLoadUnconditionally - Return true if we know that executing a load
11151/// from this value cannot trap. If it is not obviously safe to load from the
11152/// specified pointer, we do a quick local scan of the basic block containing
11153/// ScanFrom, to determine if the address is already accessed.
11154static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000011155 // If it is an alloca it is always safe to load from.
11156 if (isa<AllocaInst>(V)) return true;
11157
Duncan Sandse40a94a2007-09-19 10:25:38 +000011158 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000011159 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000011160 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000011161 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011162
11163 // Otherwise, be a little bit agressive by scanning the local block where we
11164 // want to check to see if the pointer is already being loaded or stored
11165 // from/to. If so, the previous load or store would have already trapped,
11166 // so there is no harm doing an extra load (also, CSE will later eliminate
11167 // the load entirely).
11168 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11169
11170 while (BBI != E) {
11171 --BBI;
11172
Chris Lattner476983a2008-06-20 05:12:56 +000011173 // If we see a free or a call (which might do a free) the pointer could be
11174 // marked invalid.
Dale Johannesen966d6632009-03-13 19:23:20 +000011175 if (isa<FreeInst>(BBI) ||
11176 (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
Chris Lattner476983a2008-06-20 05:12:56 +000011177 return false;
11178
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011179 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11180 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000011181 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011182 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000011183 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011184
11185 }
11186 return false;
11187}
11188
11189Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11190 Value *Op = LI.getOperand(0);
11191
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011192 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011193 unsigned KnownAlign =
11194 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011195 if (KnownAlign >
11196 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11197 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011198 LI.setAlignment(KnownAlign);
11199
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011200 // load (cast X) --> cast (load X) iff safe
11201 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011202 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011203 return Res;
11204
11205 // None of the following transforms are legal for volatile loads.
11206 if (LI.isVolatile()) return 0;
11207
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011208 // Do really simple store-to-load forwarding and load CSE, to catch cases
11209 // where there are several consequtive memory accesses to the same location,
11210 // separated by a few arithmetic operations.
11211 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011212 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11213 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214
Christopher Lamb2c175392007-12-29 07:56:53 +000011215 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11216 const Value *GEPI0 = GEPI->getOperand(0);
11217 // TODO: Consider a target hook for valid address spaces for this xform.
11218 if (isa<ConstantPointerNull>(GEPI0) &&
11219 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011220 // Insert a new store to null instruction before the load to indicate
11221 // that this code is not reachable. We do this instead of inserting
11222 // an unreachable instruction directly because we cannot modify the
11223 // CFG.
11224 new StoreInst(UndefValue::get(LI.getType()),
11225 Constant::getNullValue(Op->getType()), &LI);
11226 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11227 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011229
11230 if (Constant *C = dyn_cast<Constant>(Op)) {
11231 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011232 // TODO: Consider a target hook for valid address spaces for this xform.
11233 if (isa<UndefValue>(C) || (C->isNullValue() &&
11234 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011235 // Insert a new store to null instruction before the load to indicate that
11236 // this code is not reachable. We do this instead of inserting an
11237 // unreachable instruction directly because we cannot modify the CFG.
11238 new StoreInst(UndefValue::get(LI.getType()),
11239 Constant::getNullValue(Op->getType()), &LI);
11240 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11241 }
11242
11243 // Instcombine load (constant global) into the value loaded.
11244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011245 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011246 return ReplaceInstUsesWith(LI, GV->getInitializer());
11247
11248 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011249 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011250 if (CE->getOpcode() == Instruction::GetElementPtr) {
11251 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011252 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011253 if (Constant *V =
11254 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11255 return ReplaceInstUsesWith(LI, V);
11256 if (CE->getOperand(0)->isNullValue()) {
11257 // Insert a new store to null instruction before the load to indicate
11258 // that this code is not reachable. We do this instead of inserting
11259 // an unreachable instruction directly because we cannot modify the
11260 // CFG.
11261 new StoreInst(UndefValue::get(LI.getType()),
11262 Constant::getNullValue(Op->getType()), &LI);
11263 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11264 }
11265
11266 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011267 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011268 return Res;
11269 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011270 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 }
Chris Lattner0270a112007-08-11 18:48:48 +000011272
11273 // If this load comes from anywhere in a constant global, and if the global
11274 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011275 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011276 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011277 if (GV->getInitializer()->isNullValue())
11278 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11279 else if (isa<UndefValue>(GV->getInitializer()))
11280 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11281 }
11282 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011283
11284 if (Op->hasOneUse()) {
11285 // Change select and PHI nodes to select values instead of addresses: this
11286 // helps alias analysis out a lot, allows many others simplifications, and
11287 // exposes redundancy in the code.
11288 //
11289 // Note that we cannot do the transformation unless we know that the
11290 // introduced loads cannot trap! Something like this is valid as long as
11291 // the condition is always false: load (select bool %C, int* null, int* %G),
11292 // but it would not be valid if we transformed it to load from null
11293 // unconditionally.
11294 //
11295 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11296 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11297 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11298 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11299 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11300 SI->getOperand(1)->getName()+".val"), LI);
11301 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11302 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011303 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011304 }
11305
11306 // load (select (cond, null, P)) -> load P
11307 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11308 if (C->isNullValue()) {
11309 LI.setOperand(0, SI->getOperand(2));
11310 return &LI;
11311 }
11312
11313 // load (select (cond, P, null)) -> load P
11314 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11315 if (C->isNullValue()) {
11316 LI.setOperand(0, SI->getOperand(1));
11317 return &LI;
11318 }
11319 }
11320 }
11321 return 0;
11322}
11323
11324/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011325/// when possible. This makes it generally easy to do alias analysis and/or
11326/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011327static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11328 User *CI = cast<User>(SI.getOperand(1));
11329 Value *CastOp = CI->getOperand(0);
11330
11331 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011332 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11333 if (SrcTy == 0) return 0;
11334
11335 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011336
Chris Lattnera032c0e2009-01-16 20:08:59 +000011337 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11338 return 0;
11339
Chris Lattner54dddc72009-01-24 01:00:13 +000011340 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11341 /// to its first element. This allows us to handle things like:
11342 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11343 /// on 32-bit hosts.
11344 SmallVector<Value*, 4> NewGEPIndices;
11345
Chris Lattnera032c0e2009-01-16 20:08:59 +000011346 // If the source is an array, the code below will not succeed. Check to
11347 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11348 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011349 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11350 // Index through pointer.
11351 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11352 NewGEPIndices.push_back(Zero);
11353
11354 while (1) {
11355 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011356 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011357 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011358 NewGEPIndices.push_back(Zero);
11359 SrcPTy = STy->getElementType(0);
11360 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11361 NewGEPIndices.push_back(Zero);
11362 SrcPTy = ATy->getElementType();
11363 } else {
11364 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011365 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011366 }
11367
11368 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11369 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011370
11371 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11372 return 0;
11373
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011374 // If the pointers point into different address spaces or if they point to
11375 // values with different sizes, we can't do the transformation.
11376 if (SrcTy->getAddressSpace() !=
11377 cast<PointerType>(CI->getType())->getAddressSpace() ||
11378 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattnera032c0e2009-01-16 20:08:59 +000011379 IC.getTargetData().getTypeSizeInBits(DestPTy))
11380 return 0;
11381
11382 // Okay, we are casting from one integer or pointer type to another of
11383 // the same size. Instead of casting the pointer before
11384 // the store, cast the value to be stored.
11385 Value *NewCast;
11386 Value *SIOp0 = SI.getOperand(0);
11387 Instruction::CastOps opcode = Instruction::BitCast;
11388 const Type* CastSrcTy = SIOp0->getType();
11389 const Type* CastDstTy = SrcPTy;
11390 if (isa<PointerType>(CastDstTy)) {
11391 if (CastSrcTy->isInteger())
11392 opcode = Instruction::IntToPtr;
11393 } else if (isa<IntegerType>(CastDstTy)) {
11394 if (isa<PointerType>(SIOp0->getType()))
11395 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011396 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011397
11398 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11399 // emit a GEP to index into its first field.
11400 if (!NewGEPIndices.empty()) {
11401 if (Constant *C = dyn_cast<Constant>(CastOp))
11402 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11403 NewGEPIndices.size());
11404 else
11405 CastOp = IC.InsertNewInstBefore(
11406 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11407 NewGEPIndices.end()), SI);
11408 }
11409
Chris Lattnera032c0e2009-01-16 20:08:59 +000011410 if (Constant *C = dyn_cast<Constant>(SIOp0))
11411 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11412 else
11413 NewCast = IC.InsertNewInstBefore(
11414 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11415 SI);
11416 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417}
11418
Chris Lattner6fd8c802008-11-27 08:56:30 +000011419/// equivalentAddressValues - Test if A and B will obviously have the same
11420/// value. This includes recognizing that %t0 and %t1 will have the same
11421/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011422/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011423/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011424/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011425/// %t2 = load i32* %t1
11426///
11427static bool equivalentAddressValues(Value *A, Value *B) {
11428 // Test if the values are trivially equivalent.
11429 if (A == B) return true;
11430
11431 // Test if the values come form identical arithmetic instructions.
11432 if (isa<BinaryOperator>(A) ||
11433 isa<CastInst>(A) ||
11434 isa<PHINode>(A) ||
11435 isa<GetElementPtrInst>(A))
11436 if (Instruction *BI = dyn_cast<Instruction>(B))
11437 if (cast<Instruction>(A)->isIdenticalTo(BI))
11438 return true;
11439
11440 // Otherwise they may not be equivalent.
11441 return false;
11442}
11443
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011444// If this instruction has two uses, one of which is a llvm.dbg.declare,
11445// return the llvm.dbg.declare.
11446DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11447 if (!V->hasNUses(2))
11448 return 0;
11449 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11450 UI != E; ++UI) {
11451 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11452 return DI;
11453 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11454 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11455 return DI;
11456 }
11457 }
11458 return 0;
11459}
11460
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011461Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11462 Value *Val = SI.getOperand(0);
11463 Value *Ptr = SI.getOperand(1);
11464
11465 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11466 EraseInstFromFunction(SI);
11467 ++NumCombined;
11468 return 0;
11469 }
11470
11471 // If the RHS is an alloca with a single use, zapify the store, making the
11472 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011473 // If the RHS is an alloca with a two uses, the other one being a
11474 // llvm.dbg.declare, zapify the store and the declare, making the
11475 // alloca dead. We must do this to prevent declare's from affecting
11476 // codegen.
11477 if (!SI.isVolatile()) {
11478 if (Ptr->hasOneUse()) {
11479 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011480 EraseInstFromFunction(SI);
11481 ++NumCombined;
11482 return 0;
11483 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011484 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11485 if (isa<AllocaInst>(GEP->getOperand(0))) {
11486 if (GEP->getOperand(0)->hasOneUse()) {
11487 EraseInstFromFunction(SI);
11488 ++NumCombined;
11489 return 0;
11490 }
11491 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11492 EraseInstFromFunction(*DI);
11493 EraseInstFromFunction(SI);
11494 ++NumCombined;
11495 return 0;
11496 }
11497 }
11498 }
11499 }
11500 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11501 EraseInstFromFunction(*DI);
11502 EraseInstFromFunction(SI);
11503 ++NumCombined;
11504 return 0;
11505 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011506 }
11507
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011508 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011509 unsigned KnownAlign =
11510 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011511 if (KnownAlign >
11512 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11513 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011514 SI.setAlignment(KnownAlign);
11515
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011516 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011517 // stores to the same location, separated by a few arithmetic operations. This
11518 // situation often occurs with bitfield accesses.
11519 BasicBlock::iterator BBI = &SI;
11520 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11521 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011522 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011523 // Don't count debug info directives, lest they affect codegen,
11524 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11525 // It is necessary for correctness to skip those that feed into a
11526 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011527 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011528 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011529 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011530 continue;
11531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011532
11533 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11534 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011535 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11536 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011537 ++NumDeadStore;
11538 ++BBI;
11539 EraseInstFromFunction(*PrevSI);
11540 continue;
11541 }
11542 break;
11543 }
11544
11545 // If this is a load, we have to stop. However, if the loaded value is from
11546 // the pointer we're loading and is producing the pointer we're storing,
11547 // then *this* store is dead (X = load P; store X -> P).
11548 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011549 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11550 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011551 EraseInstFromFunction(SI);
11552 ++NumCombined;
11553 return 0;
11554 }
11555 // Otherwise, this is a load from some other location. Stores before it
11556 // may not be dead.
11557 break;
11558 }
11559
11560 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011561 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011562 break;
11563 }
11564
11565
11566 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11567
11568 // store X, null -> turns into 'unreachable' in SimplifyCFG
11569 if (isa<ConstantPointerNull>(Ptr)) {
11570 if (!isa<UndefValue>(Val)) {
11571 SI.setOperand(0, UndefValue::get(Val->getType()));
11572 if (Instruction *U = dyn_cast<Instruction>(Val))
11573 AddToWorkList(U); // Dropped a use.
11574 ++NumCombined;
11575 }
11576 return 0; // Do not modify these!
11577 }
11578
11579 // store undef, Ptr -> noop
11580 if (isa<UndefValue>(Val)) {
11581 EraseInstFromFunction(SI);
11582 ++NumCombined;
11583 return 0;
11584 }
11585
11586 // If the pointer destination is a cast, see if we can fold the cast into the
11587 // source instead.
11588 if (isa<CastInst>(Ptr))
11589 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11590 return Res;
11591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11592 if (CE->isCast())
11593 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11594 return Res;
11595
11596
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011597 // If this store is the last instruction in the basic block (possibly
11598 // excepting debug info instructions and the pointer bitcasts that feed
11599 // into them), and if the block ends with an unconditional branch, try
11600 // to move it to the successor block.
11601 BBI = &SI;
11602 do {
11603 ++BBI;
11604 } while (isa<DbgInfoIntrinsic>(BBI) ||
11605 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011606 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11607 if (BI->isUnconditional())
11608 if (SimplifyStoreAtEndOfBlock(SI))
11609 return 0; // xform done!
11610
11611 return 0;
11612}
11613
11614/// SimplifyStoreAtEndOfBlock - Turn things like:
11615/// if () { *P = v1; } else { *P = v2 }
11616/// into a phi node with a store in the successor.
11617///
11618/// Simplify things like:
11619/// *P = v1; if () { *P = v2; }
11620/// into a phi node with a store in the successor.
11621///
11622bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11623 BasicBlock *StoreBB = SI.getParent();
11624
11625 // Check to see if the successor block has exactly two incoming edges. If
11626 // so, see if the other predecessor contains a store to the same location.
11627 // if so, insert a PHI node (if needed) and move the stores down.
11628 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11629
11630 // Determine whether Dest has exactly two predecessors and, if so, compute
11631 // the other predecessor.
11632 pred_iterator PI = pred_begin(DestBB);
11633 BasicBlock *OtherBB = 0;
11634 if (*PI != StoreBB)
11635 OtherBB = *PI;
11636 ++PI;
11637 if (PI == pred_end(DestBB))
11638 return false;
11639
11640 if (*PI != StoreBB) {
11641 if (OtherBB)
11642 return false;
11643 OtherBB = *PI;
11644 }
11645 if (++PI != pred_end(DestBB))
11646 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011647
11648 // Bail out if all the relevant blocks aren't distinct (this can happen,
11649 // for example, if SI is in an infinite loop)
11650 if (StoreBB == DestBB || OtherBB == DestBB)
11651 return false;
11652
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011653 // Verify that the other block ends in a branch and is not otherwise empty.
11654 BasicBlock::iterator BBI = OtherBB->getTerminator();
11655 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11656 if (!OtherBr || BBI == OtherBB->begin())
11657 return false;
11658
11659 // If the other block ends in an unconditional branch, check for the 'if then
11660 // else' case. there is an instruction before the branch.
11661 StoreInst *OtherStore = 0;
11662 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011663 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011664 // Skip over debugging info.
11665 while (isa<DbgInfoIntrinsic>(BBI) ||
11666 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11667 if (BBI==OtherBB->begin())
11668 return false;
11669 --BBI;
11670 }
11671 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011672 OtherStore = dyn_cast<StoreInst>(BBI);
11673 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11674 return false;
11675 } else {
11676 // Otherwise, the other block ended with a conditional branch. If one of the
11677 // destinations is StoreBB, then we have the if/then case.
11678 if (OtherBr->getSuccessor(0) != StoreBB &&
11679 OtherBr->getSuccessor(1) != StoreBB)
11680 return false;
11681
11682 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11683 // if/then triangle. See if there is a store to the same ptr as SI that
11684 // lives in OtherBB.
11685 for (;; --BBI) {
11686 // Check to see if we find the matching store.
11687 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11688 if (OtherStore->getOperand(1) != SI.getOperand(1))
11689 return false;
11690 break;
11691 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011692 // If we find something that may be using or overwriting the stored
11693 // value, or if we run out of instructions, we can't do the xform.
11694 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011695 BBI == OtherBB->begin())
11696 return false;
11697 }
11698
11699 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011700 // make sure nothing reads or overwrites the stored value in
11701 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011702 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11703 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011704 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011705 return false;
11706 }
11707 }
11708
11709 // Insert a PHI node now if we need it.
11710 Value *MergedVal = OtherStore->getOperand(0);
11711 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011712 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011713 PN->reserveOperandSpace(2);
11714 PN->addIncoming(SI.getOperand(0), SI.getParent());
11715 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11716 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11717 }
11718
11719 // Advance to a place where it is safe to insert the new store and
11720 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011721 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011722 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11723 OtherStore->isVolatile()), *BBI);
11724
11725 // Nuke the old stores.
11726 EraseInstFromFunction(SI);
11727 EraseInstFromFunction(*OtherStore);
11728 ++NumCombined;
11729 return true;
11730}
11731
11732
11733Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11734 // Change br (not X), label True, label False to: br X, label False, True
11735 Value *X = 0;
11736 BasicBlock *TrueDest;
11737 BasicBlock *FalseDest;
11738 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11739 !isa<Constant>(X)) {
11740 // Swap Destinations and condition...
11741 BI.setCondition(X);
11742 BI.setSuccessor(0, FalseDest);
11743 BI.setSuccessor(1, TrueDest);
11744 return &BI;
11745 }
11746
11747 // Cannonicalize fcmp_one -> fcmp_oeq
11748 FCmpInst::Predicate FPred; Value *Y;
11749 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11750 TrueDest, FalseDest)))
11751 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11752 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11753 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11754 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11755 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11756 NewSCC->takeName(I);
11757 // Swap Destinations and condition...
11758 BI.setCondition(NewSCC);
11759 BI.setSuccessor(0, FalseDest);
11760 BI.setSuccessor(1, TrueDest);
11761 RemoveFromWorkList(I);
11762 I->eraseFromParent();
11763 AddToWorkList(NewSCC);
11764 return &BI;
11765 }
11766
11767 // Cannonicalize icmp_ne -> icmp_eq
11768 ICmpInst::Predicate IPred;
11769 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11770 TrueDest, FalseDest)))
11771 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11772 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11773 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11774 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11775 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11776 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11777 NewSCC->takeName(I);
11778 // Swap Destinations and condition...
11779 BI.setCondition(NewSCC);
11780 BI.setSuccessor(0, FalseDest);
11781 BI.setSuccessor(1, TrueDest);
11782 RemoveFromWorkList(I);
11783 I->eraseFromParent();;
11784 AddToWorkList(NewSCC);
11785 return &BI;
11786 }
11787
11788 return 0;
11789}
11790
11791Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11792 Value *Cond = SI.getCondition();
11793 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11794 if (I->getOpcode() == Instruction::Add)
11795 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11796 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11797 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11798 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11799 AddRHS));
11800 SI.setOperand(0, I->getOperand(0));
11801 AddToWorkList(I);
11802 return &SI;
11803 }
11804 }
11805 return 0;
11806}
11807
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011808Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011809 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011810
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011811 if (!EV.hasIndices())
11812 return ReplaceInstUsesWith(EV, Agg);
11813
11814 if (Constant *C = dyn_cast<Constant>(Agg)) {
11815 if (isa<UndefValue>(C))
11816 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11817
11818 if (isa<ConstantAggregateZero>(C))
11819 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11820
11821 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11822 // Extract the element indexed by the first index out of the constant
11823 Value *V = C->getOperand(*EV.idx_begin());
11824 if (EV.getNumIndices() > 1)
11825 // Extract the remaining indices out of the constant indexed by the
11826 // first index
11827 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11828 else
11829 return ReplaceInstUsesWith(EV, V);
11830 }
11831 return 0; // Can't handle other constants
11832 }
11833 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11834 // We're extracting from an insertvalue instruction, compare the indices
11835 const unsigned *exti, *exte, *insi, *inse;
11836 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11837 exte = EV.idx_end(), inse = IV->idx_end();
11838 exti != exte && insi != inse;
11839 ++exti, ++insi) {
11840 if (*insi != *exti)
11841 // The insert and extract both reference distinctly different elements.
11842 // This means the extract is not influenced by the insert, and we can
11843 // replace the aggregate operand of the extract with the aggregate
11844 // operand of the insert. i.e., replace
11845 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11846 // %E = extractvalue { i32, { i32 } } %I, 0
11847 // with
11848 // %E = extractvalue { i32, { i32 } } %A, 0
11849 return ExtractValueInst::Create(IV->getAggregateOperand(),
11850 EV.idx_begin(), EV.idx_end());
11851 }
11852 if (exti == exte && insi == inse)
11853 // Both iterators are at the end: Index lists are identical. Replace
11854 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11855 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11856 // with "i32 42"
11857 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11858 if (exti == exte) {
11859 // The extract list is a prefix of the insert list. i.e. replace
11860 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11861 // %E = extractvalue { i32, { i32 } } %I, 1
11862 // with
11863 // %X = extractvalue { i32, { i32 } } %A, 1
11864 // %E = insertvalue { i32 } %X, i32 42, 0
11865 // by switching the order of the insert and extract (though the
11866 // insertvalue should be left in, since it may have other uses).
11867 Value *NewEV = InsertNewInstBefore(
11868 ExtractValueInst::Create(IV->getAggregateOperand(),
11869 EV.idx_begin(), EV.idx_end()),
11870 EV);
11871 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11872 insi, inse);
11873 }
11874 if (insi == inse)
11875 // The insert list is a prefix of the extract list
11876 // We can simply remove the common indices from the extract and make it
11877 // operate on the inserted value instead of the insertvalue result.
11878 // i.e., replace
11879 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11880 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11881 // with
11882 // %E extractvalue { i32 } { i32 42 }, 0
11883 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11884 exti, exte);
11885 }
11886 // Can't simplify extracts from other values. Note that nested extracts are
11887 // already simplified implicitely by the above (extract ( extract (insert) )
11888 // will be translated into extract ( insert ( extract ) ) first and then just
11889 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011890 return 0;
11891}
11892
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011893/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11894/// is to leave as a vector operation.
11895static bool CheapToScalarize(Value *V, bool isConstant) {
11896 if (isa<ConstantAggregateZero>(V))
11897 return true;
11898 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11899 if (isConstant) return true;
11900 // If all elts are the same, we can extract.
11901 Constant *Op0 = C->getOperand(0);
11902 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11903 if (C->getOperand(i) != Op0)
11904 return false;
11905 return true;
11906 }
11907 Instruction *I = dyn_cast<Instruction>(V);
11908 if (!I) return false;
11909
11910 // Insert element gets simplified to the inserted element or is deleted if
11911 // this is constant idx extract element and its a constant idx insertelt.
11912 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11913 isa<ConstantInt>(I->getOperand(2)))
11914 return true;
11915 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11916 return true;
11917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11918 if (BO->hasOneUse() &&
11919 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11920 CheapToScalarize(BO->getOperand(1), isConstant)))
11921 return true;
11922 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11923 if (CI->hasOneUse() &&
11924 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11925 CheapToScalarize(CI->getOperand(1), isConstant)))
11926 return true;
11927
11928 return false;
11929}
11930
11931/// Read and decode a shufflevector mask.
11932///
11933/// It turns undef elements into values that are larger than the number of
11934/// elements in the input.
11935static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11936 unsigned NElts = SVI->getType()->getNumElements();
11937 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11938 return std::vector<unsigned>(NElts, 0);
11939 if (isa<UndefValue>(SVI->getOperand(2)))
11940 return std::vector<unsigned>(NElts, 2*NElts);
11941
11942 std::vector<unsigned> Result;
11943 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000011944 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11945 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011946 Result.push_back(NElts*2); // undef -> 8
11947 else
Gabor Greif17396002008-06-12 21:37:33 +000011948 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011949 return Result;
11950}
11951
11952/// FindScalarElement - Given a vector and an element number, see if the scalar
11953/// value is already around as a register, for example if it were inserted then
11954/// extracted from the vector.
11955static Value *FindScalarElement(Value *V, unsigned EltNo) {
11956 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11957 const VectorType *PTy = cast<VectorType>(V->getType());
11958 unsigned Width = PTy->getNumElements();
11959 if (EltNo >= Width) // Out of range access.
11960 return UndefValue::get(PTy->getElementType());
11961
11962 if (isa<UndefValue>(V))
11963 return UndefValue::get(PTy->getElementType());
11964 else if (isa<ConstantAggregateZero>(V))
11965 return Constant::getNullValue(PTy->getElementType());
11966 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11967 return CP->getOperand(EltNo);
11968 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11969 // If this is an insert to a variable element, we don't know what it is.
11970 if (!isa<ConstantInt>(III->getOperand(2)))
11971 return 0;
11972 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11973
11974 // If this is an insert to the element we are looking for, return the
11975 // inserted value.
11976 if (EltNo == IIElt)
11977 return III->getOperand(1);
11978
11979 // Otherwise, the insertelement doesn't modify the value, recurse on its
11980 // vector input.
11981 return FindScalarElement(III->getOperand(0), EltNo);
11982 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011983 unsigned LHSWidth =
11984 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011985 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011986 if (InEl < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011987 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011988 else if (InEl < LHSWidth*2)
11989 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011990 else
11991 return UndefValue::get(PTy->getElementType());
11992 }
11993
11994 // Otherwise, we don't know.
11995 return 0;
11996}
11997
11998Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011999 // If vector val is undef, replace extract with scalar undef.
12000 if (isa<UndefValue>(EI.getOperand(0)))
12001 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12002
12003 // If vector val is constant 0, replace extract with scalar 0.
12004 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12005 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12006
12007 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012008 // If vector val is constant with all elements the same, replace EI with
12009 // that element. When the elements are not identical, we cannot replace yet
12010 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012011 Constant *op0 = C->getOperand(0);
12012 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12013 if (C->getOperand(i) != op0) {
12014 op0 = 0;
12015 break;
12016 }
12017 if (op0)
12018 return ReplaceInstUsesWith(EI, op0);
12019 }
12020
12021 // If extracting a specified index from the vector, see if we can recursively
12022 // find a previously computed scalar that was inserted into the vector.
12023 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12024 unsigned IndexVal = IdxC->getZExtValue();
12025 unsigned VectorWidth =
12026 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12027
12028 // If this is extracting an invalid index, turn this into undef, to avoid
12029 // crashing the code below.
12030 if (IndexVal >= VectorWidth)
12031 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12032
12033 // This instruction only demands the single element from the input vector.
12034 // If the input vector has a single use, simplify it based on this use
12035 // property.
12036 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012037 APInt UndefElts(VectorWidth, 0);
12038 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012039 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012040 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012041 EI.setOperand(0, V);
12042 return &EI;
12043 }
12044 }
12045
12046 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12047 return ReplaceInstUsesWith(EI, Elt);
12048
12049 // If the this extractelement is directly using a bitcast from a vector of
12050 // the same number of elements, see if we can find the source element from
12051 // it. In this case, we will end up needing to bitcast the scalars.
12052 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12053 if (const VectorType *VT =
12054 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12055 if (VT->getNumElements() == VectorWidth)
12056 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12057 return new BitCastInst(Elt, EI.getType());
12058 }
12059 }
12060
12061 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12062 if (I->hasOneUse()) {
12063 // Push extractelement into predecessor operation if legal and
12064 // profitable to do so
12065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12066 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12067 if (CheapToScalarize(BO, isConstantElt)) {
12068 ExtractElementInst *newEI0 =
12069 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12070 EI.getName()+".lhs");
12071 ExtractElementInst *newEI1 =
12072 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12073 EI.getName()+".rhs");
12074 InsertNewInstBefore(newEI0, EI);
12075 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012076 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012077 }
12078 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012079 unsigned AS =
12080 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012081 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12082 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012083 GetElementPtrInst *GEP =
12084 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012085 InsertNewInstBefore(GEP, EI);
12086 return new LoadInst(GEP);
12087 }
12088 }
12089 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12090 // Extracting the inserted element?
12091 if (IE->getOperand(2) == EI.getOperand(1))
12092 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12093 // If the inserted and extracted elements are constants, they must not
12094 // be the same value, extract from the pre-inserted value instead.
12095 if (isa<Constant>(IE->getOperand(2)) &&
12096 isa<Constant>(EI.getOperand(1))) {
12097 AddUsesToWorkList(EI);
12098 EI.setOperand(0, IE->getOperand(0));
12099 return &EI;
12100 }
12101 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12102 // If this is extracting an element from a shufflevector, figure out where
12103 // it came from and extract from the appropriate input element instead.
12104 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12105 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12106 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012107 unsigned LHSWidth =
12108 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12109
12110 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012111 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012112 else if (SrcIdx < LHSWidth*2) {
12113 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012114 Src = SVI->getOperand(1);
12115 } else {
12116 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12117 }
12118 return new ExtractElementInst(Src, SrcIdx);
12119 }
12120 }
12121 }
12122 return 0;
12123}
12124
12125/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12126/// elements from either LHS or RHS, return the shuffle mask and true.
12127/// Otherwise, return false.
12128static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12129 std::vector<Constant*> &Mask) {
12130 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12131 "Invalid CollectSingleShuffleElements");
12132 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12133
12134 if (isa<UndefValue>(V)) {
12135 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12136 return true;
12137 } else if (V == LHS) {
12138 for (unsigned i = 0; i != NumElts; ++i)
12139 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12140 return true;
12141 } else if (V == RHS) {
12142 for (unsigned i = 0; i != NumElts; ++i)
12143 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12144 return true;
12145 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12146 // If this is an insert of an extract from some other vector, include it.
12147 Value *VecOp = IEI->getOperand(0);
12148 Value *ScalarOp = IEI->getOperand(1);
12149 Value *IdxOp = IEI->getOperand(2);
12150
12151 if (!isa<ConstantInt>(IdxOp))
12152 return false;
12153 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12154
12155 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12156 // Okay, we can handle this if the vector we are insertinting into is
12157 // transitively ok.
12158 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12159 // If so, update the mask to reflect the inserted undef.
12160 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12161 return true;
12162 }
12163 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12164 if (isa<ConstantInt>(EI->getOperand(1)) &&
12165 EI->getOperand(0)->getType() == V->getType()) {
12166 unsigned ExtractedIdx =
12167 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12168
12169 // This must be extracting from either LHS or RHS.
12170 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12171 // Okay, we can handle this if the vector we are insertinting into is
12172 // transitively ok.
12173 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12174 // If so, update the mask to reflect the inserted value.
12175 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012176 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012177 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12178 } else {
12179 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012180 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012181 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12182
12183 }
12184 return true;
12185 }
12186 }
12187 }
12188 }
12189 }
12190 // TODO: Handle shufflevector here!
12191
12192 return false;
12193}
12194
12195/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12196/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12197/// that computes V and the LHS value of the shuffle.
12198static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12199 Value *&RHS) {
12200 assert(isa<VectorType>(V->getType()) &&
12201 (RHS == 0 || V->getType() == RHS->getType()) &&
12202 "Invalid shuffle!");
12203 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12204
12205 if (isa<UndefValue>(V)) {
12206 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12207 return V;
12208 } else if (isa<ConstantAggregateZero>(V)) {
12209 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12210 return V;
12211 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12212 // If this is an insert of an extract from some other vector, include it.
12213 Value *VecOp = IEI->getOperand(0);
12214 Value *ScalarOp = IEI->getOperand(1);
12215 Value *IdxOp = IEI->getOperand(2);
12216
12217 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12218 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12219 EI->getOperand(0)->getType() == V->getType()) {
12220 unsigned ExtractedIdx =
12221 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12222 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12223
12224 // Either the extracted from or inserted into vector must be RHSVec,
12225 // otherwise we'd end up with a shuffle of three inputs.
12226 if (EI->getOperand(0) == RHS || RHS == 0) {
12227 RHS = EI->getOperand(0);
12228 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012229 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012230 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12231 return V;
12232 }
12233
12234 if (VecOp == RHS) {
12235 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12236 // Everything but the extracted element is replaced with the RHS.
12237 for (unsigned i = 0; i != NumElts; ++i) {
12238 if (i != InsertedIdx)
12239 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12240 }
12241 return V;
12242 }
12243
12244 // If this insertelement is a chain that comes from exactly these two
12245 // vectors, return the vector and the effective shuffle.
12246 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12247 return EI->getOperand(0);
12248
12249 }
12250 }
12251 }
12252 // TODO: Handle shufflevector here!
12253
12254 // Otherwise, can't do anything fancy. Return an identity vector.
12255 for (unsigned i = 0; i != NumElts; ++i)
12256 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12257 return V;
12258}
12259
12260Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12261 Value *VecOp = IE.getOperand(0);
12262 Value *ScalarOp = IE.getOperand(1);
12263 Value *IdxOp = IE.getOperand(2);
12264
12265 // Inserting an undef or into an undefined place, remove this.
12266 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12267 ReplaceInstUsesWith(IE, VecOp);
12268
12269 // If the inserted element was extracted from some other vector, and if the
12270 // indexes are constant, try to turn this into a shufflevector operation.
12271 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12272 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12273 EI->getOperand(0)->getType() == IE.getType()) {
12274 unsigned NumVectorElts = IE.getType()->getNumElements();
12275 unsigned ExtractedIdx =
12276 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12277 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12278
12279 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12280 return ReplaceInstUsesWith(IE, VecOp);
12281
12282 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12283 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12284
12285 // If we are extracting a value from a vector, then inserting it right
12286 // back into the same place, just use the input vector.
12287 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12288 return ReplaceInstUsesWith(IE, VecOp);
12289
12290 // We could theoretically do this for ANY input. However, doing so could
12291 // turn chains of insertelement instructions into a chain of shufflevector
12292 // instructions, and right now we do not merge shufflevectors. As such,
12293 // only do this in a situation where it is clear that there is benefit.
12294 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12295 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12296 // the values of VecOp, except then one read from EIOp0.
12297 // Build a new shuffle mask.
12298 std::vector<Constant*> Mask;
12299 if (isa<UndefValue>(VecOp))
12300 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12301 else {
12302 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12303 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12304 NumVectorElts));
12305 }
12306 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12307 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12308 ConstantVector::get(Mask));
12309 }
12310
12311 // If this insertelement isn't used by some other insertelement, turn it
12312 // (and any insertelements it points to), into one big shuffle.
12313 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12314 std::vector<Constant*> Mask;
12315 Value *RHS = 0;
12316 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12317 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12318 // We now have a shuffle of LHS, RHS, Mask.
12319 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12320 }
12321 }
12322 }
12323
12324 return 0;
12325}
12326
12327
12328Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12329 Value *LHS = SVI.getOperand(0);
12330 Value *RHS = SVI.getOperand(1);
12331 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12332
12333 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012334
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012335 // Undefined shuffle mask -> undefined value.
12336 if (isa<UndefValue>(SVI.getOperand(2)))
12337 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012338
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012339 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012340
12341 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12342 return 0;
12343
Evan Cheng63295ab2009-02-03 10:05:09 +000012344 APInt UndefElts(VWidth, 0);
12345 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12346 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012347 LHS = SVI.getOperand(0);
12348 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012349 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012350 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012351
12352 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12353 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12354 if (LHS == RHS || isa<UndefValue>(LHS)) {
12355 if (isa<UndefValue>(LHS) && LHS == RHS) {
12356 // shuffle(undef,undef,mask) -> undef.
12357 return ReplaceInstUsesWith(SVI, LHS);
12358 }
12359
12360 // Remap any references to RHS to use LHS.
12361 std::vector<Constant*> Elts;
12362 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12363 if (Mask[i] >= 2*e)
12364 Elts.push_back(UndefValue::get(Type::Int32Ty));
12365 else {
12366 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012367 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012368 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012369 Elts.push_back(UndefValue::get(Type::Int32Ty));
12370 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012371 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012372 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12373 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374 }
12375 }
12376 SVI.setOperand(0, SVI.getOperand(1));
12377 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12378 SVI.setOperand(2, ConstantVector::get(Elts));
12379 LHS = SVI.getOperand(0);
12380 RHS = SVI.getOperand(1);
12381 MadeChange = true;
12382 }
12383
12384 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12385 bool isLHSID = true, isRHSID = true;
12386
12387 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12388 if (Mask[i] >= e*2) continue; // Ignore undef values.
12389 // Is this an identity shuffle of the LHS value?
12390 isLHSID &= (Mask[i] == i);
12391
12392 // Is this an identity shuffle of the RHS value?
12393 isRHSID &= (Mask[i]-e == i);
12394 }
12395
12396 // Eliminate identity shuffles.
12397 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12398 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12399
12400 // If the LHS is a shufflevector itself, see if we can combine it with this
12401 // one without producing an unusual shuffle. Here we are really conservative:
12402 // we are absolutely afraid of producing a shuffle mask not in the input
12403 // program, because the code gen may not be smart enough to turn a merged
12404 // shuffle into two specific shuffles: it may produce worse code. As such,
12405 // we only merge two shuffles if the result is one of the two input shuffle
12406 // masks. In this case, merging the shuffles just removes one instruction,
12407 // which we know is safe. This is good for things like turning:
12408 // (splat(splat)) -> splat.
12409 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12410 if (isa<UndefValue>(RHS)) {
12411 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12412
12413 std::vector<unsigned> NewMask;
12414 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12415 if (Mask[i] >= 2*e)
12416 NewMask.push_back(2*e);
12417 else
12418 NewMask.push_back(LHSMask[Mask[i]]);
12419
12420 // If the result mask is equal to the src shuffle or this shuffle mask, do
12421 // the replacement.
12422 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012423 unsigned LHSInNElts =
12424 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012425 std::vector<Constant*> Elts;
12426 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012427 if (NewMask[i] >= LHSInNElts*2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012428 Elts.push_back(UndefValue::get(Type::Int32Ty));
12429 } else {
12430 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12431 }
12432 }
12433 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12434 LHSSVI->getOperand(1),
12435 ConstantVector::get(Elts));
12436 }
12437 }
12438 }
12439
12440 return MadeChange ? &SVI : 0;
12441}
12442
12443
12444
12445
12446/// TryToSinkInstruction - Try to move the specified instruction from its
12447/// current block into the beginning of DestBlock, which can only happen if it's
12448/// safe to move the instruction past all of the instructions between it and the
12449/// end of its block.
12450static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12451 assert(I->hasOneUse() && "Invariants didn't hold!");
12452
12453 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012454 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12455 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012456
12457 // Do not sink alloca instructions out of the entry block.
12458 if (isa<AllocaInst>(I) && I->getParent() ==
12459 &DestBlock->getParent()->getEntryBlock())
12460 return false;
12461
12462 // We can only sink load instructions if there is nothing between the load and
12463 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012464 if (I->mayReadFromMemory()) {
12465 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012466 Scan != E; ++Scan)
12467 if (Scan->mayWriteToMemory())
12468 return false;
12469 }
12470
Dan Gohman514277c2008-05-23 21:05:58 +000012471 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012472
Dale Johannesen24339f12009-03-03 01:09:07 +000012473 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012474 I->moveBefore(InsertPos);
12475 ++NumSunkInst;
12476 return true;
12477}
12478
12479
12480/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12481/// all reachable code to the worklist.
12482///
12483/// This has a couple of tricks to make the code faster and more powerful. In
12484/// particular, we constant fold and DCE instructions as we go, to avoid adding
12485/// them to the worklist (this significantly speeds up instcombine on code where
12486/// many instructions are dead or constant). Additionally, if we find a branch
12487/// whose condition is a known constant, we only visit the reachable successors.
12488///
12489static void AddReachableCodeToWorklist(BasicBlock *BB,
12490 SmallPtrSet<BasicBlock*, 64> &Visited,
12491 InstCombiner &IC,
12492 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012493 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012494 Worklist.push_back(BB);
12495
12496 while (!Worklist.empty()) {
12497 BB = Worklist.back();
12498 Worklist.pop_back();
12499
12500 // We have now visited this block! If we've already been here, ignore it.
12501 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012502
12503 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012504 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12505 Instruction *Inst = BBI++;
12506
12507 // DCE instruction if trivially dead.
12508 if (isInstructionTriviallyDead(Inst)) {
12509 ++NumDeadInst;
12510 DOUT << "IC: DCE: " << *Inst;
12511 Inst->eraseFromParent();
12512 continue;
12513 }
12514
12515 // ConstantProp instruction if trivially constant.
12516 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12517 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12518 Inst->replaceAllUsesWith(C);
12519 ++NumConstProp;
12520 Inst->eraseFromParent();
12521 continue;
12522 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012523
Devang Patel794140c2008-11-19 18:56:50 +000012524 // If there are two consecutive llvm.dbg.stoppoint calls then
12525 // it is likely that the optimizer deleted code in between these
12526 // two intrinsics.
12527 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12528 if (DBI_Next) {
12529 if (DBI_Prev
12530 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12531 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12532 IC.RemoveFromWorkList(DBI_Prev);
12533 DBI_Prev->eraseFromParent();
12534 }
12535 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012536 } else {
12537 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012538 }
12539
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012540 IC.AddToWorkList(Inst);
12541 }
12542
12543 // Recursively visit successors. If this is a branch or switch on a
12544 // constant, only visit the reachable successor.
12545 TerminatorInst *TI = BB->getTerminator();
12546 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12547 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12548 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012549 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012550 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012551 continue;
12552 }
12553 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12554 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12555 // See if this is an explicit destination.
12556 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12557 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012558 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012559 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012560 continue;
12561 }
12562
12563 // Otherwise it is the default destination.
12564 Worklist.push_back(SI->getSuccessor(0));
12565 continue;
12566 }
12567 }
12568
12569 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12570 Worklist.push_back(TI->getSuccessor(i));
12571 }
12572}
12573
12574bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12575 bool Changed = false;
12576 TD = &getAnalysis<TargetData>();
12577
12578 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12579 << F.getNameStr() << "\n");
12580
12581 {
12582 // Do a depth-first traversal of the function, populate the worklist with
12583 // the reachable instructions. Ignore blocks that are not reachable. Keep
12584 // track of which blocks we visit.
12585 SmallPtrSet<BasicBlock*, 64> Visited;
12586 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12587
12588 // Do a quick scan over the function. If we find any blocks that are
12589 // unreachable, remove any instructions inside of them. This prevents
12590 // the instcombine code from having to deal with some bad special cases.
12591 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12592 if (!Visited.count(BB)) {
12593 Instruction *Term = BB->getTerminator();
12594 while (Term != BB->begin()) { // Remove instrs bottom-up
12595 BasicBlock::iterator I = Term; --I;
12596
12597 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000012598 // A debug intrinsic shouldn't force another iteration if we weren't
12599 // going to do one without it.
12600 if (!isa<DbgInfoIntrinsic>(I)) {
12601 ++NumDeadInst;
12602 Changed = true;
12603 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012604 if (!I->use_empty())
12605 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12606 I->eraseFromParent();
12607 }
12608 }
12609 }
12610
12611 while (!Worklist.empty()) {
12612 Instruction *I = RemoveOneFromWorkList();
12613 if (I == 0) continue; // skip null values.
12614
12615 // Check to see if we can DCE the instruction.
12616 if (isInstructionTriviallyDead(I)) {
12617 // Add operands to the worklist.
12618 if (I->getNumOperands() < 4)
12619 AddUsesToWorkList(*I);
12620 ++NumDeadInst;
12621
12622 DOUT << "IC: DCE: " << *I;
12623
12624 I->eraseFromParent();
12625 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012626 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012627 continue;
12628 }
12629
12630 // Instruction isn't dead, see if we can constant propagate it.
12631 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12632 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12633
12634 // Add operands to the worklist.
12635 AddUsesToWorkList(*I);
12636 ReplaceInstUsesWith(*I, C);
12637
12638 ++NumConstProp;
12639 I->eraseFromParent();
12640 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012641 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012642 continue;
12643 }
12644
Nick Lewyckyadb67922008-05-25 20:56:15 +000012645 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12646 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012647 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewyckyadb67922008-05-25 20:56:15 +000012649 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012650 if (NewC != CE) {
12651 i->set(NewC);
12652 Changed = true;
12653 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012654 }
12655
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012656 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012657 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 BasicBlock *BB = I->getParent();
12659 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12660 if (UserParent != BB) {
12661 bool UserIsSuccessor = false;
12662 // See if the user is one of our successors.
12663 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12664 if (*SI == UserParent) {
12665 UserIsSuccessor = true;
12666 break;
12667 }
12668
12669 // If the user is one of our immediate successors, and if that successor
12670 // only has us as a predecessors (we'd have to split the critical edge
12671 // otherwise), we can keep going.
12672 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12673 next(pred_begin(UserParent)) == pred_end(UserParent))
12674 // Okay, the CFG is simple enough, try to sink this instruction.
12675 Changed |= TryToSinkInstruction(I, UserParent);
12676 }
12677 }
12678
12679 // Now that we have an instruction, try combining it to simplify it...
12680#ifndef NDEBUG
12681 std::string OrigI;
12682#endif
12683 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12684 if (Instruction *Result = visit(*I)) {
12685 ++NumCombined;
12686 // Should we replace the old instruction with a new one?
12687 if (Result != I) {
12688 DOUT << "IC: Old = " << *I
12689 << " New = " << *Result;
12690
12691 // Everything uses the new instruction now.
12692 I->replaceAllUsesWith(Result);
12693
12694 // Push the new instruction and any users onto the worklist.
12695 AddToWorkList(Result);
12696 AddUsersToWorkList(*Result);
12697
12698 // Move the name to the new instruction first.
12699 Result->takeName(I);
12700
12701 // Insert the new instruction into the basic block...
12702 BasicBlock *InstParent = I->getParent();
12703 BasicBlock::iterator InsertPos = I;
12704
12705 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12706 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12707 ++InsertPos;
12708
12709 InstParent->getInstList().insert(InsertPos, Result);
12710
12711 // Make sure that we reprocess all operands now that we reduced their
12712 // use counts.
12713 AddUsesToWorkList(*I);
12714
12715 // Instructions can end up on the worklist more than once. Make sure
12716 // we do not process an instruction that has been deleted.
12717 RemoveFromWorkList(I);
12718
12719 // Erase the old instruction.
12720 InstParent->getInstList().erase(I);
12721 } else {
12722#ifndef NDEBUG
12723 DOUT << "IC: Mod = " << OrigI
12724 << " New = " << *I;
12725#endif
12726
12727 // If the instruction was modified, it's possible that it is now dead.
12728 // if so, remove it.
12729 if (isInstructionTriviallyDead(I)) {
12730 // Make sure we process all operands now that we are reducing their
12731 // use counts.
12732 AddUsesToWorkList(*I);
12733
12734 // Instructions may end up in the worklist more than once. Erase all
12735 // occurrences of this instruction.
12736 RemoveFromWorkList(I);
12737 I->eraseFromParent();
12738 } else {
12739 AddToWorkList(I);
12740 AddUsersToWorkList(*I);
12741 }
12742 }
12743 Changed = true;
12744 }
12745 }
12746
12747 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000012748
12749 // Do an explicit clear, this shrinks the map if needed.
12750 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012751 return Changed;
12752}
12753
12754
12755bool InstCombiner::runOnFunction(Function &F) {
12756 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12757
12758 bool EverMadeChange = false;
12759
12760 // Iterate while there is work to do.
12761 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012762 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012763 EverMadeChange = true;
12764 return EverMadeChange;
12765}
12766
12767FunctionPass *llvm::createInstructionCombiningPass() {
12768 return new InstCombiner();
12769}