blob: 10d3344598da04baa9b17d2f02a7c33b7e97b7ba [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"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/GetElementPtrTypeIterator.h"
50#include "llvm/Support/InstVisitor.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/PatternMatch.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#include <sstream>
62using namespace llvm;
63using namespace llvm::PatternMatch;
64
65STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71namespace {
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
78 TargetData *TD;
79 bool MustPreserveLCSSA;
80 public:
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
108
109
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116 UI != UE; ++UI)
117 AddToWorkList(cast<Instruction>(*UI));
118 }
119
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126 AddToWorkList(Op);
127 }
128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140 AddToWorkList(Op);
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
147
148 public:
149 virtual bool runOnFunction(Function &F);
150
151 bool DoOneIteration(Function &F, unsigned ItNum);
152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
157 }
158
159 TargetData &getTargetData() const { return *TD; }
160
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
167 //
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
198
199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
202 BinaryOperator &I);
203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
205 Instruction *commonPointerCastTransforms(CastInst &CI);
206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 Instruction *visitBitCast(BitCastInst &CI);
218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
220 Instruction *visitSelectInst(SelectInst &CI);
221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225 Instruction *visitAllocationInst(AllocationInst &AI);
226 Instruction *visitFreeInst(FreeInst &FI);
227 Instruction *visitLoadInst(LoadInst &LI);
228 Instruction *visitStoreInst(StoreInst &SI);
229 Instruction *visitBranchInst(BranchInst &BI);
230 Instruction *visitSwitchInst(SwitchInst &SI);
231 Instruction *visitInsertElementInst(InsertElementInst &IE);
232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
234
235 // visitInstruction - Specify what to return for unhandled instructions...
236 Instruction *visitInstruction(Instruction &I) { return 0; }
237
238 private:
239 Instruction *visitCallSite(CallSite CS);
240 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
245 public:
246 // InsertNewInstBefore - insert an instruction New before instruction Old
247 // in the program. Add the new instruction to the worklist.
248 //
249 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
250 assert(New && New->getParent() == 0 &&
251 "New instruction already inserted into a basic block!");
252 BasicBlock *BB = Old.getParent();
253 BB->getInstList().insert(&Old, New); // Insert inst
254 AddToWorkList(New);
255 return New;
256 }
257
258 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
259 /// This also adds the cast to the worklist. Finally, this returns the
260 /// cast.
261 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
262 Instruction &Pos) {
263 if (V->getType() == Ty) return V;
264
265 if (Constant *CV = dyn_cast<Constant>(V))
266 return ConstantExpr::getCast(opc, CV, Ty);
267
Gabor Greifa645dd32008-05-16 19:29:10 +0000268 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 AddToWorkList(C);
270 return C;
271 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000272
273 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
274 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
275 }
276
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277
278 // ReplaceInstUsesWith - This method is to be used when an instruction is
279 // found to be dead, replacable with another preexisting expression. Here
280 // we add all uses of I to the worklist, replace all uses of I with the new
281 // value, then return I, so that the inst combiner will know that I was
282 // modified.
283 //
284 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
285 AddUsersToWorkList(I); // Add all modified instrs to worklist
286 if (&I != V) {
287 I.replaceAllUsesWith(V);
288 return &I;
289 } else {
290 // If we are replacing the instruction with itself, this must be in a
291 // segment of unreachable code, so just clobber the instruction.
292 I.replaceAllUsesWith(UndefValue::get(I.getType()));
293 return &I;
294 }
295 }
296
297 // UpdateValueUsesWith - This method is to be used when an value is
298 // found to be replacable with another preexisting expression or was
299 // updated. Here we add all uses of I to the worklist, replace all uses of
300 // I with the new value (unless the instruction was just updated), then
301 // return true, so that the inst combiner will know that I was modified.
302 //
303 bool UpdateValueUsesWith(Value *Old, Value *New) {
304 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
305 if (Old != New)
306 Old->replaceAllUsesWith(New);
307 if (Instruction *I = dyn_cast<Instruction>(Old))
308 AddToWorkList(I);
309 if (Instruction *I = dyn_cast<Instruction>(New))
310 AddToWorkList(I);
311 return true;
312 }
313
314 // EraseInstFromFunction - When dealing with an instruction that has side
315 // effects or produces a void value, we can't rely on DCE to delete the
316 // instruction. Instead, visit methods should return the value returned by
317 // this function.
318 Instruction *EraseInstFromFunction(Instruction &I) {
319 assert(I.use_empty() && "Cannot erase instruction that is used!");
320 AddUsesToWorkList(I);
321 RemoveFromWorkList(&I);
322 I.eraseFromParent();
323 return 0; // Don't do anything with FI
324 }
325
326 private:
327 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
328 /// InsertBefore instruction. This is specialized a bit to avoid inserting
329 /// casts that are known to not do anything...
330 ///
331 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
332 Value *V, const Type *DestTy,
333 Instruction *InsertBefore);
334
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
343 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
344 /// on the demanded bits.
345 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth = 0);
348
349 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
350 uint64_t &UndefElts, unsigned Depth = 0);
351
352 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
353 // PHI node as operand #0, see if we can fold the instruction into the PHI
354 // (which is only possible if all operands to the PHI are constants).
355 Instruction *FoldOpIntoPhi(Instruction &I);
356
357 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
358 // operator and they all are only used by the PHI, PHI together their
359 // inputs, and do the operation once, to the result of the PHI.
360 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
361 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
362
363
364 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
365 ConstantInt *AndRHS, BinaryOperator &TheAnd);
366
367 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
368 bool isSub, Instruction &I);
369 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
370 bool isSigned, bool Inside, Instruction &IB);
371 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
372 Instruction *MatchBSwap(BinaryOperator &I);
373 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000374 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000375 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000376
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377
378 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
381 APInt& KnownOne, unsigned Depth = 0);
382 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
383 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
384 unsigned CastOpc,
385 int &NumCastsRemoved);
386 unsigned GetOrEnforceKnownAlignment(Value *V,
387 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389}
390
Dan Gohman089efff2008-05-13 00:00:25 +0000391char InstCombiner::ID = 0;
392static RegisterPass<InstCombiner>
393X("instcombine", "Combine redundant instructions");
394
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395// getComplexity: Assign a complexity or rank value to LLVM Values...
396// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
397static unsigned getComplexity(Value *V) {
398 if (isa<Instruction>(V)) {
399 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
400 return 3;
401 return 4;
402 }
403 if (isa<Argument>(V)) return 3;
404 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
405}
406
407// isOnlyUse - Return true if this instruction will be deleted if we stop using
408// it.
409static bool isOnlyUse(Value *V) {
410 return V->hasOneUse() || isa<Constant>(V);
411}
412
413// getPromotedType - Return the specified type promoted as it would be to pass
414// though a va_arg area...
415static const Type *getPromotedType(const Type *Ty) {
416 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
417 if (ITy->getBitWidth() < 32)
418 return Type::Int32Ty;
419 }
420 return Ty;
421}
422
Chris Lattnere6b62d92008-05-19 20:18:56 +0000423/// GetFPMantissaWidth - Return the width of the mantissa (aka significand) of
424/// the specified floating point type in bits. This returns -1 if unknown.
425static int GetFPMantissaWidth(const Type *FPType) {
426 if (FPType == Type::FloatTy)
427 return 24;
428 if (FPType == Type::DoubleTy)
429 return 53;
430 if (FPType == Type::X86_FP80Ty)
431 return 64;
432 return -1; // Unknown/crazy type.
433}
434
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435/// getBitCastOperand - If the specified operand is a CastInst or a constant
436/// expression bitcast, return the operand value, otherwise return null.
437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439 return I->getOperand(0);
440 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
441 if (CE->getOpcode() == Instruction::BitCast)
442 return CE->getOperand(0);
443 return 0;
444}
445
446/// This function is a wrapper around CastInst::isEliminableCastPair. It
447/// simply extracts arguments and returns what that function returns.
448static Instruction::CastOps
449isEliminableCastPair(
450 const CastInst *CI, ///< The first cast instruction
451 unsigned opcode, ///< The opcode of the second cast instruction
452 const Type *DstTy, ///< The target type for the second cast instruction
453 TargetData *TD ///< The target data for pointer size
454) {
455
456 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
457 const Type *MidTy = CI->getType(); // B from above
458
459 // Get the opcodes of the two Cast instructions
460 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
461 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
462
463 return Instruction::CastOps(
464 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
465 DstTy, TD->getIntPtrType()));
466}
467
468/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
469/// in any code being generated. It does not require codegen if V is simple
470/// enough or if the cast can be folded into other casts.
471static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
472 const Type *Ty, TargetData *TD) {
473 if (V->getType() == Ty || isa<Constant>(V)) return false;
474
475 // If this is another cast that can be eliminated, it isn't codegen either.
476 if (const CastInst *CI = dyn_cast<CastInst>(V))
477 if (isEliminableCastPair(CI, opcode, Ty, TD))
478 return false;
479 return true;
480}
481
482/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
483/// InsertBefore instruction. This is specialized a bit to avoid inserting
484/// casts that are known to not do anything...
485///
486Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
487 Value *V, const Type *DestTy,
488 Instruction *InsertBefore) {
489 if (V->getType() == DestTy) return V;
490 if (Constant *C = dyn_cast<Constant>(V))
491 return ConstantExpr::getCast(opcode, C, DestTy);
492
493 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
494}
495
496// SimplifyCommutative - This performs a few simplifications for commutative
497// operators:
498//
499// 1. Order operands such that they are listed from right (least complex) to
500// left (most complex). This puts constants before unary operators before
501// binary operators.
502//
503// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505//
506bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
507 bool Changed = false;
508 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509 Changed = !I.swapOperands();
510
511 if (!I.isAssociative()) return Changed;
512 Instruction::BinaryOps Opcode = I.getOpcode();
513 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515 if (isa<Constant>(I.getOperand(1))) {
516 Constant *Folded = ConstantExpr::get(I.getOpcode(),
517 cast<Constant>(I.getOperand(1)),
518 cast<Constant>(Op->getOperand(1)));
519 I.setOperand(0, Op->getOperand(0));
520 I.setOperand(1, Folded);
521 return true;
522 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524 isOnlyUse(Op) && isOnlyUse(Op1)) {
525 Constant *C1 = cast<Constant>(Op->getOperand(1));
526 Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
529 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000530 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 Op1->getOperand(0),
532 Op1->getName(), &I);
533 AddToWorkList(New);
534 I.setOperand(0, New);
535 I.setOperand(1, Folded);
536 return true;
537 }
538 }
539 return Changed;
540}
541
542/// SimplifyCompare - For a CmpInst this function just orders the operands
543/// so that theyare listed from right (least complex) to left (most complex).
544/// This puts constants before unary operators before binary operators.
545bool InstCombiner::SimplifyCompare(CmpInst &I) {
546 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547 return false;
548 I.swapOperands();
549 // Compare instructions are not associative so there's nothing else we can do.
550 return true;
551}
552
553// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554// if the LHS is a constant zero (which is the 'negate' form).
555//
556static inline Value *dyn_castNegVal(Value *V) {
557 if (BinaryOperator::isNeg(V))
558 return BinaryOperator::getNegArgument(V);
559
560 // Constants can be considered to be negated values if they can be folded.
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantExpr::getNeg(C);
563 return 0;
564}
565
566static inline Value *dyn_castNotVal(Value *V) {
567 if (BinaryOperator::isNot(V))
568 return BinaryOperator::getNotArgument(V);
569
570 // Constants can be considered to be not'ed values...
571 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
572 return ConstantInt::get(~C->getValue());
573 return 0;
574}
575
576// dyn_castFoldableMul - If this value is a multiply that can be folded into
577// other computations (because it has a constant operand), return the
578// non-constant operand of the multiply, and set CST to point to the multiplier.
579// Otherwise, return null.
580//
581static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
582 if (V->hasOneUse() && V->getType()->isInteger())
583 if (Instruction *I = dyn_cast<Instruction>(V)) {
584 if (I->getOpcode() == Instruction::Mul)
585 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
586 return I->getOperand(0);
587 if (I->getOpcode() == Instruction::Shl)
588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
589 // The multiplier is really 1 << CST.
590 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
591 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
592 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
593 return I->getOperand(0);
594 }
595 }
596 return 0;
597}
598
599/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
600/// expression, return it.
601static User *dyn_castGetElementPtr(Value *V) {
602 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
604 if (CE->getOpcode() == Instruction::GetElementPtr)
605 return cast<User>(V);
606 return false;
607}
608
Dan Gohman2d648bb2008-04-10 18:43:06 +0000609/// getOpcode - If this is an Instruction or a ConstantExpr, return the
610/// opcode value. Otherwise return UserOp1.
611static unsigned getOpcode(User *U) {
612 if (Instruction *I = dyn_cast<Instruction>(U))
613 return I->getOpcode();
614 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
615 return CE->getOpcode();
616 // Use UserOp1 to mean there's no opcode.
617 return Instruction::UserOp1;
618}
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620/// AddOne - Add one to a ConstantInt
621static ConstantInt *AddOne(ConstantInt *C) {
622 APInt Val(C->getValue());
623 return ConstantInt::get(++Val);
624}
625/// SubOne - Subtract one from a ConstantInt
626static ConstantInt *SubOne(ConstantInt *C) {
627 APInt Val(C->getValue());
628 return ConstantInt::get(--Val);
629}
630/// Add - Add two ConstantInts together
631static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
632 return ConstantInt::get(C1->getValue() + C2->getValue());
633}
634/// And - Bitwise AND two ConstantInts together
635static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
636 return ConstantInt::get(C1->getValue() & C2->getValue());
637}
638/// Subtract - Subtract one ConstantInt from another
639static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() - C2->getValue());
641}
642/// Multiply - Multiply two ConstantInts together
643static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() * C2->getValue());
645}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000646/// MultiplyOverflows - True if the multiply can not be expressed in an int
647/// this size.
648static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
649 uint32_t W = C1->getBitWidth();
650 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
651 if (sign) {
652 LHSExt.sext(W * 2);
653 RHSExt.sext(W * 2);
654 } else {
655 LHSExt.zext(W * 2);
656 RHSExt.zext(W * 2);
657 }
658
659 APInt MulExt = LHSExt * RHSExt;
660
661 if (sign) {
662 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
663 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
664 return MulExt.slt(Min) || MulExt.sgt(Max);
665 } else
666 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
667}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668
669/// ComputeMaskedBits - Determine which of the bits specified in Mask are
670/// known to be either zero or one and return them in the KnownZero/KnownOne
671/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
672/// processing.
673/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
674/// we cannot optimize based on the assumption that it is zero without changing
675/// it to be an explicit zero. If we don't change it to zero, other code could
676/// optimized based on the contradictory assumption that it is non-zero.
677/// Because instcombine aggressively folds operations with undef args anyway,
678/// this won't lose us code quality.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000679void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
680 APInt& KnownZero, APInt& KnownOne,
681 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 assert(V && "No Value?");
683 assert(Depth <= 6 && "Limit Search Depth");
684 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000685 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
686 "Not integer or pointer type!");
687 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
688 (!isa<IntegerType>(V->getType()) ||
689 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 KnownZero.getBitWidth() == BitWidth &&
691 KnownOne.getBitWidth() == BitWidth &&
692 "V, Mask, KnownOne and KnownZero should have same BitWidth");
693 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
694 // We know all of the bits for a constant!
695 KnownOne = CI->getValue() & Mask;
696 KnownZero = ~KnownOne & Mask;
697 return;
698 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000699 // Null is all-zeros.
700 if (isa<ConstantPointerNull>(V)) {
701 KnownOne.clear();
702 KnownZero = Mask;
703 return;
704 }
705 // The address of an aligned GlobalValue has trailing zeros.
706 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
707 unsigned Align = GV->getAlignment();
708 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
709 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
710 if (Align > 0)
711 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
712 CountTrailingZeros_32(Align));
713 else
714 KnownZero.clear();
715 KnownOne.clear();
716 return;
717 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718
Dan Gohmanbec16052008-04-28 17:02:21 +0000719 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
720
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 if (Depth == 6 || Mask == 0)
722 return; // Limit search depth.
723
Dan Gohman2d648bb2008-04-10 18:43:06 +0000724 User *I = dyn_cast<User>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 if (!I) return;
726
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000728 switch (getOpcode(I)) {
729 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 case Instruction::And: {
731 // If either the LHS or the RHS are Zero, the result is zero.
732 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
733 APInt Mask2(Mask & ~KnownZero);
734 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
736 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
737
738 // Output known-1 bits are only known if set in both the LHS & RHS.
739 KnownOne &= KnownOne2;
740 // Output known-0 are known to be clear if zero in either the LHS | RHS.
741 KnownZero |= KnownZero2;
742 return;
743 }
744 case Instruction::Or: {
745 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
746 APInt Mask2(Mask & ~KnownOne);
747 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
748 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
749 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
750
751 // Output known-0 bits are only known if clear in both the LHS & RHS.
752 KnownZero &= KnownZero2;
753 // Output known-1 are known to be set if set in either the LHS | RHS.
754 KnownOne |= KnownOne2;
755 return;
756 }
757 case Instruction::Xor: {
758 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // Output known-0 bits are known if clear or set in both the LHS & RHS.
764 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
765 // Output known-1 are known to be set if set in only one of the LHS, RHS.
766 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
767 KnownZero = KnownZeroOut;
768 return;
769 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000770 case Instruction::Mul: {
771 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
772 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
773 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
776
777 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohmanbec16052008-04-28 17:02:21 +0000778 // Also compute a conserative estimate for high known-0 bits.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000779 // More trickiness is possible, but this is sufficient for the
780 // interesting case of alignment computation.
781 KnownOne.clear();
782 unsigned TrailZ = KnownZero.countTrailingOnes() +
783 KnownZero2.countTrailingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +0000784 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman4c451852008-05-07 00:35:55 +0000785 KnownZero2.countLeadingOnes(),
786 BitWidth) - BitWidth;
Dan Gohmanbec16052008-04-28 17:02:21 +0000787
Dan Gohman2d648bb2008-04-10 18:43:06 +0000788 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000789 LeadZ = std::min(LeadZ, BitWidth);
790 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
791 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000792 KnownZero &= Mask;
793 return;
794 }
Dan Gohmanbec16052008-04-28 17:02:21 +0000795 case Instruction::UDiv: {
796 // For the purposes of computing leading zeros we can conservatively
797 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000798 // be less than the denominator.
Dan Gohmanbec16052008-04-28 17:02:21 +0000799 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
800 ComputeMaskedBits(I->getOperand(0),
801 AllOnes, KnownZero2, KnownOne2, Depth+1);
802 unsigned LeadZ = KnownZero2.countLeadingOnes();
803
804 KnownOne2.clear();
805 KnownZero2.clear();
806 ComputeMaskedBits(I->getOperand(1),
807 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000808 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
809 if (RHSUnknownLeadingOnes != BitWidth)
810 LeadZ = std::min(BitWidth,
811 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000812
813 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
814 return;
815 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 case Instruction::Select:
817 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
818 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
819 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
820 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
821
822 // Only known if known in both the LHS and RHS.
823 KnownOne &= KnownOne2;
824 KnownZero &= KnownZero2;
825 return;
826 case Instruction::FPTrunc:
827 case Instruction::FPExt:
828 case Instruction::FPToUI:
829 case Instruction::FPToSI:
830 case Instruction::SIToFP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 case Instruction::UIToFP:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000832 return; // Can't work with floating point.
833 case Instruction::PtrToInt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 case Instruction::IntToPtr:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000835 // We can't handle these if we don't know the pointer size.
836 if (!TD) return;
Chris Lattnere3061db2008-05-19 20:27:56 +0000837 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000838 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 case Instruction::Trunc: {
Chris Lattnere3061db2008-05-19 20:27:56 +0000840 // Note that we handle pointer operands here because of inttoptr/ptrtoint
841 // which fall through here.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000842 const Type *SrcTy = I->getOperand(0)->getType();
843 uint32_t SrcBitWidth = TD ?
844 TD->getTypeSizeInBits(SrcTy) :
845 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000847 MaskIn.zextOrTrunc(SrcBitWidth);
848 KnownZero.zextOrTrunc(SrcBitWidth);
849 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000851 KnownZero.zextOrTrunc(BitWidth);
852 KnownOne.zextOrTrunc(BitWidth);
853 // Any top bits are known to be zero.
854 if (BitWidth > SrcBitWidth)
855 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 return;
857 }
858 case Instruction::BitCast: {
859 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000860 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
862 return;
863 }
864 break;
865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 case Instruction::SExt: {
867 // Compute the bits in the result that are not present in the input.
868 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
869 uint32_t SrcBitWidth = SrcTy->getBitWidth();
870
871 APInt MaskIn(Mask);
872 MaskIn.trunc(SrcBitWidth);
873 KnownZero.trunc(SrcBitWidth);
874 KnownOne.trunc(SrcBitWidth);
875 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
877 KnownZero.zext(BitWidth);
878 KnownOne.zext(BitWidth);
879
880 // If the sign bit of the input is known set or clear, then we know the
881 // top bits of the result.
882 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
883 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
884 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
885 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
886 return;
887 }
888 case Instruction::Shl:
889 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
890 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
891 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
892 APInt Mask2(Mask.lshr(ShiftAmt));
893 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
895 KnownZero <<= ShiftAmt;
896 KnownOne <<= ShiftAmt;
897 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
898 return;
899 }
900 break;
901 case Instruction::LShr:
902 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
903 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
904 // Compute the new bits that are at the top now.
905 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
906
907 // Unsigned shift right.
908 APInt Mask2(Mask.shl(ShiftAmt));
909 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
910 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
911 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
912 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
913 // high bits known zero.
914 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
915 return;
916 }
917 break;
918 case Instruction::AShr:
919 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
920 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
921 // Compute the new bits that are at the top now.
922 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
923
924 // Signed shift right.
925 APInt Mask2(Mask.shl(ShiftAmt));
926 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
927 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
928 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
929 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
930
931 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
932 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
933 KnownZero |= HighBits;
934 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
935 KnownOne |= HighBits;
936 return;
937 }
938 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000939 case Instruction::Sub: {
940 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
941 // We know that the top bits of C-X are clear if X contains less bits
942 // than C (i.e. no wrap-around can happen). For example, 20-X is
943 // positive if we can prove that X is >= 0 and < 16.
944 if (!CLHS->getValue().isNegative()) {
945 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
946 // NLZ can't be BitWidth with no sign bit
947 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000948 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
949 Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000950
Dan Gohmanbec16052008-04-28 17:02:21 +0000951 // If all of the MaskV bits are known to be zero, then we know the
952 // output top bits are zero, because we now know that the output is
953 // from [0-C].
954 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman2d648bb2008-04-10 18:43:06 +0000955 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
956 // Top bits known zero.
957 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000958 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000959 }
960 }
961 }
962 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000963 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000964 // Output known-0 bits are known if clear or set in both the low clear bits
965 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
966 // low 3 bits clear.
Dan Gohmanbec16052008-04-28 17:02:21 +0000967 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
968 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
971
972 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
973 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
974 KnownZeroOut = std::min(KnownZeroOut,
975 KnownZero2.countTrailingOnes());
976
977 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000978 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000979 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000980 case Instruction::SRem:
981 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
982 APInt RA = Rem->getValue();
983 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +0000984 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000985 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
986 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
987
988 // The sign of a remainder is equal to the sign of the first
989 // operand (zero being positive).
990 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
991 KnownZero2 |= ~LowBits;
992 else if (KnownOne2[BitWidth-1])
993 KnownOne2 |= ~LowBits;
994
995 KnownZero |= KnownZero2 & Mask;
996 KnownOne |= KnownOne2 & Mask;
997
998 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
999 }
1000 }
1001 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001002 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001003 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1004 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001005 if (RA.isPowerOf2()) {
1006 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001007 APInt Mask2 = LowBits & Mask;
1008 KnownZero |= ~LowBits & Mask;
1009 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1010 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001011 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001012 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001013 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001014
1015 // Since the result is less than or equal to either operand, any leading
1016 // zero bits in either operand must also exist in the result.
1017 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1018 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1019 Depth+1);
1020 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1021 Depth+1);
1022
1023 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1024 KnownZero2.countLeadingOnes());
1025 KnownOne.clear();
1026 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001027 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001028 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00001029
1030 case Instruction::Alloca:
1031 case Instruction::Malloc: {
1032 AllocationInst *AI = cast<AllocationInst>(V);
1033 unsigned Align = AI->getAlignment();
1034 if (Align == 0 && TD) {
1035 if (isa<AllocaInst>(AI))
1036 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1037 else if (isa<MallocInst>(AI)) {
1038 // Malloc returns maximally aligned memory.
1039 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1040 Align =
1041 std::max(Align,
1042 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1043 Align =
1044 std::max(Align,
1045 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1046 }
1047 }
1048
1049 if (Align > 0)
1050 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1051 CountTrailingZeros_32(Align));
1052 break;
1053 }
1054 case Instruction::GetElementPtr: {
1055 // Analyze all of the subscripts of this getelementptr instruction
1056 // to determine if we can prove known low zero bits.
1057 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1058 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1059 ComputeMaskedBits(I->getOperand(0), LocalMask,
1060 LocalKnownZero, LocalKnownOne, Depth+1);
1061 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1062
1063 gep_type_iterator GTI = gep_type_begin(I);
1064 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1065 Value *Index = I->getOperand(i);
1066 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1067 // Handle struct member offset arithmetic.
1068 if (!TD) return;
1069 const StructLayout *SL = TD->getStructLayout(STy);
1070 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1071 uint64_t Offset = SL->getElementOffset(Idx);
1072 TrailZ = std::min(TrailZ,
1073 CountTrailingZeros_64(Offset));
1074 } else {
1075 // Handle array index arithmetic.
1076 const Type *IndexedTy = GTI.getIndexedType();
1077 if (!IndexedTy->isSized()) return;
1078 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1079 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1080 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1081 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1082 ComputeMaskedBits(Index, LocalMask,
1083 LocalKnownZero, LocalKnownOne, Depth+1);
1084 TrailZ = std::min(TrailZ,
1085 CountTrailingZeros_64(TypeSize) +
1086 LocalKnownZero.countTrailingOnes());
1087 }
1088 }
1089
1090 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1091 break;
1092 }
1093 case Instruction::PHI: {
1094 PHINode *P = cast<PHINode>(I);
1095 // Handle the case of a simple two-predecessor recurrence PHI.
1096 // There's a lot more that could theoretically be done here, but
1097 // this is sufficient to catch some interesting cases.
1098 if (P->getNumIncomingValues() == 2) {
1099 for (unsigned i = 0; i != 2; ++i) {
1100 Value *L = P->getIncomingValue(i);
1101 Value *R = P->getIncomingValue(!i);
1102 User *LU = dyn_cast<User>(L);
1103 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1104 // Check for operations that have the property that if
1105 // both their operands have low zero bits, the result
1106 // will have low zero bits.
1107 if (Opcode == Instruction::Add ||
1108 Opcode == Instruction::Sub ||
1109 Opcode == Instruction::And ||
1110 Opcode == Instruction::Or ||
1111 Opcode == Instruction::Mul) {
1112 Value *LL = LU->getOperand(0);
1113 Value *LR = LU->getOperand(1);
1114 // Find a recurrence.
1115 if (LL == I)
1116 L = LR;
1117 else if (LR == I)
1118 L = LL;
1119 else
1120 break;
1121 // Ok, we have a PHI of the form L op= R. Check for low
1122 // zero bits.
1123 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1124 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1125 Mask2 = APInt::getLowBitsSet(BitWidth,
1126 KnownZero2.countTrailingOnes());
1127 KnownOne2.clear();
1128 KnownZero2.clear();
1129 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1130 KnownZero = Mask &
1131 APInt::getLowBitsSet(BitWidth,
1132 KnownZero2.countTrailingOnes());
1133 break;
1134 }
1135 }
1136 }
1137 break;
1138 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001139 case Instruction::Call:
1140 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1141 switch (II->getIntrinsicID()) {
1142 default: break;
1143 case Intrinsic::ctpop:
1144 case Intrinsic::ctlz:
1145 case Intrinsic::cttz: {
1146 unsigned LowBits = Log2_32(BitWidth)+1;
1147 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1148 break;
1149 }
1150 }
1151 }
1152 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 }
1154}
1155
1156/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1157/// this predicate to simplify operations downstream. Mask is known to be zero
1158/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001159bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1160 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1162 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1163 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1164 return (KnownZero & Mask) == Mask;
1165}
1166
1167/// ShrinkDemandedConstant - Check to see if the specified operand of the
1168/// specified instruction is a constant integer. If so, check to see if there
1169/// are any bits set in the constant that are not demanded. If so, shrink the
1170/// constant and return true.
1171static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1172 APInt Demanded) {
1173 assert(I && "No instruction?");
1174 assert(OpNo < I->getNumOperands() && "Operand index too large");
1175
1176 // If the operand is not a constant integer, nothing to do.
1177 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1178 if (!OpC) return false;
1179
1180 // If there are no bits set that aren't demanded, nothing to do.
1181 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1182 if ((~Demanded & OpC->getValue()) == 0)
1183 return false;
1184
1185 // This instruction is producing bits that are not demanded. Shrink the RHS.
1186 Demanded &= OpC->getValue();
1187 I->setOperand(OpNo, ConstantInt::get(Demanded));
1188 return true;
1189}
1190
1191// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1192// set of known zero and one bits, compute the maximum and minimum values that
1193// could have the specified known zero and known one bits, returning them in
1194// min/max.
1195static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1196 const APInt& KnownZero,
1197 const APInt& KnownOne,
1198 APInt& Min, APInt& Max) {
1199 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1200 assert(KnownZero.getBitWidth() == BitWidth &&
1201 KnownOne.getBitWidth() == BitWidth &&
1202 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1203 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1204 APInt UnknownBits = ~(KnownZero|KnownOne);
1205
1206 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1207 // bit if it is unknown.
1208 Min = KnownOne;
1209 Max = KnownOne|UnknownBits;
1210
1211 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1212 Min.set(BitWidth-1);
1213 Max.clear(BitWidth-1);
1214 }
1215}
1216
1217// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1218// a set of known zero and one bits, compute the maximum and minimum values that
1219// could have the specified known zero and known one bits, returning them in
1220// min/max.
1221static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001222 const APInt &KnownZero,
1223 const APInt &KnownOne,
1224 APInt &Min, APInt &Max) {
1225 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 assert(KnownZero.getBitWidth() == BitWidth &&
1227 KnownOne.getBitWidth() == BitWidth &&
1228 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1229 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1230 APInt UnknownBits = ~(KnownZero|KnownOne);
1231
1232 // The minimum value is when the unknown bits are all zeros.
1233 Min = KnownOne;
1234 // The maximum value is when the unknown bits are all ones.
1235 Max = KnownOne|UnknownBits;
1236}
1237
1238/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1239/// value based on the demanded bits. When this function is called, it is known
1240/// that only the bits set in DemandedMask of the result of V are ever used
1241/// downstream. Consequently, depending on the mask and V, it may be possible
1242/// to replace V with a constant or one of its operands. In such cases, this
1243/// function does the replacement and returns true. In all other cases, it
1244/// returns false after analyzing the expression and setting KnownOne and known
1245/// to be one in the expression. KnownZero contains all the bits that are known
1246/// to be zero in the expression. These are provided to potentially allow the
1247/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1248/// the expression. KnownOne and KnownZero always follow the invariant that
1249/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1250/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1251/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1252/// and KnownOne must all be the same.
1253bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1254 APInt& KnownZero, APInt& KnownOne,
1255 unsigned Depth) {
1256 assert(V != 0 && "Null pointer of Value???");
1257 assert(Depth <= 6 && "Limit Search Depth");
1258 uint32_t BitWidth = DemandedMask.getBitWidth();
1259 const IntegerType *VTy = cast<IntegerType>(V->getType());
1260 assert(VTy->getBitWidth() == BitWidth &&
1261 KnownZero.getBitWidth() == BitWidth &&
1262 KnownOne.getBitWidth() == BitWidth &&
1263 "Value *V, DemandedMask, KnownZero and KnownOne \
1264 must have same BitWidth");
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1266 // We know all of the bits for a constant!
1267 KnownOne = CI->getValue() & DemandedMask;
1268 KnownZero = ~KnownOne & DemandedMask;
1269 return false;
1270 }
1271
1272 KnownZero.clear();
1273 KnownOne.clear();
1274 if (!V->hasOneUse()) { // Other users may use these bits.
1275 if (Depth != 0) { // Not at the root.
1276 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1277 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1278 return false;
1279 }
1280 // If this is the root being simplified, allow it to have multiple uses,
1281 // just set the DemandedMask to all bits.
1282 DemandedMask = APInt::getAllOnesValue(BitWidth);
1283 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1284 if (V != UndefValue::get(VTy))
1285 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1286 return false;
1287 } else if (Depth == 6) { // Limit search depth.
1288 return false;
1289 }
1290
1291 Instruction *I = dyn_cast<Instruction>(V);
1292 if (!I) return false; // Only analyze instructions.
1293
1294 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1295 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1296 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001297 default:
1298 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1299 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 case Instruction::And:
1301 // If either the LHS or the RHS are Zero, the result is zero.
1302 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1303 RHSKnownZero, RHSKnownOne, Depth+1))
1304 return true;
1305 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1306 "Bits known to be one AND zero?");
1307
1308 // If something is known zero on the RHS, the bits aren't demanded on the
1309 // LHS.
1310 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1311 LHSKnownZero, LHSKnownOne, Depth+1))
1312 return true;
1313 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1314 "Bits known to be one AND zero?");
1315
1316 // If all of the demanded bits are known 1 on one side, return the other.
1317 // These bits cannot contribute to the result of the 'and'.
1318 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1319 (DemandedMask & ~LHSKnownZero))
1320 return UpdateValueUsesWith(I, I->getOperand(0));
1321 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1322 (DemandedMask & ~RHSKnownZero))
1323 return UpdateValueUsesWith(I, I->getOperand(1));
1324
1325 // If all of the demanded bits in the inputs are known zeros, return zero.
1326 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1327 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1328
1329 // If the RHS is a constant, see if we can simplify it.
1330 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1331 return UpdateValueUsesWith(I, I);
1332
1333 // Output known-1 bits are only known if set in both the LHS & RHS.
1334 RHSKnownOne &= LHSKnownOne;
1335 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1336 RHSKnownZero |= LHSKnownZero;
1337 break;
1338 case Instruction::Or:
1339 // If either the LHS or the RHS are One, the result is One.
1340 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1341 RHSKnownZero, RHSKnownOne, Depth+1))
1342 return true;
1343 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1344 "Bits known to be one AND zero?");
1345 // If something is known one on the RHS, the bits aren't demanded on the
1346 // LHS.
1347 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1348 LHSKnownZero, LHSKnownOne, Depth+1))
1349 return true;
1350 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1351 "Bits known to be one AND zero?");
1352
1353 // If all of the demanded bits are known zero on one side, return the other.
1354 // These bits cannot contribute to the result of the 'or'.
1355 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1356 (DemandedMask & ~LHSKnownOne))
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1359 (DemandedMask & ~RHSKnownOne))
1360 return UpdateValueUsesWith(I, I->getOperand(1));
1361
1362 // If all of the potentially set bits on one side are known to be set on
1363 // the other side, just use the 'other' side.
1364 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1365 (DemandedMask & (~RHSKnownZero)))
1366 return UpdateValueUsesWith(I, I->getOperand(0));
1367 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1368 (DemandedMask & (~LHSKnownZero)))
1369 return UpdateValueUsesWith(I, I->getOperand(1));
1370
1371 // If the RHS is a constant, see if we can simplify it.
1372 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1373 return UpdateValueUsesWith(I, I);
1374
1375 // Output known-0 bits are only known if clear in both the LHS & RHS.
1376 RHSKnownZero &= LHSKnownZero;
1377 // Output known-1 are known to be set if set in either the LHS | RHS.
1378 RHSKnownOne |= LHSKnownOne;
1379 break;
1380 case Instruction::Xor: {
1381 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1382 RHSKnownZero, RHSKnownOne, Depth+1))
1383 return true;
1384 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1385 "Bits known to be one AND zero?");
1386 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1387 LHSKnownZero, LHSKnownOne, Depth+1))
1388 return true;
1389 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1390 "Bits known to be one AND zero?");
1391
1392 // If all of the demanded bits are known zero on one side, return the other.
1393 // These bits cannot contribute to the result of the 'xor'.
1394 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(0));
1396 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1397 return UpdateValueUsesWith(I, I->getOperand(1));
1398
1399 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1400 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1401 (RHSKnownOne & LHSKnownOne);
1402 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1403 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1404 (RHSKnownOne & LHSKnownZero);
1405
1406 // If all of the demanded bits are known to be zero on one side or the
1407 // other, turn this into an *inclusive* or.
1408 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1409 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1410 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001411 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 I->getName());
1413 InsertNewInstBefore(Or, *I);
1414 return UpdateValueUsesWith(I, Or);
1415 }
1416
1417 // If all of the demanded bits on one side are known, and all of the set
1418 // bits on that side are also known to be set on the other side, turn this
1419 // into an AND, as we know the bits will be cleared.
1420 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1421 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1422 // all known
1423 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1424 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1425 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001426 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 InsertNewInstBefore(And, *I);
1428 return UpdateValueUsesWith(I, And);
1429 }
1430 }
1431
1432 // If the RHS is a constant, see if we can simplify it.
1433 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1434 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1435 return UpdateValueUsesWith(I, I);
1436
1437 RHSKnownZero = KnownZeroOut;
1438 RHSKnownOne = KnownOneOut;
1439 break;
1440 }
1441 case Instruction::Select:
1442 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1443 RHSKnownZero, RHSKnownOne, Depth+1))
1444 return true;
1445 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1446 LHSKnownZero, LHSKnownOne, Depth+1))
1447 return true;
1448 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1451 "Bits known to be one AND zero?");
1452
1453 // If the operands are constants, see if we can simplify them.
1454 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1457 return UpdateValueUsesWith(I, I);
1458
1459 // Only known if known in both the LHS and RHS.
1460 RHSKnownOne &= LHSKnownOne;
1461 RHSKnownZero &= LHSKnownZero;
1462 break;
1463 case Instruction::Trunc: {
1464 uint32_t truncBf =
1465 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1466 DemandedMask.zext(truncBf);
1467 RHSKnownZero.zext(truncBf);
1468 RHSKnownOne.zext(truncBf);
1469 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1470 RHSKnownZero, RHSKnownOne, Depth+1))
1471 return true;
1472 DemandedMask.trunc(BitWidth);
1473 RHSKnownZero.trunc(BitWidth);
1474 RHSKnownOne.trunc(BitWidth);
1475 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1476 "Bits known to be one AND zero?");
1477 break;
1478 }
1479 case Instruction::BitCast:
1480 if (!I->getOperand(0)->getType()->isInteger())
1481 return false;
1482
1483 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1484 RHSKnownZero, RHSKnownOne, Depth+1))
1485 return true;
1486 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1487 "Bits known to be one AND zero?");
1488 break;
1489 case Instruction::ZExt: {
1490 // Compute the bits in the result that are not present in the input.
1491 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1492 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1493
1494 DemandedMask.trunc(SrcBitWidth);
1495 RHSKnownZero.trunc(SrcBitWidth);
1496 RHSKnownOne.trunc(SrcBitWidth);
1497 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1498 RHSKnownZero, RHSKnownOne, Depth+1))
1499 return true;
1500 DemandedMask.zext(BitWidth);
1501 RHSKnownZero.zext(BitWidth);
1502 RHSKnownOne.zext(BitWidth);
1503 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1504 "Bits known to be one AND zero?");
1505 // The top bits are known to be zero.
1506 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1507 break;
1508 }
1509 case Instruction::SExt: {
1510 // Compute the bits in the result that are not present in the input.
1511 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1512 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1513
1514 APInt InputDemandedBits = DemandedMask &
1515 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1516
1517 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1518 // If any of the sign extended bits are demanded, we know that the sign
1519 // bit is demanded.
1520 if ((NewBits & DemandedMask) != 0)
1521 InputDemandedBits.set(SrcBitWidth-1);
1522
1523 InputDemandedBits.trunc(SrcBitWidth);
1524 RHSKnownZero.trunc(SrcBitWidth);
1525 RHSKnownOne.trunc(SrcBitWidth);
1526 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1527 RHSKnownZero, RHSKnownOne, Depth+1))
1528 return true;
1529 InputDemandedBits.zext(BitWidth);
1530 RHSKnownZero.zext(BitWidth);
1531 RHSKnownOne.zext(BitWidth);
1532 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1533 "Bits known to be one AND zero?");
1534
1535 // If the sign bit of the input is known set or clear, then we know the
1536 // top bits of the result.
1537
1538 // If the input sign bit is known zero, or if the NewBits are not demanded
1539 // convert this into a zero extension.
1540 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1541 {
1542 // Convert to ZExt cast
1543 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1544 return UpdateValueUsesWith(I, NewCast);
1545 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1546 RHSKnownOne |= NewBits;
1547 }
1548 break;
1549 }
1550 case Instruction::Add: {
1551 // Figure out what the input bits are. If the top bits of the and result
1552 // are not demanded, then the add doesn't demand them from its input
1553 // either.
1554 uint32_t NLZ = DemandedMask.countLeadingZeros();
1555
1556 // If there is a constant on the RHS, there are a variety of xformations
1557 // we can do.
1558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1559 // If null, this should be simplified elsewhere. Some of the xforms here
1560 // won't work if the RHS is zero.
1561 if (RHS->isZero())
1562 break;
1563
1564 // If the top bit of the output is demanded, demand everything from the
1565 // input. Otherwise, we demand all the input bits except NLZ top bits.
1566 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1567
1568 // Find information about known zero/one bits in the input.
1569 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1570 LHSKnownZero, LHSKnownOne, Depth+1))
1571 return true;
1572
1573 // If the RHS of the add has bits set that can't affect the input, reduce
1574 // the constant.
1575 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1576 return UpdateValueUsesWith(I, I);
1577
1578 // Avoid excess work.
1579 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1580 break;
1581
1582 // Turn it into OR if input bits are zero.
1583 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1584 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001585 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 I->getName());
1587 InsertNewInstBefore(Or, *I);
1588 return UpdateValueUsesWith(I, Or);
1589 }
1590
1591 // We can say something about the output known-zero and known-one bits,
1592 // depending on potential carries from the input constant and the
1593 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1594 // bits set and the RHS constant is 0x01001, then we know we have a known
1595 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1596
1597 // To compute this, we first compute the potential carry bits. These are
1598 // the bits which may be modified. I'm not aware of a better way to do
1599 // this scan.
1600 const APInt& RHSVal = RHS->getValue();
1601 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1602
1603 // Now that we know which bits have carries, compute the known-1/0 sets.
1604
1605 // Bits are known one if they are known zero in one operand and one in the
1606 // other, and there is no input carry.
1607 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1608 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1609
1610 // Bits are known zero if they are known zero in both operands and there
1611 // is no input carry.
1612 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1613 } else {
1614 // If the high-bits of this ADD are not demanded, then it does not demand
1615 // the high bits of its LHS or RHS.
1616 if (DemandedMask[BitWidth-1] == 0) {
1617 // Right fill the mask of bits for this ADD to demand the most
1618 // significant bit and all those below it.
1619 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1620 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1621 LHSKnownZero, LHSKnownOne, Depth+1))
1622 return true;
1623 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 }
1627 }
1628 break;
1629 }
1630 case Instruction::Sub:
1631 // If the high-bits of this SUB are not demanded, then it does not demand
1632 // the high bits of its LHS or RHS.
1633 if (DemandedMask[BitWidth-1] == 0) {
1634 // Right fill the mask of bits for this SUB to demand the most
1635 // significant bit and all those below it.
1636 uint32_t NLZ = DemandedMask.countLeadingZeros();
1637 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1638 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1639 LHSKnownZero, LHSKnownOne, Depth+1))
1640 return true;
1641 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1642 LHSKnownZero, LHSKnownOne, Depth+1))
1643 return true;
1644 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001645 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1646 // the known zeros and ones.
1647 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 break;
1649 case Instruction::Shl:
1650 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1651 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1652 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1653 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1654 RHSKnownZero, RHSKnownOne, Depth+1))
1655 return true;
1656 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1657 "Bits known to be one AND zero?");
1658 RHSKnownZero <<= ShiftAmt;
1659 RHSKnownOne <<= ShiftAmt;
1660 // low bits known zero.
1661 if (ShiftAmt)
1662 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1663 }
1664 break;
1665 case Instruction::LShr:
1666 // For a logical shift right
1667 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1668 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1669
1670 // Unsigned shift right.
1671 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1672 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1673 RHSKnownZero, RHSKnownOne, Depth+1))
1674 return true;
1675 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1676 "Bits known to be one AND zero?");
1677 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1678 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1679 if (ShiftAmt) {
1680 // Compute the new bits that are at the top now.
1681 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1682 RHSKnownZero |= HighBits; // high bits known zero.
1683 }
1684 }
1685 break;
1686 case Instruction::AShr:
1687 // If this is an arithmetic shift right and only the low-bit is set, we can
1688 // always convert this into a logical shr, even if the shift amount is
1689 // variable. The low bit of the shift cannot be an input sign bit unless
1690 // the shift amount is >= the size of the datatype, which is undefined.
1691 if (DemandedMask == 1) {
1692 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001693 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 I->getOperand(0), I->getOperand(1), I->getName());
1695 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1696 return UpdateValueUsesWith(I, NewVal);
1697 }
1698
1699 // If the sign bit is the only bit demanded by this ashr, then there is no
1700 // need to do it, the shift doesn't change the high bit.
1701 if (DemandedMask.isSignBit())
1702 return UpdateValueUsesWith(I, I->getOperand(0));
1703
1704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1705 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1706
1707 // Signed shift right.
1708 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1709 // If any of the "high bits" are demanded, we should set the sign bit as
1710 // demanded.
1711 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1712 DemandedMaskIn.set(BitWidth-1);
1713 if (SimplifyDemandedBits(I->getOperand(0),
1714 DemandedMaskIn,
1715 RHSKnownZero, RHSKnownOne, Depth+1))
1716 return true;
1717 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1718 "Bits known to be one AND zero?");
1719 // Compute the new bits that are at the top now.
1720 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1721 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1722 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1723
1724 // Handle the sign bits.
1725 APInt SignBit(APInt::getSignBit(BitWidth));
1726 // Adjust to where it is now in the mask.
1727 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1728
1729 // If the input sign bit is known to be zero, or if none of the top bits
1730 // are demanded, turn this into an unsigned shift right.
1731 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1732 (HighBits & ~DemandedMask) == HighBits) {
1733 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001734 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001735 I->getOperand(0), SA, I->getName());
1736 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1737 return UpdateValueUsesWith(I, NewVal);
1738 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1739 RHSKnownOne |= HighBits;
1740 }
1741 }
1742 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001743 case Instruction::SRem:
1744 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1745 APInt RA = Rem->getValue();
1746 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001747 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001748 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1749 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1750 LHSKnownZero, LHSKnownOne, Depth+1))
1751 return true;
1752
1753 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1754 LHSKnownZero |= ~LowBits;
1755 else if (LHSKnownOne[BitWidth-1])
1756 LHSKnownOne |= ~LowBits;
1757
1758 KnownZero |= LHSKnownZero & DemandedMask;
1759 KnownOne |= LHSKnownOne & DemandedMask;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1762 }
1763 }
1764 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001765 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001766 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1767 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001768 if (RA.isPowerOf2()) {
1769 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001770 APInt Mask2 = LowBits & DemandedMask;
1771 KnownZero |= ~LowBits & DemandedMask;
1772 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1773 KnownZero, KnownOne, Depth+1))
1774 return true;
1775
1776 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001777 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001778 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001779 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001780
1781 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1782 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001783 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1784 KnownZero2, KnownOne2, Depth+1))
1785 return true;
1786
Dan Gohmanbec16052008-04-28 17:02:21 +00001787 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001788 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001789 KnownZero2, KnownOne2, Depth+1))
1790 return true;
1791
1792 Leaders = std::max(Leaders,
1793 KnownZero2.countLeadingOnes());
1794 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001795 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001797 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798
1799 // If the client is only demanding bits that we know, return the known
1800 // constant.
1801 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1802 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1803 return false;
1804}
1805
1806
1807/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1808/// 64 or fewer elements. DemandedElts contains the set of elements that are
1809/// actually used by the caller. This method analyzes which elements of the
1810/// operand are undef and returns that information in UndefElts.
1811///
1812/// If the information about demanded elements can be used to simplify the
1813/// operation, the operation is simplified, then the resultant value is
1814/// returned. This returns null if no change was made.
1815Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1816 uint64_t &UndefElts,
1817 unsigned Depth) {
1818 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1819 assert(VWidth <= 64 && "Vector too wide to analyze!");
1820 uint64_t EltMask = ~0ULL >> (64-VWidth);
1821 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1822 "Invalid DemandedElts!");
1823
1824 if (isa<UndefValue>(V)) {
1825 // If the entire vector is undefined, just return this info.
1826 UndefElts = EltMask;
1827 return 0;
1828 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1829 UndefElts = EltMask;
1830 return UndefValue::get(V->getType());
1831 }
1832
1833 UndefElts = 0;
1834 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1835 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1836 Constant *Undef = UndefValue::get(EltTy);
1837
1838 std::vector<Constant*> Elts;
1839 for (unsigned i = 0; i != VWidth; ++i)
1840 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1841 Elts.push_back(Undef);
1842 UndefElts |= (1ULL << i);
1843 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1844 Elts.push_back(Undef);
1845 UndefElts |= (1ULL << i);
1846 } else { // Otherwise, defined.
1847 Elts.push_back(CP->getOperand(i));
1848 }
1849
1850 // If we changed the constant, return it.
1851 Constant *NewCP = ConstantVector::get(Elts);
1852 return NewCP != CP ? NewCP : 0;
1853 } else if (isa<ConstantAggregateZero>(V)) {
1854 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1855 // set to undef.
1856 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1857 Constant *Zero = Constant::getNullValue(EltTy);
1858 Constant *Undef = UndefValue::get(EltTy);
1859 std::vector<Constant*> Elts;
1860 for (unsigned i = 0; i != VWidth; ++i)
1861 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1862 UndefElts = DemandedElts ^ EltMask;
1863 return ConstantVector::get(Elts);
1864 }
1865
1866 if (!V->hasOneUse()) { // Other users may use these bits.
1867 if (Depth != 0) { // Not at the root.
1868 // TODO: Just compute the UndefElts information recursively.
1869 return false;
1870 }
1871 return false;
1872 } else if (Depth == 10) { // Limit search depth.
1873 return false;
1874 }
1875
1876 Instruction *I = dyn_cast<Instruction>(V);
1877 if (!I) return false; // Only analyze instructions.
1878
1879 bool MadeChange = false;
1880 uint64_t UndefElts2;
1881 Value *TmpV;
1882 switch (I->getOpcode()) {
1883 default: break;
1884
1885 case Instruction::InsertElement: {
1886 // If this is a variable index, we don't know which element it overwrites.
1887 // demand exactly the same input as we produce.
1888 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1889 if (Idx == 0) {
1890 // Note that we can't propagate undef elt info, because we don't know
1891 // which elt is getting updated.
1892 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1893 UndefElts2, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895 break;
1896 }
1897
1898 // If this is inserting an element that isn't demanded, remove this
1899 // insertelement.
1900 unsigned IdxNo = Idx->getZExtValue();
1901 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1902 return AddSoonDeadInstToWorklist(*I, 0);
1903
1904 // Otherwise, the element inserted overwrites whatever was there, so the
1905 // input demanded set is simpler than the output set.
1906 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1907 DemandedElts & ~(1ULL << IdxNo),
1908 UndefElts, Depth+1);
1909 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1910
1911 // The inserted element is defined.
1912 UndefElts |= 1ULL << IdxNo;
1913 break;
1914 }
1915 case Instruction::BitCast: {
1916 // Vector->vector casts only.
1917 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1918 if (!VTy) break;
1919 unsigned InVWidth = VTy->getNumElements();
1920 uint64_t InputDemandedElts = 0;
1921 unsigned Ratio;
1922
1923 if (VWidth == InVWidth) {
1924 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1925 // elements as are demanded of us.
1926 Ratio = 1;
1927 InputDemandedElts = DemandedElts;
1928 } else if (VWidth > InVWidth) {
1929 // Untested so far.
1930 break;
1931
1932 // If there are more elements in the result than there are in the source,
1933 // then an input element is live if any of the corresponding output
1934 // elements are live.
1935 Ratio = VWidth/InVWidth;
1936 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1937 if (DemandedElts & (1ULL << OutIdx))
1938 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1939 }
1940 } else {
1941 // Untested so far.
1942 break;
1943
1944 // If there are more elements in the source than there are in the result,
1945 // then an input element is live if the corresponding output element is
1946 // live.
1947 Ratio = InVWidth/VWidth;
1948 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1949 if (DemandedElts & (1ULL << InIdx/Ratio))
1950 InputDemandedElts |= 1ULL << InIdx;
1951 }
1952
1953 // div/rem demand all inputs, because they don't want divide by zero.
1954 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1955 UndefElts2, Depth+1);
1956 if (TmpV) {
1957 I->setOperand(0, TmpV);
1958 MadeChange = true;
1959 }
1960
1961 UndefElts = UndefElts2;
1962 if (VWidth > InVWidth) {
1963 assert(0 && "Unimp");
1964 // If there are more elements in the result than there are in the source,
1965 // then an output element is undef if the corresponding input element is
1966 // undef.
1967 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1968 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1969 UndefElts |= 1ULL << OutIdx;
1970 } else if (VWidth < InVWidth) {
1971 assert(0 && "Unimp");
1972 // If there are more elements in the source than there are in the result,
1973 // then a result element is undef if all of the corresponding input
1974 // elements are undef.
1975 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1976 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1977 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1978 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1979 }
1980 break;
1981 }
1982 case Instruction::And:
1983 case Instruction::Or:
1984 case Instruction::Xor:
1985 case Instruction::Add:
1986 case Instruction::Sub:
1987 case Instruction::Mul:
1988 // div/rem demand all inputs, because they don't want divide by zero.
1989 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1990 UndefElts, Depth+1);
1991 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1992 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1993 UndefElts2, Depth+1);
1994 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1995
1996 // Output elements are undefined if both are undefined. Consider things
1997 // like undef&0. The result is known zero, not undef.
1998 UndefElts &= UndefElts2;
1999 break;
2000
2001 case Instruction::Call: {
2002 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2003 if (!II) break;
2004 switch (II->getIntrinsicID()) {
2005 default: break;
2006
2007 // Binary vector operations that work column-wise. A dest element is a
2008 // function of the corresponding input elements from the two inputs.
2009 case Intrinsic::x86_sse_sub_ss:
2010 case Intrinsic::x86_sse_mul_ss:
2011 case Intrinsic::x86_sse_min_ss:
2012 case Intrinsic::x86_sse_max_ss:
2013 case Intrinsic::x86_sse2_sub_sd:
2014 case Intrinsic::x86_sse2_mul_sd:
2015 case Intrinsic::x86_sse2_min_sd:
2016 case Intrinsic::x86_sse2_max_sd:
2017 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2018 UndefElts, Depth+1);
2019 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2020 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2021 UndefElts2, Depth+1);
2022 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2023
2024 // If only the low elt is demanded and this is a scalarizable intrinsic,
2025 // scalarize it now.
2026 if (DemandedElts == 1) {
2027 switch (II->getIntrinsicID()) {
2028 default: break;
2029 case Intrinsic::x86_sse_sub_ss:
2030 case Intrinsic::x86_sse_mul_ss:
2031 case Intrinsic::x86_sse2_sub_sd:
2032 case Intrinsic::x86_sse2_mul_sd:
2033 // TODO: Lower MIN/MAX/ABS/etc
2034 Value *LHS = II->getOperand(1);
2035 Value *RHS = II->getOperand(2);
2036 // Extract the element as scalars.
2037 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2038 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2039
2040 switch (II->getIntrinsicID()) {
2041 default: assert(0 && "Case stmts out of sync!");
2042 case Intrinsic::x86_sse_sub_ss:
2043 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002044 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 II->getName()), *II);
2046 break;
2047 case Intrinsic::x86_sse_mul_ss:
2048 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002049 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050 II->getName()), *II);
2051 break;
2052 }
2053
2054 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00002055 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2056 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 InsertNewInstBefore(New, *II);
2058 AddSoonDeadInstToWorklist(*II, 0);
2059 return New;
2060 }
2061 }
2062
2063 // Output elements are undefined if both are undefined. Consider things
2064 // like undef&0. The result is known zero, not undef.
2065 UndefElts &= UndefElts2;
2066 break;
2067 }
2068 break;
2069 }
2070 }
2071 return MadeChange ? I : 0;
2072}
2073
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074/// AssociativeOpt - Perform an optimization on an associative operator. This
2075/// function is designed to check a chain of associative operators for a
2076/// potential to apply a certain optimization. Since the optimization may be
2077/// applicable if the expression was reassociated, this checks the chain, then
2078/// reassociates the expression as necessary to expose the optimization
2079/// opportunity. This makes use of a special Functor, which must define
2080/// 'shouldApply' and 'apply' methods.
2081///
2082template<typename Functor>
2083Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2084 unsigned Opcode = Root.getOpcode();
2085 Value *LHS = Root.getOperand(0);
2086
2087 // Quick check, see if the immediate LHS matches...
2088 if (F.shouldApply(LHS))
2089 return F.apply(Root);
2090
2091 // Otherwise, if the LHS is not of the same opcode as the root, return.
2092 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2093 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2094 // Should we apply this transform to the RHS?
2095 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2096
2097 // If not to the RHS, check to see if we should apply to the LHS...
2098 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2099 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2100 ShouldApply = true;
2101 }
2102
2103 // If the functor wants to apply the optimization to the RHS of LHSI,
2104 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2105 if (ShouldApply) {
2106 BasicBlock *BB = Root.getParent();
2107
2108 // Now all of the instructions are in the current basic block, go ahead
2109 // and perform the reassociation.
2110 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2111
2112 // First move the selected RHS to the LHS of the root...
2113 Root.setOperand(0, LHSI->getOperand(1));
2114
2115 // Make what used to be the LHS of the root be the user of the root...
2116 Value *ExtraOperand = TmpLHSI->getOperand(1);
2117 if (&Root == TmpLHSI) {
2118 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2119 return 0;
2120 }
2121 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2122 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2123 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2124 BasicBlock::iterator ARI = &Root; ++ARI;
2125 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2126 ARI = Root;
2127
2128 // Now propagate the ExtraOperand down the chain of instructions until we
2129 // get to LHSI.
2130 while (TmpLHSI != LHSI) {
2131 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2132 // Move the instruction to immediately before the chain we are
2133 // constructing to avoid breaking dominance properties.
2134 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2135 BB->getInstList().insert(ARI, NextLHSI);
2136 ARI = NextLHSI;
2137
2138 Value *NextOp = NextLHSI->getOperand(1);
2139 NextLHSI->setOperand(1, ExtraOperand);
2140 TmpLHSI = NextLHSI;
2141 ExtraOperand = NextOp;
2142 }
2143
2144 // Now that the instructions are reassociated, have the functor perform
2145 // the transformation...
2146 return F.apply(Root);
2147 }
2148
2149 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2150 }
2151 return 0;
2152}
2153
Dan Gohman089efff2008-05-13 00:00:25 +00002154namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155
2156// AddRHS - Implements: X + X --> X << 1
2157struct AddRHS {
2158 Value *RHS;
2159 AddRHS(Value *rhs) : RHS(rhs) {}
2160 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2161 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002162 return BinaryOperator::CreateShl(Add.getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 ConstantInt::get(Add.getType(), 1));
2164 }
2165};
2166
2167// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2168// iff C1&C2 == 0
2169struct AddMaskingAnd {
2170 Constant *C2;
2171 AddMaskingAnd(Constant *c) : C2(c) {}
2172 bool shouldApply(Value *LHS) const {
2173 ConstantInt *C1;
2174 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2175 ConstantExpr::getAnd(C1, C2)->isNullValue();
2176 }
2177 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002178 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 }
2180};
2181
Dan Gohman089efff2008-05-13 00:00:25 +00002182}
2183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2185 InstCombiner *IC) {
2186 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2187 if (Constant *SOC = dyn_cast<Constant>(SO))
2188 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2189
Gabor Greifa645dd32008-05-16 19:29:10 +00002190 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2192 }
2193
2194 // Figure out if the constant is the left or the right argument.
2195 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2196 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2197
2198 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2199 if (ConstIsRHS)
2200 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2201 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2202 }
2203
2204 Value *Op0 = SO, *Op1 = ConstOperand;
2205 if (!ConstIsRHS)
2206 std::swap(Op0, Op1);
2207 Instruction *New;
2208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002209 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002211 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002212 SO->getName()+".cmp");
2213 else {
2214 assert(0 && "Unknown binary instruction type!");
2215 abort();
2216 }
2217 return IC->InsertNewInstBefore(New, I);
2218}
2219
2220// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2221// constant as the other operand, try to fold the binary operator into the
2222// select arguments. This also works for Cast instructions, which obviously do
2223// not have a second operand.
2224static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2225 InstCombiner *IC) {
2226 // Don't modify shared select instructions
2227 if (!SI->hasOneUse()) return 0;
2228 Value *TV = SI->getOperand(1);
2229 Value *FV = SI->getOperand(2);
2230
2231 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2232 // Bool selects with constant operands can be folded to logical ops.
2233 if (SI->getType() == Type::Int1Ty) return 0;
2234
2235 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2236 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2237
Gabor Greifd6da1d02008-04-06 20:25:17 +00002238 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2239 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 }
2241 return 0;
2242}
2243
2244
2245/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2246/// node as operand #0, see if we can fold the instruction into the PHI (which
2247/// is only possible if all operands to the PHI are constants).
2248Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2249 PHINode *PN = cast<PHINode>(I.getOperand(0));
2250 unsigned NumPHIValues = PN->getNumIncomingValues();
2251 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2252
2253 // Check to see if all of the operands of the PHI are constants. If there is
2254 // one non-constant value, remember the BB it is. If there is more than one
2255 // or if *it* is a PHI, bail out.
2256 BasicBlock *NonConstBB = 0;
2257 for (unsigned i = 0; i != NumPHIValues; ++i)
2258 if (!isa<Constant>(PN->getIncomingValue(i))) {
2259 if (NonConstBB) return 0; // More than one non-const value.
2260 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2261 NonConstBB = PN->getIncomingBlock(i);
2262
2263 // If the incoming non-constant value is in I's block, we have an infinite
2264 // loop.
2265 if (NonConstBB == I.getParent())
2266 return 0;
2267 }
2268
2269 // If there is exactly one non-constant value, we can insert a copy of the
2270 // operation in that block. However, if this is a critical edge, we would be
2271 // inserting the computation one some other paths (e.g. inside a loop). Only
2272 // do this if the pred block is unconditionally branching into the phi block.
2273 if (NonConstBB) {
2274 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2275 if (!BI || !BI->isUnconditional()) return 0;
2276 }
2277
2278 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002279 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2281 InsertNewInstBefore(NewPN, *PN);
2282 NewPN->takeName(PN);
2283
2284 // Next, add all of the operands to the PHI.
2285 if (I.getNumOperands() == 2) {
2286 Constant *C = cast<Constant>(I.getOperand(1));
2287 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002288 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002289 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2290 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2291 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2292 else
2293 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2294 } else {
2295 assert(PN->getIncomingBlock(i) == NonConstBB);
2296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002297 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002298 PN->getIncomingValue(i), C, "phitmp",
2299 NonConstBB->getTerminator());
2300 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002301 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 CI->getPredicate(),
2303 PN->getIncomingValue(i), C, "phitmp",
2304 NonConstBB->getTerminator());
2305 else
2306 assert(0 && "Unknown binop!");
2307
2308 AddToWorkList(cast<Instruction>(InV));
2309 }
2310 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2311 }
2312 } else {
2313 CastInst *CI = cast<CastInst>(&I);
2314 const Type *RetTy = CI->getType();
2315 for (unsigned i = 0; i != NumPHIValues; ++i) {
2316 Value *InV;
2317 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2318 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2319 } else {
2320 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002321 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322 I.getType(), "phitmp",
2323 NonConstBB->getTerminator());
2324 AddToWorkList(cast<Instruction>(InV));
2325 }
2326 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2327 }
2328 }
2329 return ReplaceInstUsesWith(I, NewPN);
2330}
2331
Chris Lattner55476162008-01-29 06:52:45 +00002332
2333/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2334/// value is never equal to -0.0.
2335///
2336/// Note that this function will need to be revisited when we support nondefault
2337/// rounding modes!
2338///
2339static bool CannotBeNegativeZero(const Value *V) {
2340 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2341 return !CFP->getValueAPF().isNegZero();
2342
Chris Lattner55476162008-01-29 06:52:45 +00002343 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnere3061db2008-05-19 20:27:56 +00002344 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner55476162008-01-29 06:52:45 +00002345 if (I->getOpcode() == Instruction::Add &&
2346 isa<ConstantFP>(I->getOperand(1)) &&
2347 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2348 return true;
2349
Chris Lattnere3061db2008-05-19 20:27:56 +00002350 // sitofp and uitofp turn into +0.0 for zero.
2351 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2352 return true;
2353
Chris Lattner55476162008-01-29 06:52:45 +00002354 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2355 if (II->getIntrinsicID() == Intrinsic::sqrt)
2356 return CannotBeNegativeZero(II->getOperand(1));
2357
2358 if (const CallInst *CI = dyn_cast<CallInst>(I))
2359 if (const Function *F = CI->getCalledFunction()) {
2360 if (F->isDeclaration()) {
2361 switch (F->getNameLen()) {
2362 case 3: // abs(x) != -0.0
2363 if (!strcmp(F->getNameStart(), "abs")) return true;
2364 break;
2365 case 4: // abs[lf](x) != -0.0
2366 if (!strcmp(F->getNameStart(), "absf")) return true;
2367 if (!strcmp(F->getNameStart(), "absl")) return true;
2368 break;
2369 }
2370 }
2371 }
2372 }
2373
2374 return false;
2375}
2376
2377
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002378Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2379 bool Changed = SimplifyCommutative(I);
2380 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2381
2382 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2383 // X + undef -> undef
2384 if (isa<UndefValue>(RHS))
2385 return ReplaceInstUsesWith(I, RHS);
2386
2387 // X + 0 --> X
2388 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2389 if (RHSC->isNullValue())
2390 return ReplaceInstUsesWith(I, LHS);
2391 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002392 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2393 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394 return ReplaceInstUsesWith(I, LHS);
2395 }
2396
2397 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2398 // X + (signbit) --> X ^ signbit
2399 const APInt& Val = CI->getValue();
2400 uint32_t BitWidth = Val.getBitWidth();
2401 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002403
2404 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2405 // (X & 254)+1 -> (X&254)|1
2406 if (!isa<VectorType>(I.getType())) {
2407 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2408 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2409 KnownZero, KnownOne))
2410 return &I;
2411 }
2412 }
2413
2414 if (isa<PHINode>(LHS))
2415 if (Instruction *NV = FoldOpIntoPhi(I))
2416 return NV;
2417
2418 ConstantInt *XorRHS = 0;
2419 Value *XorLHS = 0;
2420 if (isa<ConstantInt>(RHSC) &&
2421 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2422 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2423 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2424
2425 uint32_t Size = TySizeBits / 2;
2426 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2427 APInt CFF80Val(-C0080Val);
2428 do {
2429 if (TySizeBits > Size) {
2430 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2431 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2432 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2433 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2434 // This is a sign extend if the top bits are known zero.
2435 if (!MaskedValueIsZero(XorLHS,
2436 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2437 Size = 0; // Not a sign ext, but can't be any others either.
2438 break;
2439 }
2440 }
2441 Size >>= 1;
2442 C0080Val = APIntOps::lshr(C0080Val, Size);
2443 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2444 } while (Size >= 1);
2445
2446 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002447 // with funny bit widths then this switch statement should be removed. It
2448 // is just here to get the size of the "middle" type back up to something
2449 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450 const Type *MiddleType = 0;
2451 switch (Size) {
2452 default: break;
2453 case 32: MiddleType = Type::Int32Ty; break;
2454 case 16: MiddleType = Type::Int16Ty; break;
2455 case 8: MiddleType = Type::Int8Ty; break;
2456 }
2457 if (MiddleType) {
2458 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2459 InsertNewInstBefore(NewTrunc, I);
2460 return new SExtInst(NewTrunc, I.getType(), I.getName());
2461 }
2462 }
2463 }
2464
2465 // X + X --> X << 1
2466 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2467 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2468
2469 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2470 if (RHSI->getOpcode() == Instruction::Sub)
2471 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2472 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2473 }
2474 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2475 if (LHSI->getOpcode() == Instruction::Sub)
2476 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2477 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2478 }
2479 }
2480
2481 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002482 // -A + -B --> -(A + B)
2483 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002484 if (LHS->getType()->isIntOrIntVector()) {
2485 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002486 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002487 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002488 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002489 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002490 }
2491
Gabor Greifa645dd32008-05-16 19:29:10 +00002492 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002493 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494
2495 // A + -B --> A - B
2496 if (!isa<Constant>(RHS))
2497 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002498 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499
2500
2501 ConstantInt *C2;
2502 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2503 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505
2506 // X*C1 + X*C2 --> X * (C1+C2)
2507 ConstantInt *C1;
2508 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002510 }
2511
2512 // X + X*C --> X * (C+1)
2513 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515
2516 // X + ~X --> -1 since ~X = -X-1
2517 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2518 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2519
2520
2521 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2522 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2523 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2524 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002525
2526 // A+B --> A|B iff A and B have no bits set in common.
2527 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2528 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2529 APInt LHSKnownOne(IT->getBitWidth(), 0);
2530 APInt LHSKnownZero(IT->getBitWidth(), 0);
2531 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2532 if (LHSKnownZero != 0) {
2533 APInt RHSKnownOne(IT->getBitWidth(), 0);
2534 APInt RHSKnownZero(IT->getBitWidth(), 0);
2535 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2536
2537 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002538 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002539 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002540 }
2541 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002542
Nick Lewycky83598a72008-02-03 07:42:09 +00002543 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002544 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002545 Value *W, *X, *Y, *Z;
2546 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2547 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2548 if (W != Y) {
2549 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002550 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002551 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002552 std::swap(W, X);
2553 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002554 std::swap(Y, Z);
2555 std::swap(W, X);
2556 }
2557 }
2558
2559 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002560 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002561 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002562 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002563 }
2564 }
2565 }
2566
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2568 Value *X = 0;
2569 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002570 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571
2572 // (X & FF00) + xx00 -> (X+xx00) & FF00
2573 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2574 Constant *Anded = And(CRHS, C2);
2575 if (Anded == CRHS) {
2576 // See if all bits from the first bit set in the Add RHS up are included
2577 // in the mask. First, get the rightmost bit.
2578 const APInt& AddRHSV = CRHS->getValue();
2579
2580 // Form a mask of all bits from the lowest bit added through the top.
2581 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2582
2583 // See if the and mask includes all of these bits.
2584 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2585
2586 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2587 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002588 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002590 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591 }
2592 }
2593 }
2594
2595 // Try to fold constant add into select arguments.
2596 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2597 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2598 return R;
2599 }
2600
2601 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002602 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002603 {
2604 CastInst *CI = dyn_cast<CastInst>(LHS);
2605 Value *Other = RHS;
2606 if (!CI) {
2607 CI = dyn_cast<CastInst>(RHS);
2608 Other = LHS;
2609 }
2610 if (CI && CI->getType()->isSized() &&
2611 (CI->getType()->getPrimitiveSizeInBits() ==
2612 TD->getIntPtrType()->getPrimitiveSizeInBits())
2613 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002614 unsigned AS =
2615 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002616 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2617 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002618 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619 return new PtrToIntInst(I2, CI->getType());
2620 }
2621 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002622
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002623 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002624 {
2625 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2626 Value *Other = RHS;
2627 if (!SI) {
2628 SI = dyn_cast<SelectInst>(RHS);
2629 Other = LHS;
2630 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002631 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002632 Value *TV = SI->getTrueValue();
2633 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002634 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002635
2636 // Can we fold the add into the argument of the select?
2637 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002638 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2639 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002640 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002641 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2642 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002643 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002644 }
2645 }
Chris Lattner55476162008-01-29 06:52:45 +00002646
2647 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2648 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2649 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2650 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002651
2652 return Changed ? &I : 0;
2653}
2654
2655// isSignBit - Return true if the value represented by the constant only has the
2656// highest order bit set.
2657static bool isSignBit(ConstantInt *CI) {
2658 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2659 return CI->getValue() == APInt::getSignBit(NumBits);
2660}
2661
2662Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2663 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2664
2665 if (Op0 == Op1) // sub X, X -> 0
2666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2667
2668 // If this is a 'B = x-(-A)', change to B = x+A...
2669 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002671
2672 if (isa<UndefValue>(Op0))
2673 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2674 if (isa<UndefValue>(Op1))
2675 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2676
2677 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2678 // Replace (-1 - A) with (~A)...
2679 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681
2682 // C - ~X == X + (1+C)
2683 Value *X = 0;
2684 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002685 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686
2687 // -(X >>u 31) -> (X >>s 31)
2688 // -(X >>s 31) -> (X >>u 31)
2689 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002690 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691 if (SI->getOpcode() == Instruction::LShr) {
2692 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2693 // Check to see if we are shifting out everything but the sign bit.
2694 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2695 SI->getType()->getPrimitiveSizeInBits()-1) {
2696 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002697 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 SI->getOperand(0), CU, SI->getName());
2699 }
2700 }
2701 }
2702 else if (SI->getOpcode() == Instruction::AShr) {
2703 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2704 // Check to see if we are shifting out everything but the sign bit.
2705 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2706 SI->getType()->getPrimitiveSizeInBits()-1) {
2707 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002708 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709 SI->getOperand(0), CU, SI->getName());
2710 }
2711 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002712 }
2713 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 }
2715
2716 // Try to fold constant sub into select arguments.
2717 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2718 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2719 return R;
2720
2721 if (isa<PHINode>(Op0))
2722 if (Instruction *NV = FoldOpIntoPhi(I))
2723 return NV;
2724 }
2725
2726 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2727 if (Op1I->getOpcode() == Instruction::Add &&
2728 !Op0->getType()->isFPOrFPVector()) {
2729 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002730 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002732 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2734 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2735 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002736 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 Op1I->getOperand(0));
2738 }
2739 }
2740
2741 if (Op1I->hasOneUse()) {
2742 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2743 // is not used by anyone else...
2744 //
2745 if (Op1I->getOpcode() == Instruction::Sub &&
2746 !Op1I->getType()->isFPOrFPVector()) {
2747 // Swap the two operands of the subexpr...
2748 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2749 Op1I->setOperand(0, IIOp1);
2750 Op1I->setOperand(1, IIOp0);
2751
2752 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002753 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 }
2755
2756 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2757 //
2758 if (Op1I->getOpcode() == Instruction::And &&
2759 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2760 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2761
2762 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002763 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2764 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 }
2766
2767 // 0 - (X sdiv C) -> (X sdiv -C)
2768 if (Op1I->getOpcode() == Instruction::SDiv)
2769 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2770 if (CSI->isZero())
2771 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 ConstantExpr::getNeg(DivRHS));
2774
2775 // X - X*C --> X * (1-C)
2776 ConstantInt *C2 = 0;
2777 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2778 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002779 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 }
Dan Gohmanda338742007-09-17 17:31:57 +00002781
2782 // X - ((X / Y) * Y) --> X % Y
2783 if (Op1I->getOpcode() == Instruction::Mul)
2784 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2785 if (Op0 == I->getOperand(0) &&
2786 Op1I->getOperand(1) == I->getOperand(1)) {
2787 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002788 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002789 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002790 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002791 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002792 }
2793 }
2794
2795 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002796 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 if (Op0I->getOpcode() == Instruction::Add) {
2798 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2799 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2800 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2801 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2802 } else if (Op0I->getOpcode() == Instruction::Sub) {
2803 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002804 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002806 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807
2808 ConstantInt *C1;
2809 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2810 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002811 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002812
2813 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2814 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002815 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002816 }
2817 return 0;
2818}
2819
2820/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2821/// comparison only checks the sign bit. If it only checks the sign bit, set
2822/// TrueIfSigned if the result of the comparison is true when the input value is
2823/// signed.
2824static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2825 bool &TrueIfSigned) {
2826 switch (pred) {
2827 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2828 TrueIfSigned = true;
2829 return RHS->isZero();
2830 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2831 TrueIfSigned = true;
2832 return RHS->isAllOnesValue();
2833 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2834 TrueIfSigned = false;
2835 return RHS->isAllOnesValue();
2836 case ICmpInst::ICMP_UGT:
2837 // True if LHS u> RHS and RHS == high-bit-mask - 1
2838 TrueIfSigned = true;
2839 return RHS->getValue() ==
2840 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2841 case ICmpInst::ICMP_UGE:
2842 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2843 TrueIfSigned = true;
2844 return RHS->getValue() ==
2845 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2846 default:
2847 return false;
2848 }
2849}
2850
2851Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2852 bool Changed = SimplifyCommutative(I);
2853 Value *Op0 = I.getOperand(0);
2854
2855 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2856 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2857
2858 // Simplify mul instructions with a constant RHS...
2859 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2860 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2861
2862 // ((X << C1)*C2) == (X * (C2 << C1))
2863 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2864 if (SI->getOpcode() == Instruction::Shl)
2865 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002866 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 ConstantExpr::getShl(CI, ShOp));
2868
2869 if (CI->isZero())
2870 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2871 if (CI->equalsInt(1)) // X * 1 == X
2872 return ReplaceInstUsesWith(I, Op0);
2873 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002874 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875
2876 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2877 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002878 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 ConstantInt::get(Op0->getType(), Val.logBase2()));
2880 }
2881 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2882 if (Op1F->isNullValue())
2883 return ReplaceInstUsesWith(I, Op1);
2884
2885 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2886 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002887 // We need a better interface for long double here.
2888 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2889 if (Op1F->isExactlyValue(1.0))
2890 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891 }
2892
2893 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2894 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002895 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002897 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002898 Op1, "tmp");
2899 InsertNewInstBefore(Add, I);
2900 Value *C1C2 = ConstantExpr::getMul(Op1,
2901 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002902 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903
2904 }
2905
2906 // Try to fold constant mul into select arguments.
2907 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2908 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2909 return R;
2910
2911 if (isa<PHINode>(Op0))
2912 if (Instruction *NV = FoldOpIntoPhi(I))
2913 return NV;
2914 }
2915
2916 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2917 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002918 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919
2920 // If one of the operands of the multiply is a cast from a boolean value, then
2921 // we know the bool is either zero or one, so this is a 'masking' multiply.
2922 // See if we can simplify things based on how the boolean was originally
2923 // formed.
2924 CastInst *BoolCast = 0;
2925 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2926 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2927 BoolCast = CI;
2928 if (!BoolCast)
2929 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2930 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2931 BoolCast = CI;
2932 if (BoolCast) {
2933 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2934 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2935 const Type *SCOpTy = SCIOp0->getType();
2936 bool TIS = false;
2937
2938 // If the icmp is true iff the sign bit of X is set, then convert this
2939 // multiply into a shift/and combination.
2940 if (isa<ConstantInt>(SCIOp1) &&
2941 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2942 TIS) {
2943 // Shift the X value right to turn it into "all signbits".
2944 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2945 SCOpTy->getPrimitiveSizeInBits()-1);
2946 Value *V =
2947 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002948 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002949 BoolCast->getOperand(0)->getName()+
2950 ".mask"), I);
2951
2952 // If the multiply type is not the same as the source type, sign extend
2953 // or truncate to the multiply type.
2954 if (I.getType() != V->getType()) {
2955 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2956 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2957 Instruction::CastOps opcode =
2958 (SrcBits == DstBits ? Instruction::BitCast :
2959 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2960 V = InsertCastBefore(opcode, V, I.getType(), I);
2961 }
2962
2963 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002964 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002965 }
2966 }
2967 }
2968
2969 return Changed ? &I : 0;
2970}
2971
2972/// This function implements the transforms on div instructions that work
2973/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2974/// used by the visitors to those instructions.
2975/// @brief Transforms common to all three div instructions
2976Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2978
Chris Lattner653ef3c2008-02-19 06:12:18 +00002979 // undef / X -> 0 for integer.
2980 // undef / X -> undef for FP (the undef could be a snan).
2981 if (isa<UndefValue>(Op0)) {
2982 if (Op0->getType()->isFPOrFPVector())
2983 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002985 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986
2987 // X / undef -> undef
2988 if (isa<UndefValue>(Op1))
2989 return ReplaceInstUsesWith(I, Op1);
2990
Chris Lattner5be238b2008-01-28 00:58:18 +00002991 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2992 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002994 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2995 // the same basic block, then we replace the select with Y, and the
2996 // condition of the select with false (if the cond value is in the same BB).
2997 // If the select has uses other than the div, this allows them to be
2998 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2999 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 if (ST->isNullValue()) {
3001 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3002 if (CondI && CondI->getParent() == I.getParent())
3003 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3004 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3005 I.setOperand(1, SI->getOperand(2));
3006 else
3007 UpdateValueUsesWith(SI, SI->getOperand(2));
3008 return &I;
3009 }
3010
Chris Lattner5be238b2008-01-28 00:58:18 +00003011 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3012 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 if (ST->isNullValue()) {
3014 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3015 if (CondI && CondI->getParent() == I.getParent())
3016 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3017 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3018 I.setOperand(1, SI->getOperand(1));
3019 else
3020 UpdateValueUsesWith(SI, SI->getOperand(1));
3021 return &I;
3022 }
3023 }
3024
3025 return 0;
3026}
3027
3028/// This function implements the transforms common to both integer division
3029/// instructions (udiv and sdiv). It is called by the visitors to those integer
3030/// division instructions.
3031/// @brief Common integer divide transforms
3032Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3034
Chris Lattnercefb36c2008-05-16 02:59:42 +00003035 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3036 if (Op0 == Op1)
3037 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3038
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 if (Instruction *Common = commonDivTransforms(I))
3040 return Common;
3041
3042 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3043 // div X, 1 == X
3044 if (RHS->equalsInt(1))
3045 return ReplaceInstUsesWith(I, Op0);
3046
3047 // (X / C1) / C2 -> X / (C1*C2)
3048 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3049 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3050 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00003051 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003054 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00003055 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056 }
3057
3058 if (!RHS->isZero()) { // avoid X udiv 0
3059 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3060 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3061 return R;
3062 if (isa<PHINode>(Op0))
3063 if (Instruction *NV = FoldOpIntoPhi(I))
3064 return NV;
3065 }
3066 }
3067
3068 // 0 / X == 0, we don't need to preserve faults!
3069 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3070 if (LHS->equalsInt(0))
3071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3072
3073 return 0;
3074}
3075
3076Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3078
3079 // Handle the integer div common cases
3080 if (Instruction *Common = commonIDivTransforms(I))
3081 return Common;
3082
3083 // X udiv C^2 -> X >> C
3084 // Check to see if this is an unsigned division with an exact power of 2,
3085 // if so, convert to a right shift.
3086 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3087 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003088 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3090 }
3091
3092 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3093 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3094 if (RHSI->getOpcode() == Instruction::Shl &&
3095 isa<ConstantInt>(RHSI->getOperand(0))) {
3096 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3097 if (C1.isPowerOf2()) {
3098 Value *N = RHSI->getOperand(1);
3099 const Type *NTy = N->getType();
3100 if (uint32_t C2 = C1.logBase2()) {
3101 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003102 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003103 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003104 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003105 }
3106 }
3107 }
3108
3109 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3110 // where C1&C2 are powers of two.
3111 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3112 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3113 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3114 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3115 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3116 // Compute the shift amounts
3117 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3118 // Construct the "on true" case of the select
3119 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003120 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 Op0, TC, SI->getName()+".t");
3122 TSI = InsertNewInstBefore(TSI, I);
3123
3124 // Construct the "on false" case of the select
3125 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003126 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003127 Op0, FC, SI->getName()+".f");
3128 FSI = InsertNewInstBefore(FSI, I);
3129
3130 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003131 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132 }
3133 }
3134 return 0;
3135}
3136
3137Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 // Handle the integer div common cases
3141 if (Instruction *Common = commonIDivTransforms(I))
3142 return Common;
3143
3144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3145 // sdiv X, -1 == -X
3146 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003147 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148
3149 // -X/C -> X/-C
3150 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00003151 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152 }
3153
3154 // If the sign bits of both operands are zero (i.e. we can prove they are
3155 // unsigned inputs), turn this into a udiv.
3156 if (I.getType()->isInteger()) {
3157 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3158 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003159 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003160 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161 }
3162 }
3163
3164 return 0;
3165}
3166
3167Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3168 return commonDivTransforms(I);
3169}
3170
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171/// This function implements the transforms on rem instructions that work
3172/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3173/// is used by the visitors to those instructions.
3174/// @brief Transforms common to all three rem instructions
3175Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3176 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3177
Chris Lattner653ef3c2008-02-19 06:12:18 +00003178 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179 if (Constant *LHS = dyn_cast<Constant>(Op0))
3180 if (LHS->isNullValue())
3181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182
Chris Lattner653ef3c2008-02-19 06:12:18 +00003183 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3184 if (I.getType()->isFPOrFPVector())
3185 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003187 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 if (isa<UndefValue>(Op1))
3189 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3190
3191 // Handle cases involving: rem X, (select Cond, Y, Z)
3192 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3193 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3194 // the same basic block, then we replace the select with Y, and the
3195 // condition of the select with false (if the cond value is in the same
3196 // BB). If the select has uses other than the div, this allows them to be
3197 // simplified also.
3198 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3199 if (ST->isNullValue()) {
3200 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3201 if (CondI && CondI->getParent() == I.getParent())
3202 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3203 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3204 I.setOperand(1, SI->getOperand(2));
3205 else
3206 UpdateValueUsesWith(SI, SI->getOperand(2));
3207 return &I;
3208 }
3209 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3210 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3211 if (ST->isNullValue()) {
3212 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3213 if (CondI && CondI->getParent() == I.getParent())
3214 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3215 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3216 I.setOperand(1, SI->getOperand(1));
3217 else
3218 UpdateValueUsesWith(SI, SI->getOperand(1));
3219 return &I;
3220 }
3221 }
3222
3223 return 0;
3224}
3225
3226/// This function implements the transforms common to both integer remainder
3227/// instructions (urem and srem). It is called by the visitors to those integer
3228/// remainder instructions.
3229/// @brief Common integer remainder transforms
3230Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3231 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3232
3233 if (Instruction *common = commonRemTransforms(I))
3234 return common;
3235
3236 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3237 // X % 0 == undef, we don't need to preserve faults!
3238 if (RHS->equalsInt(0))
3239 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3240
3241 if (RHS->equalsInt(1)) // X % 1 == 0
3242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3243
3244 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3245 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3246 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3247 return R;
3248 } else if (isa<PHINode>(Op0I)) {
3249 if (Instruction *NV = FoldOpIntoPhi(I))
3250 return NV;
3251 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003252
3253 // See if we can fold away this rem instruction.
3254 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3255 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3256 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3257 KnownZero, KnownOne))
3258 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 }
3260 }
3261
3262 return 0;
3263}
3264
3265Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3267
3268 if (Instruction *common = commonIRemTransforms(I))
3269 return common;
3270
3271 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3272 // X urem C^2 -> X and C
3273 // Check to see if this is an unsigned remainder with an exact power of 2,
3274 // if so, convert to a bitwise and.
3275 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3276 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003277 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 }
3279
3280 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3281 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3282 if (RHSI->getOpcode() == Instruction::Shl &&
3283 isa<ConstantInt>(RHSI->getOperand(0))) {
3284 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3285 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003286 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003287 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003288 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 }
3290 }
3291 }
3292
3293 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3294 // where C1&C2 are powers of two.
3295 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3296 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3297 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3298 // STO == 0 and SFO == 0 handled above.
3299 if ((STO->getValue().isPowerOf2()) &&
3300 (SFO->getValue().isPowerOf2())) {
3301 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003302 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003303 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003304 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003305 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 }
3307 }
3308 }
3309
3310 return 0;
3311}
3312
3313Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3315
Dan Gohmandb3dd962007-11-05 23:16:33 +00003316 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317 if (Instruction *common = commonIRemTransforms(I))
3318 return common;
3319
3320 if (Value *RHSNeg = dyn_castNegVal(Op1))
3321 if (!isa<ConstantInt>(RHSNeg) ||
3322 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3323 // X % -Y -> X % Y
3324 AddUsesToWorkList(I);
3325 I.setOperand(1, RHSNeg);
3326 return &I;
3327 }
3328
Dan Gohmandb3dd962007-11-05 23:16:33 +00003329 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003330 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003331 if (I.getType()->isInteger()) {
3332 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3333 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3334 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003335 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003336 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003337 }
3338
3339 return 0;
3340}
3341
3342Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3343 return commonRemTransforms(I);
3344}
3345
3346// isMaxValueMinusOne - return true if this is Max-1
3347static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3348 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3349 if (!isSigned)
3350 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3351 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3352}
3353
3354// isMinValuePlusOne - return true if this is Min+1
3355static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3356 if (!isSigned)
3357 return C->getValue() == 1; // unsigned
3358
3359 // Calculate 1111111111000000000000
3360 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3361 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3362}
3363
3364// isOneBitSet - Return true if there is exactly one bit set in the specified
3365// constant.
3366static bool isOneBitSet(const ConstantInt *CI) {
3367 return CI->getValue().isPowerOf2();
3368}
3369
3370// isHighOnes - Return true if the constant is of the form 1+0+.
3371// This is the same as lowones(~X).
3372static bool isHighOnes(const ConstantInt *CI) {
3373 return (~CI->getValue() + 1).isPowerOf2();
3374}
3375
3376/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3377/// are carefully arranged to allow folding of expressions such as:
3378///
3379/// (A < B) | (A > B) --> (A != B)
3380///
3381/// Note that this is only valid if the first and second predicates have the
3382/// same sign. Is illegal to do: (A u< B) | (A s> B)
3383///
3384/// Three bits are used to represent the condition, as follows:
3385/// 0 A > B
3386/// 1 A == B
3387/// 2 A < B
3388///
3389/// <=> Value Definition
3390/// 000 0 Always false
3391/// 001 1 A > B
3392/// 010 2 A == B
3393/// 011 3 A >= B
3394/// 100 4 A < B
3395/// 101 5 A != B
3396/// 110 6 A <= B
3397/// 111 7 Always true
3398///
3399static unsigned getICmpCode(const ICmpInst *ICI) {
3400 switch (ICI->getPredicate()) {
3401 // False -> 0
3402 case ICmpInst::ICMP_UGT: return 1; // 001
3403 case ICmpInst::ICMP_SGT: return 1; // 001
3404 case ICmpInst::ICMP_EQ: return 2; // 010
3405 case ICmpInst::ICMP_UGE: return 3; // 011
3406 case ICmpInst::ICMP_SGE: return 3; // 011
3407 case ICmpInst::ICMP_ULT: return 4; // 100
3408 case ICmpInst::ICMP_SLT: return 4; // 100
3409 case ICmpInst::ICMP_NE: return 5; // 101
3410 case ICmpInst::ICMP_ULE: return 6; // 110
3411 case ICmpInst::ICMP_SLE: return 6; // 110
3412 // True -> 7
3413 default:
3414 assert(0 && "Invalid ICmp predicate!");
3415 return 0;
3416 }
3417}
3418
3419/// getICmpValue - This is the complement of getICmpCode, which turns an
3420/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003421/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422/// of predicate to use in new icmp instructions.
3423static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3424 switch (code) {
3425 default: assert(0 && "Illegal ICmp code!");
3426 case 0: return ConstantInt::getFalse();
3427 case 1:
3428 if (sign)
3429 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3430 else
3431 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3432 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3433 case 3:
3434 if (sign)
3435 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3436 else
3437 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3438 case 4:
3439 if (sign)
3440 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3441 else
3442 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3443 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3444 case 6:
3445 if (sign)
3446 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3447 else
3448 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3449 case 7: return ConstantInt::getTrue();
3450 }
3451}
3452
3453static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3454 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3455 (ICmpInst::isSignedPredicate(p1) &&
3456 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3457 (ICmpInst::isSignedPredicate(p2) &&
3458 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3459}
3460
3461namespace {
3462// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3463struct FoldICmpLogical {
3464 InstCombiner &IC;
3465 Value *LHS, *RHS;
3466 ICmpInst::Predicate pred;
3467 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3468 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3469 pred(ICI->getPredicate()) {}
3470 bool shouldApply(Value *V) const {
3471 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3472 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003473 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3474 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003475 return false;
3476 }
3477 Instruction *apply(Instruction &Log) const {
3478 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3479 if (ICI->getOperand(0) != LHS) {
3480 assert(ICI->getOperand(1) == LHS);
3481 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3482 }
3483
3484 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3485 unsigned LHSCode = getICmpCode(ICI);
3486 unsigned RHSCode = getICmpCode(RHSICI);
3487 unsigned Code;
3488 switch (Log.getOpcode()) {
3489 case Instruction::And: Code = LHSCode & RHSCode; break;
3490 case Instruction::Or: Code = LHSCode | RHSCode; break;
3491 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3492 default: assert(0 && "Illegal logical opcode!"); return 0;
3493 }
3494
3495 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3496 ICmpInst::isSignedPredicate(ICI->getPredicate());
3497
3498 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3499 if (Instruction *I = dyn_cast<Instruction>(RV))
3500 return I;
3501 // Otherwise, it's a constant boolean value...
3502 return IC.ReplaceInstUsesWith(Log, RV);
3503 }
3504};
3505} // end anonymous namespace
3506
3507// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3508// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3509// guaranteed to be a binary operator.
3510Instruction *InstCombiner::OptAndOp(Instruction *Op,
3511 ConstantInt *OpRHS,
3512 ConstantInt *AndRHS,
3513 BinaryOperator &TheAnd) {
3514 Value *X = Op->getOperand(0);
3515 Constant *Together = 0;
3516 if (!Op->isShift())
3517 Together = And(AndRHS, OpRHS);
3518
3519 switch (Op->getOpcode()) {
3520 case Instruction::Xor:
3521 if (Op->hasOneUse()) {
3522 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003523 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 InsertNewInstBefore(And, TheAnd);
3525 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003526 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527 }
3528 break;
3529 case Instruction::Or:
3530 if (Together == AndRHS) // (X | C) & C --> C
3531 return ReplaceInstUsesWith(TheAnd, AndRHS);
3532
3533 if (Op->hasOneUse() && Together != OpRHS) {
3534 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003535 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 InsertNewInstBefore(Or, TheAnd);
3537 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003539 }
3540 break;
3541 case Instruction::Add:
3542 if (Op->hasOneUse()) {
3543 // Adding a one to a single bit bit-field should be turned into an XOR
3544 // of the bit. First thing to check is to see if this AND is with a
3545 // single bit constant.
3546 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3547
3548 // If there is only one bit set...
3549 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3550 // Ok, at this point, we know that we are masking the result of the
3551 // ADD down to exactly one bit. If the constant we are adding has
3552 // no bits set below this bit, then we can eliminate the ADD.
3553 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3554
3555 // Check to see if any bits below the one bit set in AndRHSV are set.
3556 if ((AddRHS & (AndRHSV-1)) == 0) {
3557 // If not, the only thing that can effect the output of the AND is
3558 // the bit specified by AndRHSV. If that bit is set, the effect of
3559 // the XOR is to toggle the bit. If it is clear, then the ADD has
3560 // no effect.
3561 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3562 TheAnd.setOperand(0, X);
3563 return &TheAnd;
3564 } else {
3565 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003566 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567 InsertNewInstBefore(NewAnd, TheAnd);
3568 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003569 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570 }
3571 }
3572 }
3573 }
3574 break;
3575
3576 case Instruction::Shl: {
3577 // We know that the AND will not produce any of the bits shifted in, so if
3578 // the anded constant includes them, clear them now!
3579 //
3580 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3581 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3582 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3583 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3584
3585 if (CI->getValue() == ShlMask) {
3586 // Masking out bits that the shift already masks
3587 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3588 } else if (CI != AndRHS) { // Reducing bits set in and.
3589 TheAnd.setOperand(1, CI);
3590 return &TheAnd;
3591 }
3592 break;
3593 }
3594 case Instruction::LShr:
3595 {
3596 // We know that the AND will not produce any of the bits shifted in, so if
3597 // the anded constant includes them, clear them now! This only applies to
3598 // unsigned shifts, because a signed shr may bring in set bits!
3599 //
3600 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3601 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3602 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3603 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3604
3605 if (CI->getValue() == ShrMask) {
3606 // Masking out bits that the shift already masks.
3607 return ReplaceInstUsesWith(TheAnd, Op);
3608 } else if (CI != AndRHS) {
3609 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3610 return &TheAnd;
3611 }
3612 break;
3613 }
3614 case Instruction::AShr:
3615 // Signed shr.
3616 // See if this is shifting in some sign extension, then masking it out
3617 // with an and.
3618 if (Op->hasOneUse()) {
3619 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3620 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3621 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3622 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3623 if (C == AndRHS) { // Masking out bits shifted in.
3624 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3625 // Make the argument unsigned.
3626 Value *ShVal = Op->getOperand(0);
3627 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003628 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003630 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003631 }
3632 }
3633 break;
3634 }
3635 return 0;
3636}
3637
3638
3639/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3640/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3641/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3642/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3643/// insert new instructions.
3644Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3645 bool isSigned, bool Inside,
3646 Instruction &IB) {
3647 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3648 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3649 "Lo is not <= Hi in range emission code!");
3650
3651 if (Inside) {
3652 if (Lo == Hi) // Trivially false.
3653 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3654
3655 // V >= Min && V < Hi --> V < Hi
3656 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3657 ICmpInst::Predicate pred = (isSigned ?
3658 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3659 return new ICmpInst(pred, V, Hi);
3660 }
3661
3662 // Emit V-Lo <u Hi-Lo
3663 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003664 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003665 InsertNewInstBefore(Add, IB);
3666 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3667 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3668 }
3669
3670 if (Lo == Hi) // Trivially true.
3671 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3672
3673 // V < Min || V >= Hi -> V > Hi-1
3674 Hi = SubOne(cast<ConstantInt>(Hi));
3675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676 ICmpInst::Predicate pred = (isSigned ?
3677 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3678 return new ICmpInst(pred, V, Hi);
3679 }
3680
3681 // Emit V-Lo >u Hi-1-Lo
3682 // Note that Hi has already had one subtracted from it, above.
3683 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003684 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 InsertNewInstBefore(Add, IB);
3686 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3687 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3688}
3689
3690// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3691// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3692// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3693// not, since all 1s are not contiguous.
3694static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3695 const APInt& V = Val->getValue();
3696 uint32_t BitWidth = Val->getType()->getBitWidth();
3697 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3698
3699 // look for the first zero bit after the run of ones
3700 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3701 // look for the first non-zero bit
3702 ME = V.getActiveBits();
3703 return true;
3704}
3705
3706/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3707/// where isSub determines whether the operator is a sub. If we can fold one of
3708/// the following xforms:
3709///
3710/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3711/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3713///
3714/// return (A +/- B).
3715///
3716Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3717 ConstantInt *Mask, bool isSub,
3718 Instruction &I) {
3719 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3720 if (!LHSI || LHSI->getNumOperands() != 2 ||
3721 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3722
3723 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3724
3725 switch (LHSI->getOpcode()) {
3726 default: return 0;
3727 case Instruction::And:
3728 if (And(N, Mask) == Mask) {
3729 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3730 if ((Mask->getValue().countLeadingZeros() +
3731 Mask->getValue().countPopulation()) ==
3732 Mask->getValue().getBitWidth())
3733 break;
3734
3735 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3736 // part, we don't need any explicit masks to take them out of A. If that
3737 // is all N is, ignore it.
3738 uint32_t MB = 0, ME = 0;
3739 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3740 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3741 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3742 if (MaskedValueIsZero(RHS, Mask))
3743 break;
3744 }
3745 }
3746 return 0;
3747 case Instruction::Or:
3748 case Instruction::Xor:
3749 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3750 if ((Mask->getValue().countLeadingZeros() +
3751 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3752 && And(N, Mask)->isZero())
3753 break;
3754 return 0;
3755 }
3756
3757 Instruction *New;
3758 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003759 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003761 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762 return InsertNewInstBefore(New, I);
3763}
3764
3765Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3766 bool Changed = SimplifyCommutative(I);
3767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3768
3769 if (isa<UndefValue>(Op1)) // X & undef -> 0
3770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3771
3772 // and X, X = X
3773 if (Op0 == Op1)
3774 return ReplaceInstUsesWith(I, Op1);
3775
3776 // See if we can simplify any instructions used by the instruction whose sole
3777 // purpose is to compute bits we don't care about.
3778 if (!isa<VectorType>(I.getType())) {
3779 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3780 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3781 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3782 KnownZero, KnownOne))
3783 return &I;
3784 } else {
3785 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3786 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3787 return ReplaceInstUsesWith(I, I.getOperand(0));
3788 } else if (isa<ConstantAggregateZero>(Op1)) {
3789 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3790 }
3791 }
3792
3793 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3794 const APInt& AndRHSMask = AndRHS->getValue();
3795 APInt NotAndRHS(~AndRHSMask);
3796
3797 // Optimize a variety of ((val OP C1) & C2) combinations...
3798 if (isa<BinaryOperator>(Op0)) {
3799 Instruction *Op0I = cast<Instruction>(Op0);
3800 Value *Op0LHS = Op0I->getOperand(0);
3801 Value *Op0RHS = Op0I->getOperand(1);
3802 switch (Op0I->getOpcode()) {
3803 case Instruction::Xor:
3804 case Instruction::Or:
3805 // If the mask is only needed on one incoming arm, push it up.
3806 if (Op0I->hasOneUse()) {
3807 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3808 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003809 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 Op0RHS->getName()+".masked");
3811 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003812 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003813 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3814 }
3815 if (!isa<Constant>(Op0RHS) &&
3816 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3817 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003818 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003819 Op0LHS->getName()+".masked");
3820 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003821 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003822 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3823 }
3824 }
3825
3826 break;
3827 case Instruction::Add:
3828 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3829 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3830 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3831 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003832 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003833 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003834 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003835 break;
3836
3837 case Instruction::Sub:
3838 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003842 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003843 break;
3844 }
3845
3846 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3847 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3848 return Res;
3849 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3850 // If this is an integer truncation or change from signed-to-unsigned, and
3851 // if the source is an and/or with immediate, transform it. This
3852 // frequently occurs for bitfield accesses.
3853 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3854 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3855 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003856 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003857 if (CastOp->getOpcode() == Instruction::And) {
3858 // Change: and (cast (and X, C1) to T), C2
3859 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3860 // This will fold the two constants together, which may allow
3861 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003862 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003863 CastOp->getOperand(0), I.getType(),
3864 CastOp->getName()+".shrunk");
3865 NewCast = InsertNewInstBefore(NewCast, I);
3866 // trunc_or_bitcast(C1)&C2
3867 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3868 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003869 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003870 } else if (CastOp->getOpcode() == Instruction::Or) {
3871 // Change: and (cast (or X, C1) to T), C2
3872 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3873 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3874 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3875 return ReplaceInstUsesWith(I, AndRHS);
3876 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003878 }
3879 }
3880
3881 // Try to fold constant and into select arguments.
3882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3884 return R;
3885 if (isa<PHINode>(Op0))
3886 if (Instruction *NV = FoldOpIntoPhi(I))
3887 return NV;
3888 }
3889
3890 Value *Op0NotVal = dyn_castNotVal(Op0);
3891 Value *Op1NotVal = dyn_castNotVal(Op1);
3892
3893 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3895
3896 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3897 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003898 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 I.getName()+".demorgan");
3900 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 }
3903
3904 {
3905 Value *A = 0, *B = 0, *C = 0, *D = 0;
3906 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3907 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3908 return ReplaceInstUsesWith(I, Op1);
3909
3910 // (A|B) & ~(A&B) -> A^B
3911 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3912 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003913 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003914 }
3915 }
3916
3917 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3918 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3919 return ReplaceInstUsesWith(I, Op0);
3920
3921 // ~(A&B) & (A|B) -> A^B
3922 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3923 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003924 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925 }
3926 }
3927
3928 if (Op0->hasOneUse() &&
3929 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3930 if (A == Op1) { // (A^B)&A -> A&(A^B)
3931 I.swapOperands(); // Simplify below
3932 std::swap(Op0, Op1);
3933 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3934 cast<BinaryOperator>(Op0)->swapOperands();
3935 I.swapOperands(); // Simplify below
3936 std::swap(Op0, Op1);
3937 }
3938 }
3939 if (Op1->hasOneUse() &&
3940 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3941 if (B == Op0) { // B&(A^B) -> B&(B^A)
3942 cast<BinaryOperator>(Op1)->swapOperands();
3943 std::swap(A, B);
3944 }
3945 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003946 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003947 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003948 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949 }
3950 }
3951 }
3952
3953 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3954 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3955 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3956 return R;
3957
3958 Value *LHSVal, *RHSVal;
3959 ConstantInt *LHSCst, *RHSCst;
3960 ICmpInst::Predicate LHSCC, RHSCC;
3961 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3962 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3963 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3964 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3965 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3966 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3967 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003968 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3969
3970 // Don't try to fold ICMP_SLT + ICMP_ULT.
3971 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3972 ICmpInst::isSignedPredicate(LHSCC) ==
3973 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003975 ICmpInst::Predicate GT;
3976 if (ICmpInst::isSignedPredicate(LHSCC) ||
3977 (ICmpInst::isEquality(LHSCC) &&
3978 ICmpInst::isSignedPredicate(RHSCC)))
3979 GT = ICmpInst::ICMP_SGT;
3980 else
3981 GT = ICmpInst::ICMP_UGT;
3982
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3984 ICmpInst *LHS = cast<ICmpInst>(Op0);
3985 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3986 std::swap(LHS, RHS);
3987 std::swap(LHSCst, RHSCst);
3988 std::swap(LHSCC, RHSCC);
3989 }
3990
3991 // At this point, we know we have have two icmp instructions
3992 // comparing a value against two constants and and'ing the result
3993 // together. Because of the above check, we know that we only have
3994 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3995 // (from the FoldICmpLogical check above), that the two constants
3996 // are not equal and that the larger constant is on the RHS
3997 assert(LHSCst != RHSCst && "Compares not folded above?");
3998
3999 switch (LHSCC) {
4000 default: assert(0 && "Unknown integer condition code!");
4001 case ICmpInst::ICMP_EQ:
4002 switch (RHSCC) {
4003 default: assert(0 && "Unknown integer condition code!");
4004 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4005 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4006 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4007 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4008 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4009 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4010 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4011 return ReplaceInstUsesWith(I, LHS);
4012 }
4013 case ICmpInst::ICMP_NE:
4014 switch (RHSCC) {
4015 default: assert(0 && "Unknown integer condition code!");
4016 case ICmpInst::ICMP_ULT:
4017 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4018 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4019 break; // (X != 13 & X u< 15) -> no change
4020 case ICmpInst::ICMP_SLT:
4021 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4022 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4023 break; // (X != 13 & X s< 15) -> no change
4024 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4025 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4026 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4027 return ReplaceInstUsesWith(I, RHS);
4028 case ICmpInst::ICMP_NE:
4029 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4030 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004031 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004032 LHSVal->getName()+".off");
4033 InsertNewInstBefore(Add, I);
4034 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4035 ConstantInt::get(Add->getType(), 1));
4036 }
4037 break; // (X != 13 & X != 15) -> no change
4038 }
4039 break;
4040 case ICmpInst::ICMP_ULT:
4041 switch (RHSCC) {
4042 default: assert(0 && "Unknown integer condition code!");
4043 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4044 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4045 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4046 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4047 break;
4048 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4049 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4050 return ReplaceInstUsesWith(I, LHS);
4051 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4052 break;
4053 }
4054 break;
4055 case ICmpInst::ICMP_SLT:
4056 switch (RHSCC) {
4057 default: assert(0 && "Unknown integer condition code!");
4058 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4059 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4060 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4061 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4062 break;
4063 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4064 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4065 return ReplaceInstUsesWith(I, LHS);
4066 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4067 break;
4068 }
4069 break;
4070 case ICmpInst::ICMP_UGT:
4071 switch (RHSCC) {
4072 default: assert(0 && "Unknown integer condition code!");
4073 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4074 return ReplaceInstUsesWith(I, LHS);
4075 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4076 return ReplaceInstUsesWith(I, RHS);
4077 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4078 break;
4079 case ICmpInst::ICMP_NE:
4080 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4081 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4082 break; // (X u> 13 & X != 15) -> no change
4083 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4084 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4085 true, I);
4086 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4087 break;
4088 }
4089 break;
4090 case ICmpInst::ICMP_SGT:
4091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004093 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4095 return ReplaceInstUsesWith(I, RHS);
4096 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4097 break;
4098 case ICmpInst::ICMP_NE:
4099 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4100 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4101 break; // (X s> 13 & X != 15) -> no change
4102 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4103 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4104 true, I);
4105 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4106 break;
4107 }
4108 break;
4109 }
4110 }
4111 }
4112
4113 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4114 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4115 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4116 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4117 const Type *SrcTy = Op0C->getOperand(0)->getType();
4118 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4119 // Only do this if the casts both really cause code to be generated.
4120 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4121 I.getType(), TD) &&
4122 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4123 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004124 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004125 Op1C->getOperand(0),
4126 I.getName());
4127 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004128 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004129 }
4130 }
4131
4132 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4133 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4134 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4135 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4136 SI0->getOperand(1) == SI1->getOperand(1) &&
4137 (SI0->hasOneUse() || SI1->hasOneUse())) {
4138 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004139 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140 SI1->getOperand(0),
4141 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004142 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 SI1->getOperand(1));
4144 }
4145 }
4146
Chris Lattner91882432007-10-24 05:38:08 +00004147 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4148 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4149 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4150 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4151 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4152 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4153 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4154 // If either of the constants are nans, then the whole thing returns
4155 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004156 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004157 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4158 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4159 RHS->getOperand(0));
4160 }
4161 }
4162 }
4163
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164 return Changed ? &I : 0;
4165}
4166
4167/// CollectBSwapParts - Look to see if the specified value defines a single byte
4168/// in the result. If it does, and if the specified byte hasn't been filled in
4169/// yet, fill it in and return false.
4170static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4171 Instruction *I = dyn_cast<Instruction>(V);
4172 if (I == 0) return true;
4173
4174 // If this is an or instruction, it is an inner node of the bswap.
4175 if (I->getOpcode() == Instruction::Or)
4176 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4177 CollectBSwapParts(I->getOperand(1), ByteValues);
4178
4179 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4180 // If this is a shift by a constant int, and it is "24", then its operand
4181 // defines a byte. We only handle unsigned types here.
4182 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4183 // Not shifting the entire input by N-1 bytes?
4184 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4185 8*(ByteValues.size()-1))
4186 return true;
4187
4188 unsigned DestNo;
4189 if (I->getOpcode() == Instruction::Shl) {
4190 // X << 24 defines the top byte with the lowest of the input bytes.
4191 DestNo = ByteValues.size()-1;
4192 } else {
4193 // X >>u 24 defines the low byte with the highest of the input bytes.
4194 DestNo = 0;
4195 }
4196
4197 // If the destination byte value is already defined, the values are or'd
4198 // together, which isn't a bswap (unless it's an or of the same bits).
4199 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4200 return true;
4201 ByteValues[DestNo] = I->getOperand(0);
4202 return false;
4203 }
4204
4205 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4206 // don't have this.
4207 Value *Shift = 0, *ShiftLHS = 0;
4208 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4209 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4210 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4211 return true;
4212 Instruction *SI = cast<Instruction>(Shift);
4213
4214 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4215 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4216 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4217 return true;
4218
4219 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4220 unsigned DestByte;
4221 if (AndAmt->getValue().getActiveBits() > 64)
4222 return true;
4223 uint64_t AndAmtVal = AndAmt->getZExtValue();
4224 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4225 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4226 break;
4227 // Unknown mask for bswap.
4228 if (DestByte == ByteValues.size()) return true;
4229
4230 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4231 unsigned SrcByte;
4232 if (SI->getOpcode() == Instruction::Shl)
4233 SrcByte = DestByte - ShiftBytes;
4234 else
4235 SrcByte = DestByte + ShiftBytes;
4236
4237 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4238 if (SrcByte != ByteValues.size()-DestByte-1)
4239 return true;
4240
4241 // If the destination byte value is already defined, the values are or'd
4242 // together, which isn't a bswap (unless it's an or of the same bits).
4243 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4244 return true;
4245 ByteValues[DestByte] = SI->getOperand(0);
4246 return false;
4247}
4248
4249/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4250/// If so, insert the new bswap intrinsic and return it.
4251Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4252 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4253 if (!ITy || ITy->getBitWidth() % 16)
4254 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4255
4256 /// ByteValues - For each byte of the result, we keep track of which value
4257 /// defines each byte.
4258 SmallVector<Value*, 8> ByteValues;
4259 ByteValues.resize(ITy->getBitWidth()/8);
4260
4261 // Try to find all the pieces corresponding to the bswap.
4262 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4263 CollectBSwapParts(I.getOperand(1), ByteValues))
4264 return 0;
4265
4266 // Check to see if all of the bytes come from the same value.
4267 Value *V = ByteValues[0];
4268 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4269
4270 // Check to make sure that all of the bytes come from the same value.
4271 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4272 if (ByteValues[i] != V)
4273 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004274 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004276 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004277 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278}
4279
4280
4281Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4282 bool Changed = SimplifyCommutative(I);
4283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4284
4285 if (isa<UndefValue>(Op1)) // X | undef -> -1
4286 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4287
4288 // or X, X = X
4289 if (Op0 == Op1)
4290 return ReplaceInstUsesWith(I, Op0);
4291
4292 // See if we can simplify any instructions used by the instruction whose sole
4293 // purpose is to compute bits we don't care about.
4294 if (!isa<VectorType>(I.getType())) {
4295 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4296 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4297 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4298 KnownZero, KnownOne))
4299 return &I;
4300 } else if (isa<ConstantAggregateZero>(Op1)) {
4301 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4302 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4303 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4304 return ReplaceInstUsesWith(I, I.getOperand(1));
4305 }
4306
4307
4308
4309 // or X, -1 == -1
4310 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4311 ConstantInt *C1 = 0; Value *X = 0;
4312 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4313 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004314 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 InsertNewInstBefore(Or, I);
4316 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004317 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004318 ConstantInt::get(RHS->getValue() | C1->getValue()));
4319 }
4320
4321 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4322 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004323 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 InsertNewInstBefore(Or, I);
4325 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004326 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004327 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4328 }
4329
4330 // Try to fold constant and into select arguments.
4331 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4332 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4333 return R;
4334 if (isa<PHINode>(Op0))
4335 if (Instruction *NV = FoldOpIntoPhi(I))
4336 return NV;
4337 }
4338
4339 Value *A = 0, *B = 0;
4340 ConstantInt *C1 = 0, *C2 = 0;
4341
4342 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4343 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4344 return ReplaceInstUsesWith(I, Op1);
4345 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4346 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4347 return ReplaceInstUsesWith(I, Op0);
4348
4349 // (A | B) | C and A | (B | C) -> bswap if possible.
4350 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4351 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4352 match(Op1, m_Or(m_Value(), m_Value())) ||
4353 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4354 match(Op1, m_Shift(m_Value(), m_Value())))) {
4355 if (Instruction *BSwap = MatchBSwap(I))
4356 return BSwap;
4357 }
4358
4359 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4360 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4361 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004362 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363 InsertNewInstBefore(NOr, I);
4364 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004365 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004366 }
4367
4368 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4369 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4370 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004371 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004372 InsertNewInstBefore(NOr, I);
4373 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004374 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004375 }
4376
4377 // (A & C)|(B & D)
4378 Value *C = 0, *D = 0;
4379 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4380 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4381 Value *V1 = 0, *V2 = 0, *V3 = 0;
4382 C1 = dyn_cast<ConstantInt>(C);
4383 C2 = dyn_cast<ConstantInt>(D);
4384 if (C1 && C2) { // (A & C1)|(B & C2)
4385 // If we have: ((V + N) & C1) | (V & C2)
4386 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4387 // replace with V+N.
4388 if (C1->getValue() == ~C2->getValue()) {
4389 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4390 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4391 // Add commutes, try both ways.
4392 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4393 return ReplaceInstUsesWith(I, A);
4394 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4395 return ReplaceInstUsesWith(I, A);
4396 }
4397 // Or commutes, try both ways.
4398 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4399 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4400 // Add commutes, try both ways.
4401 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4402 return ReplaceInstUsesWith(I, B);
4403 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4404 return ReplaceInstUsesWith(I, B);
4405 }
4406 }
4407 V1 = 0; V2 = 0; V3 = 0;
4408 }
4409
4410 // Check to see if we have any common things being and'ed. If so, find the
4411 // terms for V1 & (V2|V3).
4412 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4413 if (A == B) // (A & C)|(A & D) == A & (C|D)
4414 V1 = A, V2 = C, V3 = D;
4415 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4416 V1 = A, V2 = B, V3 = C;
4417 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4418 V1 = C, V2 = A, V3 = D;
4419 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4420 V1 = C, V2 = A, V3 = B;
4421
4422 if (V1) {
4423 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004424 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4425 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004427 }
4428 }
4429
4430 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4431 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4432 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4433 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4434 SI0->getOperand(1) == SI1->getOperand(1) &&
4435 (SI0->hasOneUse() || SI1->hasOneUse())) {
4436 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004437 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004438 SI1->getOperand(0),
4439 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004440 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004441 SI1->getOperand(1));
4442 }
4443 }
4444
4445 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4446 if (A == Op1) // ~A | A == -1
4447 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4448 } else {
4449 A = 0;
4450 }
4451 // Note, A is still live here!
4452 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4453 if (Op0 == B)
4454 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4455
4456 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4457 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004458 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004459 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004460 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004461 }
4462 }
4463
4464 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4465 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4466 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4467 return R;
4468
4469 Value *LHSVal, *RHSVal;
4470 ConstantInt *LHSCst, *RHSCst;
4471 ICmpInst::Predicate LHSCC, RHSCC;
4472 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4473 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4474 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4475 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4476 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4477 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4478 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4479 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4480 // We can't fold (ugt x, C) | (sgt x, C2).
4481 PredicatesFoldable(LHSCC, RHSCC)) {
4482 // Ensure that the larger constant is on the RHS.
4483 ICmpInst *LHS = cast<ICmpInst>(Op0);
4484 bool NeedsSwap;
4485 if (ICmpInst::isSignedPredicate(LHSCC))
4486 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4487 else
4488 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4489
4490 if (NeedsSwap) {
4491 std::swap(LHS, RHS);
4492 std::swap(LHSCst, RHSCst);
4493 std::swap(LHSCC, RHSCC);
4494 }
4495
4496 // At this point, we know we have have two icmp instructions
4497 // comparing a value against two constants and or'ing the result
4498 // together. Because of the above check, we know that we only have
4499 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4500 // FoldICmpLogical check above), that the two constants are not
4501 // equal.
4502 assert(LHSCst != RHSCst && "Compares not folded above?");
4503
4504 switch (LHSCC) {
4505 default: assert(0 && "Unknown integer condition code!");
4506 case ICmpInst::ICMP_EQ:
4507 switch (RHSCC) {
4508 default: assert(0 && "Unknown integer condition code!");
4509 case ICmpInst::ICMP_EQ:
4510 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4511 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004512 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004513 LHSVal->getName()+".off");
4514 InsertNewInstBefore(Add, I);
4515 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4516 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4517 }
4518 break; // (X == 13 | X == 15) -> no change
4519 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4520 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4521 break;
4522 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4523 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4524 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4525 return ReplaceInstUsesWith(I, RHS);
4526 }
4527 break;
4528 case ICmpInst::ICMP_NE:
4529 switch (RHSCC) {
4530 default: assert(0 && "Unknown integer condition code!");
4531 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4532 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4533 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4534 return ReplaceInstUsesWith(I, LHS);
4535 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4536 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4537 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4538 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4539 }
4540 break;
4541 case ICmpInst::ICMP_ULT:
4542 switch (RHSCC) {
4543 default: assert(0 && "Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4545 break;
4546 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(false))
4550 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004551 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4552 false, I);
4553 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4554 break;
4555 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4556 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4557 return ReplaceInstUsesWith(I, RHS);
4558 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4559 break;
4560 }
4561 break;
4562 case ICmpInst::ICMP_SLT:
4563 switch (RHSCC) {
4564 default: assert(0 && "Unknown integer condition code!");
4565 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4566 break;
4567 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004568 // If RHSCst is [us]MAXINT, it is always false. Not handling
4569 // this can cause overflow.
4570 if (RHSCst->isMaxValue(true))
4571 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004572 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4573 false, I);
4574 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4578 return ReplaceInstUsesWith(I, RHS);
4579 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4580 break;
4581 }
4582 break;
4583 case ICmpInst::ICMP_UGT:
4584 switch (RHSCC) {
4585 default: assert(0 && "Unknown integer condition code!");
4586 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4587 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4588 return ReplaceInstUsesWith(I, LHS);
4589 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4590 break;
4591 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4592 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4593 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4594 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4595 break;
4596 }
4597 break;
4598 case ICmpInst::ICMP_SGT:
4599 switch (RHSCC) {
4600 default: assert(0 && "Unknown integer condition code!");
4601 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4602 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4603 return ReplaceInstUsesWith(I, LHS);
4604 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4605 break;
4606 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4607 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4608 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4609 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4610 break;
4611 }
4612 break;
4613 }
4614 }
4615 }
4616
4617 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004618 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004619 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4620 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004621 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4622 !isa<ICmpInst>(Op1C->getOperand(0))) {
4623 const Type *SrcTy = Op0C->getOperand(0)->getType();
4624 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4625 // Only do this if the casts both really cause code to be
4626 // generated.
4627 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4628 I.getType(), TD) &&
4629 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4630 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004631 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004632 Op1C->getOperand(0),
4633 I.getName());
4634 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004635 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004636 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004637 }
4638 }
Chris Lattner91882432007-10-24 05:38:08 +00004639 }
4640
4641
4642 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4643 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4644 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4645 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004646 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4647 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004648 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4649 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4650 // If either of the constants are nans, then the whole thing returns
4651 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004652 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004653 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4654
4655 // Otherwise, no need to compare the two constants, compare the
4656 // rest.
4657 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4658 RHS->getOperand(0));
4659 }
4660 }
4661 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662
4663 return Changed ? &I : 0;
4664}
4665
Dan Gohman089efff2008-05-13 00:00:25 +00004666namespace {
4667
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004668// XorSelf - Implements: X ^ X --> 0
4669struct XorSelf {
4670 Value *RHS;
4671 XorSelf(Value *rhs) : RHS(rhs) {}
4672 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4673 Instruction *apply(BinaryOperator &Xor) const {
4674 return &Xor;
4675 }
4676};
4677
Dan Gohman089efff2008-05-13 00:00:25 +00004678}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004679
4680Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4681 bool Changed = SimplifyCommutative(I);
4682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4683
Evan Chenge5cd8032008-03-25 20:07:13 +00004684 if (isa<UndefValue>(Op1)) {
4685 if (isa<UndefValue>(Op0))
4686 // Handle undef ^ undef -> 0 special case. This is a common
4687 // idiom (misuse).
4688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004691
4692 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4693 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004694 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004695 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4696 }
4697
4698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
4700 if (!isa<VectorType>(I.getType())) {
4701 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4702 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4703 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4704 KnownZero, KnownOne))
4705 return &I;
4706 } else if (isa<ConstantAggregateZero>(Op1)) {
4707 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4708 }
4709
4710 // Is this a ~ operation?
4711 if (Value *NotOp = dyn_castNotVal(&I)) {
4712 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4713 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4714 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4715 if (Op0I->getOpcode() == Instruction::And ||
4716 Op0I->getOpcode() == Instruction::Or) {
4717 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4718 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4719 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004720 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004721 Op0I->getOperand(1)->getName()+".not");
4722 InsertNewInstBefore(NotY, I);
4723 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004724 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004725 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004726 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004727 }
4728 }
4729 }
4730 }
4731
4732
4733 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004734 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4735 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4736 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004737 return new ICmpInst(ICI->getInversePredicate(),
4738 ICI->getOperand(0), ICI->getOperand(1));
4739
Nick Lewycky1405e922007-08-06 20:04:16 +00004740 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4741 return new FCmpInst(FCI->getInversePredicate(),
4742 FCI->getOperand(0), FCI->getOperand(1));
4743 }
4744
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004745 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4746 // ~(c-X) == X-c-1 == X+(-c-1)
4747 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4748 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4749 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4750 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4751 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004752 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004753 }
4754
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004755 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004756 if (Op0I->getOpcode() == Instruction::Add) {
4757 // ~(X-c) --> (-c-1)-X
4758 if (RHS->isAllOnesValue()) {
4759 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004760 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004761 ConstantExpr::getSub(NegOp0CI,
4762 ConstantInt::get(I.getType(), 1)),
4763 Op0I->getOperand(0));
4764 } else if (RHS->getValue().isSignBit()) {
4765 // (X + C) ^ signbit -> (X + C + signbit)
4766 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004767 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004768
4769 }
4770 } else if (Op0I->getOpcode() == Instruction::Or) {
4771 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4772 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4773 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4774 // Anything in both C1 and C2 is known to be zero, remove it from
4775 // NewRHS.
4776 Constant *CommonBits = And(Op0CI, RHS);
4777 NewRHS = ConstantExpr::getAnd(NewRHS,
4778 ConstantExpr::getNot(CommonBits));
4779 AddToWorkList(Op0I);
4780 I.setOperand(0, Op0I->getOperand(0));
4781 I.setOperand(1, NewRHS);
4782 return &I;
4783 }
4784 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004786 }
4787
4788 // Try to fold constant and into select arguments.
4789 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4791 return R;
4792 if (isa<PHINode>(Op0))
4793 if (Instruction *NV = FoldOpIntoPhi(I))
4794 return NV;
4795 }
4796
4797 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4798 if (X == Op1)
4799 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4800
4801 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4802 if (X == Op0)
4803 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4804
4805
4806 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4807 if (Op1I) {
4808 Value *A, *B;
4809 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4810 if (A == Op0) { // B^(B|A) == (A|B)^B
4811 Op1I->swapOperands();
4812 I.swapOperands();
4813 std::swap(Op0, Op1);
4814 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4815 I.swapOperands(); // Simplified below.
4816 std::swap(Op0, Op1);
4817 }
4818 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4819 if (Op0 == A) // A^(A^B) == B
4820 return ReplaceInstUsesWith(I, B);
4821 else if (Op0 == B) // A^(B^A) == B
4822 return ReplaceInstUsesWith(I, A);
4823 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4824 if (A == Op0) { // A^(A&B) -> A^(B&A)
4825 Op1I->swapOperands();
4826 std::swap(A, B);
4827 }
4828 if (B == Op0) { // A^(B&A) -> (B&A)^A
4829 I.swapOperands(); // Simplified below.
4830 std::swap(Op0, Op1);
4831 }
4832 }
4833 }
4834
4835 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4836 if (Op0I) {
4837 Value *A, *B;
4838 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4839 if (A == Op1) // (B|A)^B == (A|B)^B
4840 std::swap(A, B);
4841 if (B == Op1) { // (A|B)^B == A & ~B
4842 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004843 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4844 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004845 }
4846 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4847 if (Op1 == A) // (A^B)^A == B
4848 return ReplaceInstUsesWith(I, B);
4849 else if (Op1 == B) // (B^A)^A == B
4850 return ReplaceInstUsesWith(I, A);
4851 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4852 if (A == Op1) // (A&B)^A -> (B&A)^A
4853 std::swap(A, B);
4854 if (B == Op1 && // (B&A)^A == ~B & A
4855 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4856 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004857 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4858 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004859 }
4860 }
4861 }
4862
4863 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4864 if (Op0I && Op1I && Op0I->isShift() &&
4865 Op0I->getOpcode() == Op1I->getOpcode() &&
4866 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4867 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4868 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004869 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004870 Op1I->getOperand(0),
4871 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004872 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004873 Op1I->getOperand(1));
4874 }
4875
4876 if (Op0I && Op1I) {
4877 Value *A, *B, *C, *D;
4878 // (A & B)^(A | B) -> A ^ B
4879 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4880 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4881 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004882 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004883 }
4884 // (A | B)^(A & B) -> A ^ B
4885 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4886 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4887 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004888 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004889 }
4890
4891 // (A & B)^(C & D)
4892 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4893 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4894 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4895 // (X & Y)^(X & Y) -> (Y^Z) & X
4896 Value *X = 0, *Y = 0, *Z = 0;
4897 if (A == C)
4898 X = A, Y = B, Z = D;
4899 else if (A == D)
4900 X = A, Y = B, Z = C;
4901 else if (B == C)
4902 X = B, Y = A, Z = D;
4903 else if (B == D)
4904 X = B, Y = A, Z = C;
4905
4906 if (X) {
4907 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004908 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4909 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004910 }
4911 }
4912 }
4913
4914 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4915 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4916 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4917 return R;
4918
4919 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004920 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004921 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4922 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4923 const Type *SrcTy = Op0C->getOperand(0)->getType();
4924 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4925 // Only do this if the casts both really cause code to be generated.
4926 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4927 I.getType(), TD) &&
4928 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4929 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004930 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004931 Op1C->getOperand(0),
4932 I.getName());
4933 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004934 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004935 }
4936 }
Chris Lattner91882432007-10-24 05:38:08 +00004937 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004938 return Changed ? &I : 0;
4939}
4940
4941/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4942/// overflowed for this type.
4943static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4944 ConstantInt *In2, bool IsSigned = false) {
4945 Result = cast<ConstantInt>(Add(In1, In2));
4946
4947 if (IsSigned)
4948 if (In2->getValue().isNegative())
4949 return Result->getValue().sgt(In1->getValue());
4950 else
4951 return Result->getValue().slt(In1->getValue());
4952 else
4953 return Result->getValue().ult(In1->getValue());
4954}
4955
4956/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4957/// code necessary to compute the offset from the base pointer (without adding
4958/// in the base pointer). Return the result as a signed integer of intptr size.
4959static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4960 TargetData &TD = IC.getTargetData();
4961 gep_type_iterator GTI = gep_type_begin(GEP);
4962 const Type *IntPtrTy = TD.getIntPtrType();
4963 Value *Result = Constant::getNullValue(IntPtrTy);
4964
4965 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004966 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4968
4969 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4970 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004971 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4973 if (OpC->isZero()) continue;
4974
4975 // Handle a struct index, which adds its field offset to the pointer.
4976 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4977 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4978
4979 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4980 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4981 else
4982 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004983 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004984 ConstantInt::get(IntPtrTy, Size),
4985 GEP->getName()+".offs"), I);
4986 continue;
4987 }
4988
4989 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4990 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4991 Scale = ConstantExpr::getMul(OC, Scale);
4992 if (Constant *RC = dyn_cast<Constant>(Result))
4993 Result = ConstantExpr::getAdd(RC, Scale);
4994 else {
4995 // Emit an add instruction.
4996 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004997 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998 GEP->getName()+".offs"), I);
4999 }
5000 continue;
5001 }
5002 // Convert to correct type.
5003 if (Op->getType() != IntPtrTy) {
5004 if (Constant *OpC = dyn_cast<Constant>(Op))
5005 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5006 else
5007 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5008 Op->getName()+".c"), I);
5009 }
5010 if (Size != 1) {
5011 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5012 if (Constant *OpC = dyn_cast<Constant>(Op))
5013 Op = ConstantExpr::getMul(OpC, Scale);
5014 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005015 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005016 GEP->getName()+".idx"), I);
5017 }
5018
5019 // Emit an add instruction.
5020 if (isa<Constant>(Op) && isa<Constant>(Result))
5021 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5022 cast<Constant>(Result));
5023 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005024 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005025 GEP->getName()+".offs"), I);
5026 }
5027 return Result;
5028}
5029
Chris Lattnereba75862008-04-22 02:53:33 +00005030
5031/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5032/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5033/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5034/// complex, and scales are involved. The above expression would also be legal
5035/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5036/// later form is less amenable to optimization though, and we are allowed to
5037/// generate the first by knowing that pointer arithmetic doesn't overflow.
5038///
5039/// If we can't emit an optimized form for this expression, this returns null.
5040///
5041static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5042 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005043 TargetData &TD = IC.getTargetData();
5044 gep_type_iterator GTI = gep_type_begin(GEP);
5045
5046 // Check to see if this gep only has a single variable index. If so, and if
5047 // any constant indices are a multiple of its scale, then we can compute this
5048 // in terms of the scale of the variable index. For example, if the GEP
5049 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5050 // because the expression will cross zero at the same point.
5051 unsigned i, e = GEP->getNumOperands();
5052 int64_t Offset = 0;
5053 for (i = 1; i != e; ++i, ++GTI) {
5054 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5055 // Compute the aggregate offset of constant indices.
5056 if (CI->isZero()) continue;
5057
5058 // Handle a struct index, which adds its field offset to the pointer.
5059 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5060 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5061 } else {
5062 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5063 Offset += Size*CI->getSExtValue();
5064 }
5065 } else {
5066 // Found our variable index.
5067 break;
5068 }
5069 }
5070
5071 // If there are no variable indices, we must have a constant offset, just
5072 // evaluate it the general way.
5073 if (i == e) return 0;
5074
5075 Value *VariableIdx = GEP->getOperand(i);
5076 // Determine the scale factor of the variable element. For example, this is
5077 // 4 if the variable index is into an array of i32.
5078 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5079
5080 // Verify that there are no other variable indices. If so, emit the hard way.
5081 for (++i, ++GTI; i != e; ++i, ++GTI) {
5082 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5083 if (!CI) return 0;
5084
5085 // Compute the aggregate offset of constant indices.
5086 if (CI->isZero()) continue;
5087
5088 // Handle a struct index, which adds its field offset to the pointer.
5089 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5090 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5091 } else {
5092 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5093 Offset += Size*CI->getSExtValue();
5094 }
5095 }
5096
5097 // Okay, we know we have a single variable index, which must be a
5098 // pointer/array/vector index. If there is no offset, life is simple, return
5099 // the index.
5100 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5101 if (Offset == 0) {
5102 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5103 // we don't need to bother extending: the extension won't affect where the
5104 // computation crosses zero.
5105 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5106 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5107 VariableIdx->getNameStart(), &I);
5108 return VariableIdx;
5109 }
5110
5111 // Otherwise, there is an index. The computation we will do will be modulo
5112 // the pointer size, so get it.
5113 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5114
5115 Offset &= PtrSizeMask;
5116 VariableScale &= PtrSizeMask;
5117
5118 // To do this transformation, any constant index must be a multiple of the
5119 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5120 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5121 // multiple of the variable scale.
5122 int64_t NewOffs = Offset / (int64_t)VariableScale;
5123 if (Offset != NewOffs*(int64_t)VariableScale)
5124 return 0;
5125
5126 // Okay, we can do this evaluation. Start by converting the index to intptr.
5127 const Type *IntPtrTy = TD.getIntPtrType();
5128 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005129 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005130 true /*SExt*/,
5131 VariableIdx->getNameStart(), &I);
5132 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005134}
5135
5136
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005137/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5138/// else. At this point we know that the GEP is on the LHS of the comparison.
5139Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5140 ICmpInst::Predicate Cond,
5141 Instruction &I) {
5142 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5143
Chris Lattnereba75862008-04-22 02:53:33 +00005144 // Look through bitcasts.
5145 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5146 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005147
5148 Value *PtrBase = GEPLHS->getOperand(0);
5149 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005150 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005151 // This transformation (ignoring the base and scales) is valid because we
5152 // know pointers can't overflow. See if we can output an optimized form.
5153 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5154
5155 // If not, synthesize the offset the hard way.
5156 if (Offset == 0)
5157 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005158 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5159 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005160 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5161 // If the base pointers are different, but the indices are the same, just
5162 // compare the base pointer.
5163 if (PtrBase != GEPRHS->getOperand(0)) {
5164 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5165 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5166 GEPRHS->getOperand(0)->getType();
5167 if (IndicesTheSame)
5168 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5169 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5170 IndicesTheSame = false;
5171 break;
5172 }
5173
5174 // If all indices are the same, just compare the base pointers.
5175 if (IndicesTheSame)
5176 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5177 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5178
5179 // Otherwise, the base pointers are different and the indices are
5180 // different, bail out.
5181 return 0;
5182 }
5183
5184 // If one of the GEPs has all zero indices, recurse.
5185 bool AllZeros = true;
5186 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5187 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5188 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5189 AllZeros = false;
5190 break;
5191 }
5192 if (AllZeros)
5193 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5194 ICmpInst::getSwappedPredicate(Cond), I);
5195
5196 // If the other GEP has all zero indices, recurse.
5197 AllZeros = true;
5198 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5199 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5200 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5201 AllZeros = false;
5202 break;
5203 }
5204 if (AllZeros)
5205 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5206
5207 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5208 // If the GEPs only differ by one index, compare it.
5209 unsigned NumDifferences = 0; // Keep track of # differences.
5210 unsigned DiffOperand = 0; // The operand that differs.
5211 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5212 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5213 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5214 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5215 // Irreconcilable differences.
5216 NumDifferences = 2;
5217 break;
5218 } else {
5219 if (NumDifferences++) break;
5220 DiffOperand = i;
5221 }
5222 }
5223
5224 if (NumDifferences == 0) // SAME GEP?
5225 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005226 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005227 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005228
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005229 else if (NumDifferences == 1) {
5230 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5231 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5232 // Make sure we do a signed comparison here.
5233 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5234 }
5235 }
5236
5237 // Only lower this if the icmp is the only user of the GEP or if we expect
5238 // the result to fold to a constant!
5239 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5240 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5241 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5242 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5243 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5244 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5245 }
5246 }
5247 return 0;
5248}
5249
Chris Lattnere6b62d92008-05-19 20:18:56 +00005250/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5251///
5252Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5253 Instruction *LHSI,
5254 Constant *RHSC) {
5255 if (!isa<ConstantFP>(RHSC)) return 0;
5256 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5257
5258 // Get the width of the mantissa. We don't want to hack on conversions that
5259 // might lose information from the integer, e.g. "i64 -> float"
5260 int MantissaWidth = GetFPMantissaWidth(LHSI->getType());
5261 if (MantissaWidth == -1) return 0; // Unknown.
5262
5263 // Check to see that the input is converted from an integer type that is small
5264 // enough that preserves all bits. TODO: check here for "known" sign bits.
5265 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5266 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5267
5268 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5269 if (isa<UIToFPInst>(LHSI))
5270 ++InputSize;
5271
5272 // If the conversion would lose info, don't hack on this.
5273 if ((int)InputSize > MantissaWidth)
5274 return 0;
5275
5276 // Otherwise, we can potentially simplify the comparison. We know that it
5277 // will always come through as an integer value and we know the constant is
5278 // not a NAN (it would have been previously simplified).
5279 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5280
5281 ICmpInst::Predicate Pred;
5282 switch (I.getPredicate()) {
5283 default: assert(0 && "Unexpected predicate!");
5284 case FCmpInst::FCMP_UEQ:
5285 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5286 case FCmpInst::FCMP_UGT:
5287 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5288 case FCmpInst::FCMP_UGE:
5289 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5290 case FCmpInst::FCMP_ULT:
5291 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5292 case FCmpInst::FCMP_ULE:
5293 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5294 case FCmpInst::FCMP_UNE:
5295 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5296 case FCmpInst::FCMP_ORD:
5297 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5298 case FCmpInst::FCMP_UNO:
5299 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5300 }
5301
5302 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5303
5304 // Now we know that the APFloat is a normal number, zero or inf.
5305
5306 // See if the FP constant is top large for the integer. For example,
5307 // comparing an i8 to 300.0.
5308 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5309
5310 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5311 // and large values.
5312 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5313 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5314 APFloat::rmNearestTiesToEven);
5315 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5316 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5317 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5318 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5319 }
5320
5321 // See if the RHS value is < SignedMin.
5322 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5323 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5324 APFloat::rmNearestTiesToEven);
5325 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5326 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5327 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5328 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5329 }
5330
5331 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5332 // it may still be fractional. See if it is fractional by casting the FP
5333 // value to the integer value and back, checking for equality. Don't do this
5334 // for zero, because -0.0 is not fractional.
5335 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5336 if (!RHS.isZero() &&
5337 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5338 // If we had a comparison against a fractional value, we have to adjust
5339 // the compare predicate and sometimes the value. RHSC is rounded towards
5340 // zero at this point.
5341 switch (Pred) {
5342 default: assert(0 && "Unexpected integer comparison!");
5343 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5344 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5345 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5346 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5347 case ICmpInst::ICMP_SLE:
5348 // (float)int <= 4.4 --> int <= 4
5349 // (float)int <= -4.4 --> int < -4
5350 if (RHS.isNegative())
5351 Pred = ICmpInst::ICMP_SLT;
5352 break;
5353 case ICmpInst::ICMP_SLT:
5354 // (float)int < -4.4 --> int < -4
5355 // (float)int < 4.4 --> int <= 4
5356 if (!RHS.isNegative())
5357 Pred = ICmpInst::ICMP_SLE;
5358 break;
5359 case ICmpInst::ICMP_SGT:
5360 // (float)int > 4.4 --> int > 4
5361 // (float)int > -4.4 --> int >= -4
5362 if (RHS.isNegative())
5363 Pred = ICmpInst::ICMP_SGE;
5364 break;
5365 case ICmpInst::ICMP_SGE:
5366 // (float)int >= -4.4 --> int >= -4
5367 // (float)int >= 4.4 --> int > 4
5368 if (!RHS.isNegative())
5369 Pred = ICmpInst::ICMP_SGT;
5370 break;
5371 }
5372 }
5373
5374 // Lower this FP comparison into an appropriate integer version of the
5375 // comparison.
5376 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5377}
5378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005379Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5380 bool Changed = SimplifyCompare(I);
5381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5382
5383 // Fold trivial predicates.
5384 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5385 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5386 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5387 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5388
5389 // Simplify 'fcmp pred X, X'
5390 if (Op0 == Op1) {
5391 switch (I.getPredicate()) {
5392 default: assert(0 && "Unknown predicate!");
5393 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5394 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5395 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5396 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5397 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5398 case FCmpInst::FCMP_OLT: // True if ordered and less than
5399 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5400 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5401
5402 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5403 case FCmpInst::FCMP_ULT: // True if unordered or less than
5404 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5405 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5406 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5407 I.setPredicate(FCmpInst::FCMP_UNO);
5408 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5409 return &I;
5410
5411 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5412 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5413 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5414 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5415 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5416 I.setPredicate(FCmpInst::FCMP_ORD);
5417 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5418 return &I;
5419 }
5420 }
5421
5422 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5423 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5424
5425 // Handle fcmp with constant RHS
5426 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005427 // If the constant is a nan, see if we can fold the comparison based on it.
5428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5429 if (CFP->getValueAPF().isNaN()) {
5430 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5431 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5432 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5433 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5434 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5435 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5436 }
5437 }
5438
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005439 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5440 switch (LHSI->getOpcode()) {
5441 case Instruction::PHI:
5442 if (Instruction *NV = FoldOpIntoPhi(I))
5443 return NV;
5444 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005445 case Instruction::SIToFP:
5446 case Instruction::UIToFP:
5447 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5448 return NV;
5449 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005450 case Instruction::Select:
5451 // If either operand of the select is a constant, we can fold the
5452 // comparison into the select arms, which will cause one to be
5453 // constant folded and the select turned into a bitwise or.
5454 Value *Op1 = 0, *Op2 = 0;
5455 if (LHSI->hasOneUse()) {
5456 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5457 // Fold the known value into the constant operand.
5458 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5459 // Insert a new FCmp of the other select operand.
5460 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5461 LHSI->getOperand(2), RHSC,
5462 I.getName()), I);
5463 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5464 // Fold the known value into the constant operand.
5465 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5466 // Insert a new FCmp of the other select operand.
5467 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5468 LHSI->getOperand(1), RHSC,
5469 I.getName()), I);
5470 }
5471 }
5472
5473 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005474 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005475 break;
5476 }
5477 }
5478
5479 return Changed ? &I : 0;
5480}
5481
5482Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5483 bool Changed = SimplifyCompare(I);
5484 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5485 const Type *Ty = Op0->getType();
5486
5487 // icmp X, X
5488 if (Op0 == Op1)
5489 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005490 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005491
5492 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5493 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005494
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005495 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5496 // addresses never equal each other! We already know that Op0 != Op1.
5497 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5498 isa<ConstantPointerNull>(Op0)) &&
5499 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5500 isa<ConstantPointerNull>(Op1)))
5501 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005502 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005503
5504 // icmp's with boolean values can always be turned into bitwise operations
5505 if (Ty == Type::Int1Ty) {
5506 switch (I.getPredicate()) {
5507 default: assert(0 && "Invalid icmp instruction!");
5508 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005509 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005510 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005511 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005512 }
5513 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005514 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515
5516 case ICmpInst::ICMP_UGT:
5517 case ICmpInst::ICMP_SGT:
5518 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5519 // FALL THROUGH
5520 case ICmpInst::ICMP_ULT:
5521 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005522 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005523 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005524 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005525 }
5526 case ICmpInst::ICMP_UGE:
5527 case ICmpInst::ICMP_SGE:
5528 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5529 // FALL THROUGH
5530 case ICmpInst::ICMP_ULE:
5531 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005532 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005533 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005534 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005535 }
5536 }
5537 }
5538
5539 // See if we are doing a comparison between a constant and an instruction that
5540 // can be folded into the comparison.
5541 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005542 Value *A, *B;
5543
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005544 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5545 if (I.isEquality() && CI->isNullValue() &&
5546 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5547 // (icmp cond A B) if cond is equality
5548 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005549 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005551 switch (I.getPredicate()) {
5552 default: break;
5553 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5554 if (CI->isMinValue(false))
5555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5556 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5557 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5558 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5559 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5560 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5561 if (CI->isMinValue(true))
5562 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5563 ConstantInt::getAllOnesValue(Op0->getType()));
5564
5565 break;
5566
5567 case ICmpInst::ICMP_SLT:
5568 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5569 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5570 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5571 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5572 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5573 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5574 break;
5575
5576 case ICmpInst::ICMP_UGT:
5577 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5579 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5580 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5581 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5582 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5583
5584 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5585 if (CI->isMaxValue(true))
5586 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5587 ConstantInt::getNullValue(Op0->getType()));
5588 break;
5589
5590 case ICmpInst::ICMP_SGT:
5591 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5592 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5593 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5594 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5595 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5596 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5597 break;
5598
5599 case ICmpInst::ICMP_ULE:
5600 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5601 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5602 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5603 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5604 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5605 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5606 break;
5607
5608 case ICmpInst::ICMP_SLE:
5609 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5610 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5611 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5612 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5613 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5614 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5615 break;
5616
5617 case ICmpInst::ICMP_UGE:
5618 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5619 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5620 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5621 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5622 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5623 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5624 break;
5625
5626 case ICmpInst::ICMP_SGE:
5627 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5628 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5629 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5630 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5631 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5632 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5633 break;
5634 }
5635
5636 // If we still have a icmp le or icmp ge instruction, turn it into the
5637 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5638 // already been handled above, this requires little checking.
5639 //
5640 switch (I.getPredicate()) {
5641 default: break;
5642 case ICmpInst::ICMP_ULE:
5643 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5644 case ICmpInst::ICMP_SLE:
5645 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5646 case ICmpInst::ICMP_UGE:
5647 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5648 case ICmpInst::ICMP_SGE:
5649 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5650 }
5651
5652 // See if we can fold the comparison based on bits known to be zero or one
5653 // in the input. If this comparison is a normal comparison, it demands all
5654 // bits, if it is a sign bit comparison, it only demands the sign bit.
5655
5656 bool UnusedBit;
5657 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5658
5659 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5660 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5661 if (SimplifyDemandedBits(Op0,
5662 isSignBit ? APInt::getSignBit(BitWidth)
5663 : APInt::getAllOnesValue(BitWidth),
5664 KnownZero, KnownOne, 0))
5665 return &I;
5666
5667 // Given the known and unknown bits, compute a range that the LHS could be
5668 // in.
5669 if ((KnownOne | KnownZero) != 0) {
5670 // Compute the Min, Max and RHS values based on the known bits. For the
5671 // EQ and NE we use unsigned values.
5672 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5673 const APInt& RHSVal = CI->getValue();
5674 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5675 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5676 Max);
5677 } else {
5678 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5679 Max);
5680 }
5681 switch (I.getPredicate()) { // LE/GE have been folded already.
5682 default: assert(0 && "Unknown icmp opcode!");
5683 case ICmpInst::ICMP_EQ:
5684 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5685 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5686 break;
5687 case ICmpInst::ICMP_NE:
5688 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5689 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5690 break;
5691 case ICmpInst::ICMP_ULT:
5692 if (Max.ult(RHSVal))
5693 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5694 if (Min.uge(RHSVal))
5695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5696 break;
5697 case ICmpInst::ICMP_UGT:
5698 if (Min.ugt(RHSVal))
5699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5700 if (Max.ule(RHSVal))
5701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5702 break;
5703 case ICmpInst::ICMP_SLT:
5704 if (Max.slt(RHSVal))
5705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5706 if (Min.sgt(RHSVal))
5707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5708 break;
5709 case ICmpInst::ICMP_SGT:
5710 if (Min.sgt(RHSVal))
5711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5712 if (Max.sle(RHSVal))
5713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5714 break;
5715 }
5716 }
5717
5718 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5719 // instruction, see if that instruction also has constants so that the
5720 // instruction can be folded into the icmp
5721 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5722 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5723 return Res;
5724 }
5725
5726 // Handle icmp with constant (but not simple integer constant) RHS
5727 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5728 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5729 switch (LHSI->getOpcode()) {
5730 case Instruction::GetElementPtr:
5731 if (RHSC->isNullValue()) {
5732 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5733 bool isAllZeros = true;
5734 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5735 if (!isa<Constant>(LHSI->getOperand(i)) ||
5736 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5737 isAllZeros = false;
5738 break;
5739 }
5740 if (isAllZeros)
5741 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5742 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5743 }
5744 break;
5745
5746 case Instruction::PHI:
5747 if (Instruction *NV = FoldOpIntoPhi(I))
5748 return NV;
5749 break;
5750 case Instruction::Select: {
5751 // If either operand of the select is a constant, we can fold the
5752 // comparison into the select arms, which will cause one to be
5753 // constant folded and the select turned into a bitwise or.
5754 Value *Op1 = 0, *Op2 = 0;
5755 if (LHSI->hasOneUse()) {
5756 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5757 // Fold the known value into the constant operand.
5758 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5759 // Insert a new ICmp of the other select operand.
5760 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5761 LHSI->getOperand(2), RHSC,
5762 I.getName()), I);
5763 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5764 // Fold the known value into the constant operand.
5765 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5766 // Insert a new ICmp of the other select operand.
5767 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5768 LHSI->getOperand(1), RHSC,
5769 I.getName()), I);
5770 }
5771 }
5772
5773 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005774 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005775 break;
5776 }
5777 case Instruction::Malloc:
5778 // If we have (malloc != null), and if the malloc has a single use, we
5779 // can assume it is successful and remove the malloc.
5780 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5781 AddToWorkList(LHSI);
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 break;
5786 }
5787 }
5788
5789 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5790 if (User *GEP = dyn_castGetElementPtr(Op0))
5791 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5792 return NI;
5793 if (User *GEP = dyn_castGetElementPtr(Op1))
5794 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5795 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5796 return NI;
5797
5798 // Test to see if the operands of the icmp are casted versions of other
5799 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5800 // now.
5801 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5802 if (isa<PointerType>(Op0->getType()) &&
5803 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5804 // We keep moving the cast from the left operand over to the right
5805 // operand, where it can often be eliminated completely.
5806 Op0 = CI->getOperand(0);
5807
5808 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5809 // so eliminate it as well.
5810 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5811 Op1 = CI2->getOperand(0);
5812
5813 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005814 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005815 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5816 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5817 } else {
5818 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005819 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005820 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005821 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005822 return new ICmpInst(I.getPredicate(), Op0, Op1);
5823 }
5824 }
5825
5826 if (isa<CastInst>(Op0)) {
5827 // Handle the special case of: icmp (cast bool to X), <cst>
5828 // This comes up when you have code like
5829 // int X = A < B;
5830 // if (X) ...
5831 // For generality, we handle any zero-extension of any operand comparison
5832 // with a constant or another cast from the same type.
5833 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5834 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5835 return R;
5836 }
5837
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005838 // ~x < ~y --> y < x
5839 { Value *A, *B;
5840 if (match(Op0, m_Not(m_Value(A))) &&
5841 match(Op1, m_Not(m_Value(B))))
5842 return new ICmpInst(I.getPredicate(), B, A);
5843 }
5844
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005845 if (I.isEquality()) {
5846 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005847
5848 // -x == -y --> x == y
5849 if (match(Op0, m_Neg(m_Value(A))) &&
5850 match(Op1, m_Neg(m_Value(B))))
5851 return new ICmpInst(I.getPredicate(), A, B);
5852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005853 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5854 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5855 Value *OtherVal = A == Op1 ? B : A;
5856 return new ICmpInst(I.getPredicate(), OtherVal,
5857 Constant::getNullValue(A->getType()));
5858 }
5859
5860 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5861 // A^c1 == C^c2 --> A == C^(c1^c2)
5862 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5863 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5864 if (Op1->hasOneUse()) {
5865 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005866 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005867 return new ICmpInst(I.getPredicate(), A,
5868 InsertNewInstBefore(Xor, I));
5869 }
5870
5871 // A^B == A^D -> B == D
5872 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5873 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5874 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5875 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5876 }
5877 }
5878
5879 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5880 (A == Op0 || B == Op0)) {
5881 // A == (A^B) -> B == 0
5882 Value *OtherVal = A == Op0 ? B : A;
5883 return new ICmpInst(I.getPredicate(), OtherVal,
5884 Constant::getNullValue(A->getType()));
5885 }
5886 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5887 // (A-B) == A -> B == 0
5888 return new ICmpInst(I.getPredicate(), B,
5889 Constant::getNullValue(B->getType()));
5890 }
5891 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5892 // A == (A-B) -> B == 0
5893 return new ICmpInst(I.getPredicate(), B,
5894 Constant::getNullValue(B->getType()));
5895 }
5896
5897 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5898 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5899 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5900 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5901 Value *X = 0, *Y = 0, *Z = 0;
5902
5903 if (A == C) {
5904 X = B; Y = D; Z = A;
5905 } else if (A == D) {
5906 X = B; Y = C; Z = A;
5907 } else if (B == C) {
5908 X = A; Y = D; Z = B;
5909 } else if (B == D) {
5910 X = A; Y = C; Z = B;
5911 }
5912
5913 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005914 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5915 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916 I.setOperand(0, Op1);
5917 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5918 return &I;
5919 }
5920 }
5921 }
5922 return Changed ? &I : 0;
5923}
5924
5925
5926/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5927/// and CmpRHS are both known to be integer constants.
5928Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5929 ConstantInt *DivRHS) {
5930 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5931 const APInt &CmpRHSV = CmpRHS->getValue();
5932
5933 // FIXME: If the operand types don't match the type of the divide
5934 // then don't attempt this transform. The code below doesn't have the
5935 // logic to deal with a signed divide and an unsigned compare (and
5936 // vice versa). This is because (x /s C1) <s C2 produces different
5937 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5938 // (x /u C1) <u C2. Simply casting the operands and result won't
5939 // work. :( The if statement below tests that condition and bails
5940 // if it finds it.
5941 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5942 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5943 return 0;
5944 if (DivRHS->isZero())
5945 return 0; // The ProdOV computation fails on divide by zero.
5946
5947 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5948 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5949 // C2 (CI). By solving for X we can turn this into a range check
5950 // instead of computing a divide.
5951 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5952
5953 // Determine if the product overflows by seeing if the product is
5954 // not equal to the divide. Make sure we do the same kind of divide
5955 // as in the LHS instruction that we're folding.
5956 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5957 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5958
5959 // Get the ICmp opcode
5960 ICmpInst::Predicate Pred = ICI.getPredicate();
5961
5962 // Figure out the interval that is being checked. For example, a comparison
5963 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5964 // Compute this interval based on the constants involved and the signedness of
5965 // the compare/divide. This computes a half-open interval, keeping track of
5966 // whether either value in the interval overflows. After analysis each
5967 // overflow variable is set to 0 if it's corresponding bound variable is valid
5968 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5969 int LoOverflow = 0, HiOverflow = 0;
5970 ConstantInt *LoBound = 0, *HiBound = 0;
5971
5972
5973 if (!DivIsSigned) { // udiv
5974 // e.g. X/5 op 3 --> [15, 20)
5975 LoBound = Prod;
5976 HiOverflow = LoOverflow = ProdOV;
5977 if (!HiOverflow)
5978 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005979 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005980 if (CmpRHSV == 0) { // (X / pos) op 0
5981 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5982 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5983 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005984 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5986 HiOverflow = LoOverflow = ProdOV;
5987 if (!HiOverflow)
5988 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5989 } else { // (X / pos) op neg
5990 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5991 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5992 LoOverflow = AddWithOverflow(LoBound, Prod,
5993 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5994 HiBound = AddOne(Prod);
5995 HiOverflow = ProdOV ? -1 : 0;
5996 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005997 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005998 if (CmpRHSV == 0) { // (X / neg) op 0
5999 // e.g. X/-5 op 0 --> [-4, 5)
6000 LoBound = AddOne(DivRHS);
6001 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6002 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6003 HiOverflow = 1; // [INTMIN+1, overflow)
6004 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6005 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006006 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006007 // e.g. X/-5 op 3 --> [-19, -14)
6008 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6009 if (!LoOverflow)
6010 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6011 HiBound = AddOne(Prod);
6012 } else { // (X / neg) op neg
6013 // e.g. X/-5 op -3 --> [15, 20)
6014 LoBound = Prod;
6015 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6016 HiBound = Subtract(Prod, DivRHS);
6017 }
6018
6019 // Dividing by a negative swaps the condition. LT <-> GT
6020 Pred = ICmpInst::getSwappedPredicate(Pred);
6021 }
6022
6023 Value *X = DivI->getOperand(0);
6024 switch (Pred) {
6025 default: assert(0 && "Unhandled icmp opcode!");
6026 case ICmpInst::ICMP_EQ:
6027 if (LoOverflow && HiOverflow)
6028 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6029 else if (HiOverflow)
6030 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6031 ICmpInst::ICMP_UGE, X, LoBound);
6032 else if (LoOverflow)
6033 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6034 ICmpInst::ICMP_ULT, X, HiBound);
6035 else
6036 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6037 case ICmpInst::ICMP_NE:
6038 if (LoOverflow && HiOverflow)
6039 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6040 else if (HiOverflow)
6041 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6042 ICmpInst::ICMP_ULT, X, LoBound);
6043 else if (LoOverflow)
6044 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6045 ICmpInst::ICMP_UGE, X, HiBound);
6046 else
6047 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6048 case ICmpInst::ICMP_ULT:
6049 case ICmpInst::ICMP_SLT:
6050 if (LoOverflow == +1) // Low bound is greater than input range.
6051 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6052 if (LoOverflow == -1) // Low bound is less than input range.
6053 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6054 return new ICmpInst(Pred, X, LoBound);
6055 case ICmpInst::ICMP_UGT:
6056 case ICmpInst::ICMP_SGT:
6057 if (HiOverflow == +1) // High bound greater than input range.
6058 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6059 else if (HiOverflow == -1) // High bound less than input range.
6060 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6061 if (Pred == ICmpInst::ICMP_UGT)
6062 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6063 else
6064 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6065 }
6066}
6067
6068
6069/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6070///
6071Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6072 Instruction *LHSI,
6073 ConstantInt *RHS) {
6074 const APInt &RHSV = RHS->getValue();
6075
6076 switch (LHSI->getOpcode()) {
6077 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6078 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6079 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6080 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006081 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6082 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006083 Value *CompareVal = LHSI->getOperand(0);
6084
6085 // If the sign bit of the XorCST is not set, there is no change to
6086 // the operation, just stop using the Xor.
6087 if (!XorCST->getValue().isNegative()) {
6088 ICI.setOperand(0, CompareVal);
6089 AddToWorkList(LHSI);
6090 return &ICI;
6091 }
6092
6093 // Was the old condition true if the operand is positive?
6094 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6095
6096 // If so, the new one isn't.
6097 isTrueIfPositive ^= true;
6098
6099 if (isTrueIfPositive)
6100 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6101 else
6102 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6103 }
6104 }
6105 break;
6106 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6107 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6108 LHSI->getOperand(0)->hasOneUse()) {
6109 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6110
6111 // If the LHS is an AND of a truncating cast, we can widen the
6112 // and/compare to be the input width without changing the value
6113 // produced, eliminating a cast.
6114 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6115 // We can do this transformation if either the AND constant does not
6116 // have its sign bit set or if it is an equality comparison.
6117 // Extending a relational comparison when we're checking the sign
6118 // bit would not work.
6119 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006120 (ICI.isEquality() ||
6121 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006122 uint32_t BitWidth =
6123 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6124 APInt NewCST = AndCST->getValue();
6125 NewCST.zext(BitWidth);
6126 APInt NewCI = RHSV;
6127 NewCI.zext(BitWidth);
6128 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006129 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006130 ConstantInt::get(NewCST),LHSI->getName());
6131 InsertNewInstBefore(NewAnd, ICI);
6132 return new ICmpInst(ICI.getPredicate(), NewAnd,
6133 ConstantInt::get(NewCI));
6134 }
6135 }
6136
6137 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6138 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6139 // happens a LOT in code produced by the C front-end, for bitfield
6140 // access.
6141 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6142 if (Shift && !Shift->isShift())
6143 Shift = 0;
6144
6145 ConstantInt *ShAmt;
6146 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6147 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6148 const Type *AndTy = AndCST->getType(); // Type of the and.
6149
6150 // We can fold this as long as we can't shift unknown bits
6151 // into the mask. This can only happen with signed shift
6152 // rights, as they sign-extend.
6153 if (ShAmt) {
6154 bool CanFold = Shift->isLogicalShift();
6155 if (!CanFold) {
6156 // To test for the bad case of the signed shr, see if any
6157 // of the bits shifted in could be tested after the mask.
6158 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6159 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6160
6161 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6162 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6163 AndCST->getValue()) == 0)
6164 CanFold = true;
6165 }
6166
6167 if (CanFold) {
6168 Constant *NewCst;
6169 if (Shift->getOpcode() == Instruction::Shl)
6170 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6171 else
6172 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6173
6174 // Check to see if we are shifting out any of the bits being
6175 // compared.
6176 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6177 // If we shifted bits out, the fold is not going to work out.
6178 // As a special case, check to see if this means that the
6179 // result is always true or false now.
6180 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6181 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6182 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6183 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6184 } else {
6185 ICI.setOperand(1, NewCst);
6186 Constant *NewAndCST;
6187 if (Shift->getOpcode() == Instruction::Shl)
6188 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6189 else
6190 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6191 LHSI->setOperand(1, NewAndCST);
6192 LHSI->setOperand(0, Shift->getOperand(0));
6193 AddToWorkList(Shift); // Shift is dead.
6194 AddUsesToWorkList(ICI);
6195 return &ICI;
6196 }
6197 }
6198 }
6199
6200 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6201 // preferable because it allows the C<<Y expression to be hoisted out
6202 // of a loop if Y is invariant and X is not.
6203 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6204 ICI.isEquality() && !Shift->isArithmeticShift() &&
6205 isa<Instruction>(Shift->getOperand(0))) {
6206 // Compute C << Y.
6207 Value *NS;
6208 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006209 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006210 Shift->getOperand(1), "tmp");
6211 } else {
6212 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006213 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006214 Shift->getOperand(1), "tmp");
6215 }
6216 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6217
6218 // Compute X & (C << Y).
6219 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006220 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006221 InsertNewInstBefore(NewAnd, ICI);
6222
6223 ICI.setOperand(0, NewAnd);
6224 return &ICI;
6225 }
6226 }
6227 break;
6228
6229 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6230 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6231 if (!ShAmt) break;
6232
6233 uint32_t TypeBits = RHSV.getBitWidth();
6234
6235 // Check that the shift amount is in range. If not, don't perform
6236 // undefined shifts. When the shift is visited it will be
6237 // simplified.
6238 if (ShAmt->uge(TypeBits))
6239 break;
6240
6241 if (ICI.isEquality()) {
6242 // If we are comparing against bits always shifted out, the
6243 // comparison cannot succeed.
6244 Constant *Comp =
6245 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6246 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6247 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6248 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6249 return ReplaceInstUsesWith(ICI, Cst);
6250 }
6251
6252 if (LHSI->hasOneUse()) {
6253 // Otherwise strength reduce the shift into an and.
6254 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6255 Constant *Mask =
6256 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6257
6258 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006259 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 Mask, LHSI->getName()+".mask");
6261 Value *And = InsertNewInstBefore(AndI, ICI);
6262 return new ICmpInst(ICI.getPredicate(), And,
6263 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6264 }
6265 }
6266
6267 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6268 bool TrueIfSigned = false;
6269 if (LHSI->hasOneUse() &&
6270 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6271 // (X << 31) <s 0 --> (X&1) != 0
6272 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6273 (TypeBits-ShAmt->getZExtValue()-1));
6274 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006275 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006276 Mask, LHSI->getName()+".mask");
6277 Value *And = InsertNewInstBefore(AndI, ICI);
6278
6279 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6280 And, Constant::getNullValue(And->getType()));
6281 }
6282 break;
6283 }
6284
6285 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6286 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006287 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006288 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006289 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006290
Chris Lattner5ee84f82008-03-21 05:19:58 +00006291 // Check that the shift amount is in range. If not, don't perform
6292 // undefined shifts. When the shift is visited it will be
6293 // simplified.
6294 uint32_t TypeBits = RHSV.getBitWidth();
6295 if (ShAmt->uge(TypeBits))
6296 break;
6297
6298 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006299
Chris Lattner5ee84f82008-03-21 05:19:58 +00006300 // If we are comparing against bits always shifted out, the
6301 // comparison cannot succeed.
6302 APInt Comp = RHSV << ShAmtVal;
6303 if (LHSI->getOpcode() == Instruction::LShr)
6304 Comp = Comp.lshr(ShAmtVal);
6305 else
6306 Comp = Comp.ashr(ShAmtVal);
6307
6308 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6309 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6310 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6311 return ReplaceInstUsesWith(ICI, Cst);
6312 }
6313
6314 // Otherwise, check to see if the bits shifted out are known to be zero.
6315 // If so, we can compare against the unshifted value:
6316 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006317 if (LHSI->hasOneUse() &&
6318 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006319 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6320 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6321 ConstantExpr::getShl(RHS, ShAmt));
6322 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323
Evan Chengfb9292a2008-04-23 00:38:06 +00006324 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006325 // Otherwise strength reduce the shift into an and.
6326 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6327 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328
Chris Lattner5ee84f82008-03-21 05:19:58 +00006329 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006330 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006331 Mask, LHSI->getName()+".mask");
6332 Value *And = InsertNewInstBefore(AndI, ICI);
6333 return new ICmpInst(ICI.getPredicate(), And,
6334 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006335 }
6336 break;
6337 }
6338
6339 case Instruction::SDiv:
6340 case Instruction::UDiv:
6341 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6342 // Fold this div into the comparison, producing a range check.
6343 // Determine, based on the divide type, what the range is being
6344 // checked. If there is an overflow on the low or high side, remember
6345 // it, otherwise compute the range [low, hi) bounding the new value.
6346 // See: InsertRangeTest above for the kinds of replacements possible.
6347 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6348 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6349 DivRHS))
6350 return R;
6351 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006352
6353 case Instruction::Add:
6354 // Fold: icmp pred (add, X, C1), C2
6355
6356 if (!ICI.isEquality()) {
6357 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6358 if (!LHSC) break;
6359 const APInt &LHSV = LHSC->getValue();
6360
6361 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6362 .subtract(LHSV);
6363
6364 if (ICI.isSignedPredicate()) {
6365 if (CR.getLower().isSignBit()) {
6366 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6367 ConstantInt::get(CR.getUpper()));
6368 } else if (CR.getUpper().isSignBit()) {
6369 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6370 ConstantInt::get(CR.getLower()));
6371 }
6372 } else {
6373 if (CR.getLower().isMinValue()) {
6374 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6375 ConstantInt::get(CR.getUpper()));
6376 } else if (CR.getUpper().isMinValue()) {
6377 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6378 ConstantInt::get(CR.getLower()));
6379 }
6380 }
6381 }
6382 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006383 }
6384
6385 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6386 if (ICI.isEquality()) {
6387 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6388
6389 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6390 // the second operand is a constant, simplify a bit.
6391 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6392 switch (BO->getOpcode()) {
6393 case Instruction::SRem:
6394 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6395 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6396 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6397 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6398 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006399 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006400 BO->getName());
6401 InsertNewInstBefore(NewRem, ICI);
6402 return new ICmpInst(ICI.getPredicate(), NewRem,
6403 Constant::getNullValue(BO->getType()));
6404 }
6405 }
6406 break;
6407 case Instruction::Add:
6408 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6409 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6410 if (BO->hasOneUse())
6411 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6412 Subtract(RHS, BOp1C));
6413 } else if (RHSV == 0) {
6414 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6415 // efficiently invertible, or if the add has just this one use.
6416 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6417
6418 if (Value *NegVal = dyn_castNegVal(BOp1))
6419 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6420 else if (Value *NegVal = dyn_castNegVal(BOp0))
6421 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6422 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006423 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006424 InsertNewInstBefore(Neg, ICI);
6425 Neg->takeName(BO);
6426 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6427 }
6428 }
6429 break;
6430 case Instruction::Xor:
6431 // For the xor case, we can xor two constants together, eliminating
6432 // the explicit xor.
6433 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6434 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6435 ConstantExpr::getXor(RHS, BOC));
6436
6437 // FALLTHROUGH
6438 case Instruction::Sub:
6439 // Replace (([sub|xor] A, B) != 0) with (A != B)
6440 if (RHSV == 0)
6441 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6442 BO->getOperand(1));
6443 break;
6444
6445 case Instruction::Or:
6446 // If bits are being or'd in that are not present in the constant we
6447 // are comparing against, then the comparison could never succeed!
6448 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6449 Constant *NotCI = ConstantExpr::getNot(RHS);
6450 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6451 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6452 isICMP_NE));
6453 }
6454 break;
6455
6456 case Instruction::And:
6457 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6458 // If bits are being compared against that are and'd out, then the
6459 // comparison can never succeed!
6460 if ((RHSV & ~BOC->getValue()) != 0)
6461 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6462 isICMP_NE));
6463
6464 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6465 if (RHS == BOC && RHSV.isPowerOf2())
6466 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6467 ICmpInst::ICMP_NE, LHSI,
6468 Constant::getNullValue(RHS->getType()));
6469
6470 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6471 if (isSignBit(BOC)) {
6472 Value *X = BO->getOperand(0);
6473 Constant *Zero = Constant::getNullValue(X->getType());
6474 ICmpInst::Predicate pred = isICMP_NE ?
6475 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6476 return new ICmpInst(pred, X, Zero);
6477 }
6478
6479 // ((X & ~7) == 0) --> X < 8
6480 if (RHSV == 0 && isHighOnes(BOC)) {
6481 Value *X = BO->getOperand(0);
6482 Constant *NegX = ConstantExpr::getNeg(BOC);
6483 ICmpInst::Predicate pred = isICMP_NE ?
6484 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6485 return new ICmpInst(pred, X, NegX);
6486 }
6487 }
6488 default: break;
6489 }
6490 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6491 // Handle icmp {eq|ne} <intrinsic>, intcst.
6492 if (II->getIntrinsicID() == Intrinsic::bswap) {
6493 AddToWorkList(II);
6494 ICI.setOperand(0, II->getOperand(1));
6495 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6496 return &ICI;
6497 }
6498 }
6499 } else { // Not a ICMP_EQ/ICMP_NE
6500 // If the LHS is a cast from an integral value of the same size,
6501 // then since we know the RHS is a constant, try to simlify.
6502 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6503 Value *CastOp = Cast->getOperand(0);
6504 const Type *SrcTy = CastOp->getType();
6505 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6506 if (SrcTy->isInteger() &&
6507 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6508 // If this is an unsigned comparison, try to make the comparison use
6509 // smaller constant values.
6510 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6511 // X u< 128 => X s> -1
6512 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6513 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6514 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6515 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6516 // X u> 127 => X s< 0
6517 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6518 Constant::getNullValue(SrcTy));
6519 }
6520 }
6521 }
6522 }
6523 return 0;
6524}
6525
6526/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6527/// We only handle extending casts so far.
6528///
6529Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6530 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6531 Value *LHSCIOp = LHSCI->getOperand(0);
6532 const Type *SrcTy = LHSCIOp->getType();
6533 const Type *DestTy = LHSCI->getType();
6534 Value *RHSCIOp;
6535
6536 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6537 // integer type is the same size as the pointer type.
6538 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6539 getTargetData().getPointerSizeInBits() ==
6540 cast<IntegerType>(DestTy)->getBitWidth()) {
6541 Value *RHSOp = 0;
6542 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6543 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6544 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6545 RHSOp = RHSC->getOperand(0);
6546 // If the pointer types don't match, insert a bitcast.
6547 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006548 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006549 }
6550
6551 if (RHSOp)
6552 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6553 }
6554
6555 // The code below only handles extension cast instructions, so far.
6556 // Enforce this.
6557 if (LHSCI->getOpcode() != Instruction::ZExt &&
6558 LHSCI->getOpcode() != Instruction::SExt)
6559 return 0;
6560
6561 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6562 bool isSignedCmp = ICI.isSignedPredicate();
6563
6564 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6565 // Not an extension from the same type?
6566 RHSCIOp = CI->getOperand(0);
6567 if (RHSCIOp->getType() != LHSCIOp->getType())
6568 return 0;
6569
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006570 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006571 // and the other is a zext), then we can't handle this.
6572 if (CI->getOpcode() != LHSCI->getOpcode())
6573 return 0;
6574
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006575 // Deal with equality cases early.
6576 if (ICI.isEquality())
6577 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6578
6579 // A signed comparison of sign extended values simplifies into a
6580 // signed comparison.
6581 if (isSignedCmp && isSignedExt)
6582 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6583
6584 // The other three cases all fold into an unsigned comparison.
6585 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006586 }
6587
6588 // If we aren't dealing with a constant on the RHS, exit early
6589 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6590 if (!CI)
6591 return 0;
6592
6593 // Compute the constant that would happen if we truncated to SrcTy then
6594 // reextended to DestTy.
6595 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6596 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6597
6598 // If the re-extended constant didn't change...
6599 if (Res2 == CI) {
6600 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6601 // For example, we might have:
6602 // %A = sext short %X to uint
6603 // %B = icmp ugt uint %A, 1330
6604 // It is incorrect to transform this into
6605 // %B = icmp ugt short %X, 1330
6606 // because %A may have negative value.
6607 //
6608 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6609 // OR operation is EQ/NE.
6610 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6611 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6612 else
6613 return 0;
6614 }
6615
6616 // The re-extended constant changed so the constant cannot be represented
6617 // in the shorter type. Consequently, we cannot emit a simple comparison.
6618
6619 // First, handle some easy cases. We know the result cannot be equal at this
6620 // point so handle the ICI.isEquality() cases
6621 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6622 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6623 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6624 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6625
6626 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6627 // should have been folded away previously and not enter in here.
6628 Value *Result;
6629 if (isSignedCmp) {
6630 // We're performing a signed comparison.
6631 if (cast<ConstantInt>(CI)->getValue().isNegative())
6632 Result = ConstantInt::getFalse(); // X < (small) --> false
6633 else
6634 Result = ConstantInt::getTrue(); // X < (large) --> true
6635 } else {
6636 // We're performing an unsigned comparison.
6637 if (isSignedExt) {
6638 // We're performing an unsigned comp with a sign extended value.
6639 // This is true if the input is >= 0. [aka >s -1]
6640 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6641 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6642 NegOne, ICI.getName()), ICI);
6643 } else {
6644 // Unsigned extend & unsigned compare -> always true.
6645 Result = ConstantInt::getTrue();
6646 }
6647 }
6648
6649 // Finally, return the value computed.
6650 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6651 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6652 return ReplaceInstUsesWith(ICI, Result);
6653 } else {
6654 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6655 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6656 "ICmp should be folded!");
6657 if (Constant *CI = dyn_cast<Constant>(Result))
6658 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6659 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006660 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006661 }
6662}
6663
6664Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6665 return commonShiftTransforms(I);
6666}
6667
6668Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6669 return commonShiftTransforms(I);
6670}
6671
6672Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006673 if (Instruction *R = commonShiftTransforms(I))
6674 return R;
6675
6676 Value *Op0 = I.getOperand(0);
6677
6678 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6679 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6680 if (CSI->isAllOnesValue())
6681 return ReplaceInstUsesWith(I, CSI);
6682
6683 // See if we can turn a signed shr into an unsigned shr.
6684 if (MaskedValueIsZero(Op0,
6685 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006686 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006687
6688 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006689}
6690
6691Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6692 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6694
6695 // shl X, 0 == X and shr X, 0 == X
6696 // shl 0, X == 0 and shr 0, X == 0
6697 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6698 Op0 == Constant::getNullValue(Op0->getType()))
6699 return ReplaceInstUsesWith(I, Op0);
6700
6701 if (isa<UndefValue>(Op0)) {
6702 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6703 return ReplaceInstUsesWith(I, Op0);
6704 else // undef << X -> 0, undef >>u X -> 0
6705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6706 }
6707 if (isa<UndefValue>(Op1)) {
6708 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6709 return ReplaceInstUsesWith(I, Op0);
6710 else // X << undef, X >>u undef -> 0
6711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6712 }
6713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006714 // Try to fold constant and into select arguments.
6715 if (isa<Constant>(Op0))
6716 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6717 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6718 return R;
6719
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006720 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6721 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6722 return Res;
6723 return 0;
6724}
6725
6726Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6727 BinaryOperator &I) {
6728 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6729
6730 // See if we can simplify any instructions used by the instruction whose sole
6731 // purpose is to compute bits we don't care about.
6732 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6733 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6734 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6735 KnownZero, KnownOne))
6736 return &I;
6737
6738 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6739 // of a signed value.
6740 //
6741 if (Op1->uge(TypeBits)) {
6742 if (I.getOpcode() != Instruction::AShr)
6743 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6744 else {
6745 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6746 return &I;
6747 }
6748 }
6749
6750 // ((X*C1) << C2) == (X * (C1 << C2))
6751 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6752 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6753 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006754 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006755 ConstantExpr::getShl(BOOp, Op1));
6756
6757 // Try to fold constant and into select arguments.
6758 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6759 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6760 return R;
6761 if (isa<PHINode>(Op0))
6762 if (Instruction *NV = FoldOpIntoPhi(I))
6763 return NV;
6764
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006765 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6766 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6767 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6768 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6769 // place. Don't try to do this transformation in this case. Also, we
6770 // require that the input operand is a shift-by-constant so that we have
6771 // confidence that the shifts will get folded together. We could do this
6772 // xform in more cases, but it is unlikely to be profitable.
6773 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6774 isa<ConstantInt>(TrOp->getOperand(1))) {
6775 // Okay, we'll do this xform. Make the shift of shift.
6776 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006777 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006778 I.getName());
6779 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6780
6781 // For logical shifts, the truncation has the effect of making the high
6782 // part of the register be zeros. Emulate this by inserting an AND to
6783 // clear the top bits as needed. This 'and' will usually be zapped by
6784 // other xforms later if dead.
6785 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6786 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6787 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6788
6789 // The mask we constructed says what the trunc would do if occurring
6790 // between the shifts. We want to know the effect *after* the second
6791 // shift. We know that it is a logical shift by a constant, so adjust the
6792 // mask as appropriate.
6793 if (I.getOpcode() == Instruction::Shl)
6794 MaskV <<= Op1->getZExtValue();
6795 else {
6796 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6797 MaskV = MaskV.lshr(Op1->getZExtValue());
6798 }
6799
Gabor Greifa645dd32008-05-16 19:29:10 +00006800 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006801 TI->getName());
6802 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6803
6804 // Return the value truncated to the interesting size.
6805 return new TruncInst(And, I.getType());
6806 }
6807 }
6808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 if (Op0->hasOneUse()) {
6810 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6811 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6812 Value *V1, *V2;
6813 ConstantInt *CC;
6814 switch (Op0BO->getOpcode()) {
6815 default: break;
6816 case Instruction::Add:
6817 case Instruction::And:
6818 case Instruction::Or:
6819 case Instruction::Xor: {
6820 // These operators commute.
6821 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6822 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6823 match(Op0BO->getOperand(1),
6824 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006825 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006826 Op0BO->getOperand(0), Op1,
6827 Op0BO->getName());
6828 InsertNewInstBefore(YS, I); // (Y << C)
6829 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006830 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006831 Op0BO->getOperand(1)->getName());
6832 InsertNewInstBefore(X, I); // (X + (Y << C))
6833 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006834 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006835 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6836 }
6837
6838 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6839 Value *Op0BOOp1 = Op0BO->getOperand(1);
6840 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6841 match(Op0BOOp1,
6842 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6843 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6844 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006845 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006846 Op0BO->getOperand(0), Op1,
6847 Op0BO->getName());
6848 InsertNewInstBefore(YS, I); // (Y << C)
6849 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006850 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006851 V1->getName()+".mask");
6852 InsertNewInstBefore(XM, I); // X & (CC << C)
6853
Gabor Greifa645dd32008-05-16 19:29:10 +00006854 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006855 }
6856 }
6857
6858 // FALL THROUGH.
6859 case Instruction::Sub: {
6860 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6861 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6862 match(Op0BO->getOperand(0),
6863 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006864 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006865 Op0BO->getOperand(1), Op1,
6866 Op0BO->getName());
6867 InsertNewInstBefore(YS, I); // (Y << C)
6868 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006869 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006870 Op0BO->getOperand(0)->getName());
6871 InsertNewInstBefore(X, I); // (X + (Y << C))
6872 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006873 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006874 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6875 }
6876
6877 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6878 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6879 match(Op0BO->getOperand(0),
6880 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6881 m_ConstantInt(CC))) && V2 == Op1 &&
6882 cast<BinaryOperator>(Op0BO->getOperand(0))
6883 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006884 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 Op0BO->getOperand(1), Op1,
6886 Op0BO->getName());
6887 InsertNewInstBefore(YS, I); // (Y << C)
6888 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006889 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006890 V1->getName()+".mask");
6891 InsertNewInstBefore(XM, I); // X & (CC << C)
6892
Gabor Greifa645dd32008-05-16 19:29:10 +00006893 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006894 }
6895
6896 break;
6897 }
6898 }
6899
6900
6901 // If the operand is an bitwise operator with a constant RHS, and the
6902 // shift is the only use, we can pull it out of the shift.
6903 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6904 bool isValid = true; // Valid only for And, Or, Xor
6905 bool highBitSet = false; // Transform if high bit of constant set?
6906
6907 switch (Op0BO->getOpcode()) {
6908 default: isValid = false; break; // Do not perform transform!
6909 case Instruction::Add:
6910 isValid = isLeftShift;
6911 break;
6912 case Instruction::Or:
6913 case Instruction::Xor:
6914 highBitSet = false;
6915 break;
6916 case Instruction::And:
6917 highBitSet = true;
6918 break;
6919 }
6920
6921 // If this is a signed shift right, and the high bit is modified
6922 // by the logical operation, do not perform the transformation.
6923 // The highBitSet boolean indicates the value of the high bit of
6924 // the constant which would cause it to be modified for this
6925 // operation.
6926 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006927 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006928 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006929
6930 if (isValid) {
6931 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6932
6933 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006934 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006935 InsertNewInstBefore(NewShift, I);
6936 NewShift->takeName(Op0BO);
6937
Gabor Greifa645dd32008-05-16 19:29:10 +00006938 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006939 NewRHS);
6940 }
6941 }
6942 }
6943 }
6944
6945 // Find out if this is a shift of a shift by a constant.
6946 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6947 if (ShiftOp && !ShiftOp->isShift())
6948 ShiftOp = 0;
6949
6950 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6951 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6952 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6953 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6954 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6955 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6956 Value *X = ShiftOp->getOperand(0);
6957
6958 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6959 if (AmtSum > TypeBits)
6960 AmtSum = TypeBits;
6961
6962 const IntegerType *Ty = cast<IntegerType>(I.getType());
6963
6964 // Check for (X << c1) << c2 and (X >> c1) >> c2
6965 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006966 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006967 ConstantInt::get(Ty, AmtSum));
6968 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6969 I.getOpcode() == Instruction::AShr) {
6970 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006971 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006972 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6973 I.getOpcode() == Instruction::LShr) {
6974 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6975 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006976 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006977 InsertNewInstBefore(Shift, I);
6978
6979 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006980 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006981 }
6982
6983 // Okay, if we get here, one shift must be left, and the other shift must be
6984 // right. See if the amounts are equal.
6985 if (ShiftAmt1 == ShiftAmt2) {
6986 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6987 if (I.getOpcode() == Instruction::Shl) {
6988 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006989 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006990 }
6991 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6992 if (I.getOpcode() == Instruction::LShr) {
6993 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006994 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006995 }
6996 // We can simplify ((X << C) >>s C) into a trunc + sext.
6997 // NOTE: we could do this for any C, but that would make 'unusual' integer
6998 // types. For now, just stick to ones well-supported by the code
6999 // generators.
7000 const Type *SExtType = 0;
7001 switch (Ty->getBitWidth() - ShiftAmt1) {
7002 case 1 :
7003 case 8 :
7004 case 16 :
7005 case 32 :
7006 case 64 :
7007 case 128:
7008 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7009 break;
7010 default: break;
7011 }
7012 if (SExtType) {
7013 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7014 InsertNewInstBefore(NewTrunc, I);
7015 return new SExtInst(NewTrunc, Ty);
7016 }
7017 // Otherwise, we can't handle it yet.
7018 } else if (ShiftAmt1 < ShiftAmt2) {
7019 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7020
7021 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7022 if (I.getOpcode() == Instruction::Shl) {
7023 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7024 ShiftOp->getOpcode() == Instruction::AShr);
7025 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007026 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007027 InsertNewInstBefore(Shift, I);
7028
7029 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007030 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 }
7032
7033 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7034 if (I.getOpcode() == Instruction::LShr) {
7035 assert(ShiftOp->getOpcode() == Instruction::Shl);
7036 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007037 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007038 InsertNewInstBefore(Shift, I);
7039
7040 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007041 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007042 }
7043
7044 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7045 } else {
7046 assert(ShiftAmt2 < ShiftAmt1);
7047 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7048
7049 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7050 if (I.getOpcode() == Instruction::Shl) {
7051 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7052 ShiftOp->getOpcode() == Instruction::AShr);
7053 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007054 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007055 ConstantInt::get(Ty, ShiftDiff));
7056 InsertNewInstBefore(Shift, I);
7057
7058 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007059 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007060 }
7061
7062 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7063 if (I.getOpcode() == Instruction::LShr) {
7064 assert(ShiftOp->getOpcode() == Instruction::Shl);
7065 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007066 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 InsertNewInstBefore(Shift, I);
7068
7069 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007070 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071 }
7072
7073 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7074 }
7075 }
7076 return 0;
7077}
7078
7079
7080/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7081/// expression. If so, decompose it, returning some value X, such that Val is
7082/// X*Scale+Offset.
7083///
7084static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7085 int &Offset) {
7086 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7087 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7088 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007089 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007090 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007091 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7093 if (I->getOpcode() == Instruction::Shl) {
7094 // This is a value scaled by '1 << the shift amt'.
7095 Scale = 1U << RHS->getZExtValue();
7096 Offset = 0;
7097 return I->getOperand(0);
7098 } else if (I->getOpcode() == Instruction::Mul) {
7099 // This value is scaled by 'RHS'.
7100 Scale = RHS->getZExtValue();
7101 Offset = 0;
7102 return I->getOperand(0);
7103 } else if (I->getOpcode() == Instruction::Add) {
7104 // We have X+C. Check to see if we really have (X*C2)+C1,
7105 // where C1 is divisible by C2.
7106 unsigned SubScale;
7107 Value *SubVal =
7108 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7109 Offset += RHS->getZExtValue();
7110 Scale = SubScale;
7111 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007112 }
7113 }
7114 }
7115
7116 // Otherwise, we can't look past this.
7117 Scale = 1;
7118 Offset = 0;
7119 return Val;
7120}
7121
7122
7123/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7124/// try to eliminate the cast by moving the type information into the alloc.
7125Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7126 AllocationInst &AI) {
7127 const PointerType *PTy = cast<PointerType>(CI.getType());
7128
7129 // Remove any uses of AI that are dead.
7130 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7131
7132 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7133 Instruction *User = cast<Instruction>(*UI++);
7134 if (isInstructionTriviallyDead(User)) {
7135 while (UI != E && *UI == User)
7136 ++UI; // If this instruction uses AI more than once, don't break UI.
7137
7138 ++NumDeadInst;
7139 DOUT << "IC: DCE: " << *User;
7140 EraseInstFromFunction(*User);
7141 }
7142 }
7143
7144 // Get the type really allocated and the type casted to.
7145 const Type *AllocElTy = AI.getAllocatedType();
7146 const Type *CastElTy = PTy->getElementType();
7147 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7148
7149 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7150 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7151 if (CastElTyAlign < AllocElTyAlign) return 0;
7152
7153 // If the allocation has multiple uses, only promote it if we are strictly
7154 // increasing the alignment of the resultant allocation. If we keep it the
7155 // same, we open the door to infinite loops of various kinds.
7156 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7157
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007158 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7159 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7161
7162 // See if we can satisfy the modulus by pulling a scale out of the array
7163 // size argument.
7164 unsigned ArraySizeScale;
7165 int ArrayOffset;
7166 Value *NumElements = // See if the array size is a decomposable linear expr.
7167 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7168
7169 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7170 // do the xform.
7171 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7172 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7173
7174 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7175 Value *Amt = 0;
7176 if (Scale == 1) {
7177 Amt = NumElements;
7178 } else {
7179 // If the allocation size is constant, form a constant mul expression
7180 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7181 if (isa<ConstantInt>(NumElements))
7182 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7183 // otherwise multiply the amount and the number of elements
7184 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007185 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007186 Amt = InsertNewInstBefore(Tmp, AI);
7187 }
7188 }
7189
7190 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7191 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007192 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007193 Amt = InsertNewInstBefore(Tmp, AI);
7194 }
7195
7196 AllocationInst *New;
7197 if (isa<MallocInst>(AI))
7198 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7199 else
7200 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7201 InsertNewInstBefore(New, AI);
7202 New->takeName(&AI);
7203
7204 // If the allocation has multiple uses, insert a cast and change all things
7205 // that used it to use the new cast. This will also hack on CI, but it will
7206 // die soon.
7207 if (!AI.hasOneUse()) {
7208 AddUsesToWorkList(AI);
7209 // New is the allocation instruction, pointer typed. AI is the original
7210 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7211 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7212 InsertNewInstBefore(NewCast, AI);
7213 AI.replaceAllUsesWith(NewCast);
7214 }
7215 return ReplaceInstUsesWith(CI, New);
7216}
7217
7218/// CanEvaluateInDifferentType - Return true if we can take the specified value
7219/// and return it as type Ty without inserting any new casts and without
7220/// changing the computed value. This is used by code that tries to decide
7221/// whether promoting or shrinking integer operations to wider or smaller types
7222/// will allow us to eliminate a truncate or extend.
7223///
7224/// This is a truncation operation if Ty is smaller than V->getType(), or an
7225/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007226bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7227 unsigned CastOpc,
7228 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007229 // We can always evaluate constants in another type.
7230 if (isa<ConstantInt>(V))
7231 return true;
7232
7233 Instruction *I = dyn_cast<Instruction>(V);
7234 if (!I) return false;
7235
7236 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7237
Chris Lattneref70bb82007-08-02 06:11:14 +00007238 // If this is an extension or truncate, we can often eliminate it.
7239 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7240 // If this is a cast from the destination type, we can trivially eliminate
7241 // it, and this will remove a cast overall.
7242 if (I->getOperand(0)->getType() == Ty) {
7243 // If the first operand is itself a cast, and is eliminable, do not count
7244 // this as an eliminable cast. We would prefer to eliminate those two
7245 // casts first.
7246 if (!isa<CastInst>(I->getOperand(0)))
7247 ++NumCastsRemoved;
7248 return true;
7249 }
7250 }
7251
7252 // We can't extend or shrink something that has multiple uses: doing so would
7253 // require duplicating the instruction in general, which isn't profitable.
7254 if (!I->hasOneUse()) return false;
7255
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007256 switch (I->getOpcode()) {
7257 case Instruction::Add:
7258 case Instruction::Sub:
7259 case Instruction::And:
7260 case Instruction::Or:
7261 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007262 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007263 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7264 NumCastsRemoved) &&
7265 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7266 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007267
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007268 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007269 // A multiply can be truncated by truncating its operands.
7270 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7271 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7272 NumCastsRemoved) &&
7273 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7274 NumCastsRemoved);
7275
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 // If we are truncating the result of this SHL, and if it's a shift of a
7278 // constant amount, we can always perform a SHL in a smaller type.
7279 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7280 uint32_t BitWidth = Ty->getBitWidth();
7281 if (BitWidth < OrigTy->getBitWidth() &&
7282 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007283 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7284 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007285 }
7286 break;
7287 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288 // If this is a truncate of a logical shr, we can truncate it to a smaller
7289 // lshr iff we know that the bits we would otherwise be shifting in are
7290 // already zeros.
7291 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7292 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7293 uint32_t BitWidth = Ty->getBitWidth();
7294 if (BitWidth < OrigBitWidth &&
7295 MaskedValueIsZero(I->getOperand(0),
7296 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7297 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007298 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7299 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 }
7301 }
7302 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007303 case Instruction::ZExt:
7304 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007305 case Instruction::Trunc:
7306 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007307 // can safely replace it. Note that replacing it does not reduce the number
7308 // of casts in the input.
7309 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007310 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00007311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007312 break;
7313 default:
7314 // TODO: Can handle more cases here.
7315 break;
7316 }
7317
7318 return false;
7319}
7320
7321/// EvaluateInDifferentType - Given an expression that
7322/// CanEvaluateInDifferentType returns true for, actually insert the code to
7323/// evaluate the expression.
7324Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7325 bool isSigned) {
7326 if (Constant *C = dyn_cast<Constant>(V))
7327 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7328
7329 // Otherwise, it must be an instruction.
7330 Instruction *I = cast<Instruction>(V);
7331 Instruction *Res = 0;
7332 switch (I->getOpcode()) {
7333 case Instruction::Add:
7334 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007335 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007336 case Instruction::And:
7337 case Instruction::Or:
7338 case Instruction::Xor:
7339 case Instruction::AShr:
7340 case Instruction::LShr:
7341 case Instruction::Shl: {
7342 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7343 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007344 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007345 LHS, RHS, I->getName());
7346 break;
7347 }
7348 case Instruction::Trunc:
7349 case Instruction::ZExt:
7350 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007351 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007352 // just return the source. There's no need to insert it because it is not
7353 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007354 if (I->getOperand(0)->getType() == Ty)
7355 return I->getOperand(0);
7356
Chris Lattneref70bb82007-08-02 06:11:14 +00007357 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007358 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007359 Ty, I->getName());
7360 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007361 default:
7362 // TODO: Can handle more cases here.
7363 assert(0 && "Unreachable!");
7364 break;
7365 }
7366
7367 return InsertNewInstBefore(Res, *I);
7368}
7369
7370/// @brief Implement the transforms common to all CastInst visitors.
7371Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7372 Value *Src = CI.getOperand(0);
7373
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007374 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7375 // eliminate it now.
7376 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7377 if (Instruction::CastOps opc =
7378 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7379 // The first cast (CSrc) is eliminable so we need to fix up or replace
7380 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007381 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007382 }
7383 }
7384
7385 // If we are casting a select then fold the cast into the select
7386 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7387 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7388 return NV;
7389
7390 // If we are casting a PHI then fold the cast into the PHI
7391 if (isa<PHINode>(Src))
7392 if (Instruction *NV = FoldOpIntoPhi(CI))
7393 return NV;
7394
7395 return 0;
7396}
7397
7398/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7399Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7400 Value *Src = CI.getOperand(0);
7401
7402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7403 // If casting the result of a getelementptr instruction with no offset, turn
7404 // this into a cast of the original pointer!
7405 if (GEP->hasAllZeroIndices()) {
7406 // Changing the cast operand is usually not a good idea but it is safe
7407 // here because the pointer operand is being replaced with another
7408 // pointer operand so the opcode doesn't need to change.
7409 AddToWorkList(GEP);
7410 CI.setOperand(0, GEP->getOperand(0));
7411 return &CI;
7412 }
7413
7414 // If the GEP has a single use, and the base pointer is a bitcast, and the
7415 // GEP computes a constant offset, see if we can convert these three
7416 // instructions into fewer. This typically happens with unions and other
7417 // non-type-safe code.
7418 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7419 if (GEP->hasAllConstantIndices()) {
7420 // We are guaranteed to get a constant from EmitGEPOffset.
7421 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7422 int64_t Offset = OffsetV->getSExtValue();
7423
7424 // Get the base pointer input of the bitcast, and the type it points to.
7425 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7426 const Type *GEPIdxTy =
7427 cast<PointerType>(OrigBase->getType())->getElementType();
7428 if (GEPIdxTy->isSized()) {
7429 SmallVector<Value*, 8> NewIndices;
7430
7431 // Start with the index over the outer type. Note that the type size
7432 // might be zero (even if the offset isn't zero) if the indexed type
7433 // is something like [0 x {int, int}]
7434 const Type *IntPtrTy = TD->getIntPtrType();
7435 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007436 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007437 FirstIdx = Offset/TySize;
7438 Offset %= TySize;
7439
7440 // Handle silly modulus not returning values values [0..TySize).
7441 if (Offset < 0) {
7442 --FirstIdx;
7443 Offset += TySize;
7444 assert(Offset >= 0);
7445 }
7446 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7447 }
7448
7449 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7450
7451 // Index into the types. If we fail, set OrigBase to null.
7452 while (Offset) {
7453 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7454 const StructLayout *SL = TD->getStructLayout(STy);
7455 if (Offset < (int64_t)SL->getSizeInBytes()) {
7456 unsigned Elt = SL->getElementContainingOffset(Offset);
7457 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7458
7459 Offset -= SL->getElementOffset(Elt);
7460 GEPIdxTy = STy->getElementType(Elt);
7461 } else {
7462 // Otherwise, we can't index into this, bail out.
7463 Offset = 0;
7464 OrigBase = 0;
7465 }
7466 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7467 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007468 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007469 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7470 Offset %= EltSize;
7471 } else {
7472 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7473 }
7474 GEPIdxTy = STy->getElementType();
7475 } else {
7476 // Otherwise, we can't index into this, bail out.
7477 Offset = 0;
7478 OrigBase = 0;
7479 }
7480 }
7481 if (OrigBase) {
7482 // If we were able to index down into an element, create the GEP
7483 // and bitcast the result. This eliminates one bitcast, potentially
7484 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007485 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7486 NewIndices.begin(),
7487 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007488 InsertNewInstBefore(NGEP, CI);
7489 NGEP->takeName(GEP);
7490
7491 if (isa<BitCastInst>(CI))
7492 return new BitCastInst(NGEP, CI.getType());
7493 assert(isa<PtrToIntInst>(CI));
7494 return new PtrToIntInst(NGEP, CI.getType());
7495 }
7496 }
7497 }
7498 }
7499 }
7500
7501 return commonCastTransforms(CI);
7502}
7503
7504
7505
7506/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7507/// integer types. This function implements the common transforms for all those
7508/// cases.
7509/// @brief Implement the transforms common to CastInst with integer operands
7510Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7511 if (Instruction *Result = commonCastTransforms(CI))
7512 return Result;
7513
7514 Value *Src = CI.getOperand(0);
7515 const Type *SrcTy = Src->getType();
7516 const Type *DestTy = CI.getType();
7517 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7518 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7519
7520 // See if we can simplify any instructions used by the LHS whose sole
7521 // purpose is to compute bits we don't care about.
7522 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7523 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7524 KnownZero, KnownOne))
7525 return &CI;
7526
7527 // If the source isn't an instruction or has more than one use then we
7528 // can't do anything more.
7529 Instruction *SrcI = dyn_cast<Instruction>(Src);
7530 if (!SrcI || !Src->hasOneUse())
7531 return 0;
7532
7533 // Attempt to propagate the cast into the instruction for int->int casts.
7534 int NumCastsRemoved = 0;
7535 if (!isa<BitCastInst>(CI) &&
7536 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007537 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007539 // eliminates the cast, so it is always a win. If this is a zero-extension,
7540 // we need to do an AND to maintain the clear top-part of the computation,
7541 // so we require that the input have eliminated at least one cast. If this
7542 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007543 // require that two casts have been eliminated.
7544 bool DoXForm;
7545 switch (CI.getOpcode()) {
7546 default:
7547 // All the others use floating point so we shouldn't actually
7548 // get here because of the check above.
7549 assert(0 && "Unknown cast type");
7550 case Instruction::Trunc:
7551 DoXForm = true;
7552 break;
7553 case Instruction::ZExt:
7554 DoXForm = NumCastsRemoved >= 1;
7555 break;
7556 case Instruction::SExt:
7557 DoXForm = NumCastsRemoved >= 2;
7558 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007559 }
7560
7561 if (DoXForm) {
7562 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7563 CI.getOpcode() == Instruction::SExt);
7564 assert(Res->getType() == DestTy);
7565 switch (CI.getOpcode()) {
7566 default: assert(0 && "Unknown cast type!");
7567 case Instruction::Trunc:
7568 case Instruction::BitCast:
7569 // Just replace this cast with the result.
7570 return ReplaceInstUsesWith(CI, Res);
7571 case Instruction::ZExt: {
7572 // We need to emit an AND to clear the high bits.
7573 assert(SrcBitSize < DestBitSize && "Not a zext?");
7574 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7575 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007576 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007577 }
7578 case Instruction::SExt:
7579 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007580 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007581 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7582 CI), DestTy);
7583 }
7584 }
7585 }
7586
7587 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7588 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7589
7590 switch (SrcI->getOpcode()) {
7591 case Instruction::Add:
7592 case Instruction::Mul:
7593 case Instruction::And:
7594 case Instruction::Or:
7595 case Instruction::Xor:
7596 // If we are discarding information, rewrite.
7597 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7598 // Don't insert two casts if they cannot be eliminated. We allow
7599 // two casts to be inserted if the sizes are the same. This could
7600 // only be converting signedness, which is a noop.
7601 if (DestBitSize == SrcBitSize ||
7602 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7603 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7604 Instruction::CastOps opcode = CI.getOpcode();
7605 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7606 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007607 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7609 }
7610 }
7611
7612 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7613 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7614 SrcI->getOpcode() == Instruction::Xor &&
7615 Op1 == ConstantInt::getTrue() &&
7616 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7617 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007618 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007619 }
7620 break;
7621 case Instruction::SDiv:
7622 case Instruction::UDiv:
7623 case Instruction::SRem:
7624 case Instruction::URem:
7625 // If we are just changing the sign, rewrite.
7626 if (DestBitSize == SrcBitSize) {
7627 // Don't insert two casts if they cannot be eliminated. We allow
7628 // two casts to be inserted if the sizes are the same. This could
7629 // only be converting signedness, which is a noop.
7630 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7631 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7632 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7633 Op0, DestTy, SrcI);
7634 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7635 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007636 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7638 }
7639 }
7640 break;
7641
7642 case Instruction::Shl:
7643 // Allow changing the sign of the source operand. Do not allow
7644 // changing the size of the shift, UNLESS the shift amount is a
7645 // constant. We must not change variable sized shifts to a smaller
7646 // size, because it is undefined to shift more bits out than exist
7647 // in the value.
7648 if (DestBitSize == SrcBitSize ||
7649 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7650 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7651 Instruction::BitCast : Instruction::Trunc);
7652 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7653 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656 break;
7657 case Instruction::AShr:
7658 // If this is a signed shr, and if all bits shifted in are about to be
7659 // truncated off, turn it into an unsigned shr to allow greater
7660 // simplifications.
7661 if (DestBitSize < SrcBitSize &&
7662 isa<ConstantInt>(Op1)) {
7663 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7664 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7665 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007666 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007667 }
7668 }
7669 break;
7670 }
7671 return 0;
7672}
7673
7674Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7675 if (Instruction *Result = commonIntCastTransforms(CI))
7676 return Result;
7677
7678 Value *Src = CI.getOperand(0);
7679 const Type *Ty = CI.getType();
7680 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7681 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7682
7683 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7684 switch (SrcI->getOpcode()) {
7685 default: break;
7686 case Instruction::LShr:
7687 // We can shrink lshr to something smaller if we know the bits shifted in
7688 // are already zeros.
7689 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7690 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7691
7692 // Get a mask for the bits shifting in.
7693 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7694 Value* SrcIOp0 = SrcI->getOperand(0);
7695 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7696 if (ShAmt >= DestBitWidth) // All zeros.
7697 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7698
7699 // Okay, we can shrink this. Truncate the input, then return a new
7700 // shift.
7701 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7702 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7703 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007704 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007705 }
7706 } else { // This is a variable shr.
7707
7708 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7709 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7710 // loop-invariant and CSE'd.
7711 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7712 Value *One = ConstantInt::get(SrcI->getType(), 1);
7713
7714 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007715 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007717 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007718 SrcI->getOperand(0),
7719 "tmp"), CI);
7720 Value *Zero = Constant::getNullValue(V->getType());
7721 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7722 }
7723 }
7724 break;
7725 }
7726 }
7727
7728 return 0;
7729}
7730
Evan Chenge3779cf2008-03-24 00:21:34 +00007731/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7732/// in order to eliminate the icmp.
7733Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7734 bool DoXform) {
7735 // If we are just checking for a icmp eq of a single bit and zext'ing it
7736 // to an integer, then shift the bit to the appropriate place and then
7737 // cast to integer to avoid the comparison.
7738 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7739 const APInt &Op1CV = Op1C->getValue();
7740
7741 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7742 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7743 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7744 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7745 if (!DoXform) return ICI;
7746
7747 Value *In = ICI->getOperand(0);
7748 Value *Sh = ConstantInt::get(In->getType(),
7749 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007750 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007751 In->getName()+".lobit"),
7752 CI);
7753 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007754 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007755 false/*ZExt*/, "tmp", &CI);
7756
7757 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7758 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007759 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007760 In->getName()+".not"),
7761 CI);
7762 }
7763
7764 return ReplaceInstUsesWith(CI, In);
7765 }
7766
7767
7768
7769 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7770 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7771 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7772 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7773 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7774 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7775 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7776 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7777 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7778 // This only works for EQ and NE
7779 ICI->isEquality()) {
7780 // If Op1C some other power of two, convert:
7781 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7782 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7783 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7784 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7785
7786 APInt KnownZeroMask(~KnownZero);
7787 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7788 if (!DoXform) return ICI;
7789
7790 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7791 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7792 // (X&4) == 2 --> false
7793 // (X&4) != 2 --> true
7794 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7795 Res = ConstantExpr::getZExt(Res, CI.getType());
7796 return ReplaceInstUsesWith(CI, Res);
7797 }
7798
7799 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7800 Value *In = ICI->getOperand(0);
7801 if (ShiftAmt) {
7802 // Perform a logical shr by shiftamt.
7803 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007804 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007805 ConstantInt::get(In->getType(), ShiftAmt),
7806 In->getName()+".lobit"), CI);
7807 }
7808
7809 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7810 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007811 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007812 InsertNewInstBefore(cast<Instruction>(In), CI);
7813 }
7814
7815 if (CI.getType() == In->getType())
7816 return ReplaceInstUsesWith(CI, In);
7817 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007818 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007819 }
7820 }
7821 }
7822
7823 return 0;
7824}
7825
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007826Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7827 // If one of the common conversion will work ..
7828 if (Instruction *Result = commonIntCastTransforms(CI))
7829 return Result;
7830
7831 Value *Src = CI.getOperand(0);
7832
7833 // If this is a cast of a cast
7834 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7835 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7836 // types and if the sizes are just right we can convert this into a logical
7837 // 'and' which will be much cheaper than the pair of casts.
7838 if (isa<TruncInst>(CSrc)) {
7839 // Get the sizes of the types involved
7840 Value *A = CSrc->getOperand(0);
7841 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7842 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7843 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7844 // If we're actually extending zero bits and the trunc is a no-op
7845 if (MidSize < DstSize && SrcSize == DstSize) {
7846 // Replace both of the casts with an And of the type mask.
7847 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7848 Constant *AndConst = ConstantInt::get(AndValue);
7849 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007850 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007851 // Unfortunately, if the type changed, we need to cast it back.
7852 if (And->getType() != CI.getType()) {
7853 And->setName(CSrc->getName()+".mask");
7854 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007855 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007856 }
7857 return And;
7858 }
7859 }
7860 }
7861
Evan Chenge3779cf2008-03-24 00:21:34 +00007862 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7863 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864
Evan Chenge3779cf2008-03-24 00:21:34 +00007865 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7866 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7867 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7868 // of the (zext icmp) will be transformed.
7869 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7870 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7871 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7872 (transformZExtICmp(LHS, CI, false) ||
7873 transformZExtICmp(RHS, CI, false))) {
7874 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7875 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007876 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007878 }
7879
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007880 return 0;
7881}
7882
7883Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7884 if (Instruction *I = commonIntCastTransforms(CI))
7885 return I;
7886
7887 Value *Src = CI.getOperand(0);
7888
7889 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7890 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7891 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7892 // If we are just checking for a icmp eq of a single bit and zext'ing it
7893 // to an integer, then shift the bit to the appropriate place and then
7894 // cast to integer to avoid the comparison.
7895 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7896 const APInt &Op1CV = Op1C->getValue();
7897
7898 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7899 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7900 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7901 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7902 Value *In = ICI->getOperand(0);
7903 Value *Sh = ConstantInt::get(In->getType(),
7904 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007905 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007906 In->getName()+".lobit"),
7907 CI);
7908 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007909 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007910 true/*SExt*/, "tmp", &CI);
7911
7912 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007913 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007914 In->getName()+".not"), CI);
7915
7916 return ReplaceInstUsesWith(CI, In);
7917 }
7918 }
7919 }
7920
7921 return 0;
7922}
7923
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007924/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7925/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007926static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007927 APFloat F = CFP->getValueAPF();
7928 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007929 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007930 return 0;
7931}
7932
7933/// LookThroughFPExtensions - If this is an fp extension instruction, look
7934/// through it until we get the source value.
7935static Value *LookThroughFPExtensions(Value *V) {
7936 if (Instruction *I = dyn_cast<Instruction>(V))
7937 if (I->getOpcode() == Instruction::FPExt)
7938 return LookThroughFPExtensions(I->getOperand(0));
7939
7940 // If this value is a constant, return the constant in the smallest FP type
7941 // that can accurately represent it. This allows us to turn
7942 // (float)((double)X+2.0) into x+2.0f.
7943 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7944 if (CFP->getType() == Type::PPC_FP128Ty)
7945 return V; // No constant folding of this.
7946 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007947 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007948 return V;
7949 if (CFP->getType() == Type::DoubleTy)
7950 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007951 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007952 return V;
7953 // Don't try to shrink to various long double types.
7954 }
7955
7956 return V;
7957}
7958
7959Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7960 if (Instruction *I = commonCastTransforms(CI))
7961 return I;
7962
7963 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7964 // smaller than the destination type, we can eliminate the truncate by doing
7965 // the add as the smaller type. This applies to add/sub/mul/div as well as
7966 // many builtins (sqrt, etc).
7967 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7968 if (OpI && OpI->hasOneUse()) {
7969 switch (OpI->getOpcode()) {
7970 default: break;
7971 case Instruction::Add:
7972 case Instruction::Sub:
7973 case Instruction::Mul:
7974 case Instruction::FDiv:
7975 case Instruction::FRem:
7976 const Type *SrcTy = OpI->getType();
7977 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7978 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7979 if (LHSTrunc->getType() != SrcTy &&
7980 RHSTrunc->getType() != SrcTy) {
7981 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7982 // If the source types were both smaller than the destination type of
7983 // the cast, do this xform.
7984 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7985 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7986 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7987 CI.getType(), CI);
7988 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7989 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007990 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007991 }
7992 }
7993 break;
7994 }
7995 }
7996 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007997}
7998
7999Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8000 return commonCastTransforms(CI);
8001}
8002
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008003Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8004 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8005 // mantissa to accurately represent all values of X. For example, do not
8006 // do this with i64->float->i64.
8007 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8008 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8009 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8010 GetFPMantissaWidth(SrcI->getType()))
8011 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8012
8013 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008014}
8015
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008016Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8017 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8018 // mantissa to accurately represent all values of X. For example, do not
8019 // do this with i64->float->i64.
8020 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8021 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8022 (int)FI.getType()->getPrimitiveSizeInBits() <=
8023 GetFPMantissaWidth(SrcI->getType()))
8024 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8025
8026 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008027}
8028
8029Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8030 return commonCastTransforms(CI);
8031}
8032
8033Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8034 return commonCastTransforms(CI);
8035}
8036
8037Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8038 return commonPointerCastTransforms(CI);
8039}
8040
Chris Lattner7c1626482008-01-08 07:23:51 +00008041Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8042 if (Instruction *I = commonCastTransforms(CI))
8043 return I;
8044
8045 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8046 if (!DestPointee->isSized()) return 0;
8047
8048 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8049 ConstantInt *Cst;
8050 Value *X;
8051 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8052 m_ConstantInt(Cst)))) {
8053 // If the source and destination operands have the same type, see if this
8054 // is a single-index GEP.
8055 if (X->getType() == CI.getType()) {
8056 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00008057 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008058
8059 // Convert the constant to intptr type.
8060 APInt Offset = Cst->getValue();
8061 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8062
8063 // If Offset is evenly divisible by Size, we can do this xform.
8064 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8065 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008066 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008067 }
8068 }
8069 // TODO: Could handle other cases, e.g. where add is indexing into field of
8070 // struct etc.
8071 } else if (CI.getOperand(0)->hasOneUse() &&
8072 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8073 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8074 // "inttoptr+GEP" instead of "add+intptr".
8075
8076 // Get the size of the pointee type.
8077 uint64_t Size = TD->getABITypeSize(DestPointee);
8078
8079 // Convert the constant to intptr type.
8080 APInt Offset = Cst->getValue();
8081 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8082
8083 // If Offset is evenly divisible by Size, we can do this xform.
8084 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8085 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8086
8087 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8088 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008089 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008090 }
8091 }
8092 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008093}
8094
8095Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8096 // If the operands are integer typed then apply the integer transforms,
8097 // otherwise just apply the common ones.
8098 Value *Src = CI.getOperand(0);
8099 const Type *SrcTy = Src->getType();
8100 const Type *DestTy = CI.getType();
8101
8102 if (SrcTy->isInteger() && DestTy->isInteger()) {
8103 if (Instruction *Result = commonIntCastTransforms(CI))
8104 return Result;
8105 } else if (isa<PointerType>(SrcTy)) {
8106 if (Instruction *I = commonPointerCastTransforms(CI))
8107 return I;
8108 } else {
8109 if (Instruction *Result = commonCastTransforms(CI))
8110 return Result;
8111 }
8112
8113
8114 // Get rid of casts from one type to the same type. These are useless and can
8115 // be replaced by the operand.
8116 if (DestTy == Src->getType())
8117 return ReplaceInstUsesWith(CI, Src);
8118
8119 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8120 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8121 const Type *DstElTy = DstPTy->getElementType();
8122 const Type *SrcElTy = SrcPTy->getElementType();
8123
Nate Begemandf5b3612008-03-31 00:22:16 +00008124 // If the address spaces don't match, don't eliminate the bitcast, which is
8125 // required for changing types.
8126 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8127 return 0;
8128
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 // If we are casting a malloc or alloca to a pointer to a type of the same
8130 // size, rewrite the allocation instruction to allocate the "right" type.
8131 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8132 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8133 return V;
8134
8135 // If the source and destination are pointers, and this cast is equivalent
8136 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8137 // This can enhance SROA and other transforms that want type-safe pointers.
8138 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8139 unsigned NumZeros = 0;
8140 while (SrcElTy != DstElTy &&
8141 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8142 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8143 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8144 ++NumZeros;
8145 }
8146
8147 // If we found a path from the src to dest, create the getelementptr now.
8148 if (SrcElTy == DstElTy) {
8149 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008150 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8151 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008152 }
8153 }
8154
8155 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8156 if (SVI->hasOneUse()) {
8157 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8158 // a bitconvert to a vector with the same # elts.
8159 if (isa<VectorType>(DestTy) &&
8160 cast<VectorType>(DestTy)->getNumElements() ==
8161 SVI->getType()->getNumElements()) {
8162 CastInst *Tmp;
8163 // If either of the operands is a cast from CI.getType(), then
8164 // evaluating the shuffle in the casted destination's type will allow
8165 // us to eliminate at least one cast.
8166 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8167 Tmp->getOperand(0)->getType() == DestTy) ||
8168 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8169 Tmp->getOperand(0)->getType() == DestTy)) {
8170 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8171 SVI->getOperand(0), DestTy, &CI);
8172 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8173 SVI->getOperand(1), DestTy, &CI);
8174 // Return a new shuffle vector. Use the same element ID's, as we
8175 // know the vector types match #elts.
8176 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8177 }
8178 }
8179 }
8180 }
8181 return 0;
8182}
8183
8184/// GetSelectFoldableOperands - We want to turn code that looks like this:
8185/// %C = or %A, %B
8186/// %D = select %cond, %C, %A
8187/// into:
8188/// %C = select %cond, %B, 0
8189/// %D = or %A, %C
8190///
8191/// Assuming that the specified instruction is an operand to the select, return
8192/// a bitmask indicating which operands of this instruction are foldable if they
8193/// equal the other incoming value of the select.
8194///
8195static unsigned GetSelectFoldableOperands(Instruction *I) {
8196 switch (I->getOpcode()) {
8197 case Instruction::Add:
8198 case Instruction::Mul:
8199 case Instruction::And:
8200 case Instruction::Or:
8201 case Instruction::Xor:
8202 return 3; // Can fold through either operand.
8203 case Instruction::Sub: // Can only fold on the amount subtracted.
8204 case Instruction::Shl: // Can only fold on the shift amount.
8205 case Instruction::LShr:
8206 case Instruction::AShr:
8207 return 1;
8208 default:
8209 return 0; // Cannot fold
8210 }
8211}
8212
8213/// GetSelectFoldableConstant - For the same transformation as the previous
8214/// function, return the identity constant that goes into the select.
8215static Constant *GetSelectFoldableConstant(Instruction *I) {
8216 switch (I->getOpcode()) {
8217 default: assert(0 && "This cannot happen!"); abort();
8218 case Instruction::Add:
8219 case Instruction::Sub:
8220 case Instruction::Or:
8221 case Instruction::Xor:
8222 case Instruction::Shl:
8223 case Instruction::LShr:
8224 case Instruction::AShr:
8225 return Constant::getNullValue(I->getType());
8226 case Instruction::And:
8227 return Constant::getAllOnesValue(I->getType());
8228 case Instruction::Mul:
8229 return ConstantInt::get(I->getType(), 1);
8230 }
8231}
8232
8233/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8234/// have the same opcode and only one use each. Try to simplify this.
8235Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8236 Instruction *FI) {
8237 if (TI->getNumOperands() == 1) {
8238 // If this is a non-volatile load or a cast from the same type,
8239 // merge.
8240 if (TI->isCast()) {
8241 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8242 return 0;
8243 } else {
8244 return 0; // unknown unary op.
8245 }
8246
8247 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008248 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8249 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008250 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008251 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252 TI->getType());
8253 }
8254
8255 // Only handle binary operators here.
8256 if (!isa<BinaryOperator>(TI))
8257 return 0;
8258
8259 // Figure out if the operations have any operands in common.
8260 Value *MatchOp, *OtherOpT, *OtherOpF;
8261 bool MatchIsOpZero;
8262 if (TI->getOperand(0) == FI->getOperand(0)) {
8263 MatchOp = TI->getOperand(0);
8264 OtherOpT = TI->getOperand(1);
8265 OtherOpF = FI->getOperand(1);
8266 MatchIsOpZero = true;
8267 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8268 MatchOp = TI->getOperand(1);
8269 OtherOpT = TI->getOperand(0);
8270 OtherOpF = FI->getOperand(0);
8271 MatchIsOpZero = false;
8272 } else if (!TI->isCommutative()) {
8273 return 0;
8274 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8275 MatchOp = TI->getOperand(0);
8276 OtherOpT = TI->getOperand(1);
8277 OtherOpF = FI->getOperand(0);
8278 MatchIsOpZero = true;
8279 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8280 MatchOp = TI->getOperand(1);
8281 OtherOpT = TI->getOperand(0);
8282 OtherOpF = FI->getOperand(1);
8283 MatchIsOpZero = true;
8284 } else {
8285 return 0;
8286 }
8287
8288 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008289 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8290 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008291 InsertNewInstBefore(NewSI, SI);
8292
8293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8294 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008297 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008298 }
8299 assert(0 && "Shouldn't get here");
8300 return 0;
8301}
8302
8303Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8304 Value *CondVal = SI.getCondition();
8305 Value *TrueVal = SI.getTrueValue();
8306 Value *FalseVal = SI.getFalseValue();
8307
8308 // select true, X, Y -> X
8309 // select false, X, Y -> Y
8310 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8311 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8312
8313 // select C, X, X -> X
8314 if (TrueVal == FalseVal)
8315 return ReplaceInstUsesWith(SI, TrueVal);
8316
8317 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8318 return ReplaceInstUsesWith(SI, FalseVal);
8319 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8320 return ReplaceInstUsesWith(SI, TrueVal);
8321 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8322 if (isa<Constant>(TrueVal))
8323 return ReplaceInstUsesWith(SI, TrueVal);
8324 else
8325 return ReplaceInstUsesWith(SI, FalseVal);
8326 }
8327
8328 if (SI.getType() == Type::Int1Ty) {
8329 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8330 if (C->getZExtValue()) {
8331 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008332 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008333 } else {
8334 // Change: A = select B, false, C --> A = and !B, C
8335 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008336 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008337 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008338 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008339 }
8340 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8341 if (C->getZExtValue() == false) {
8342 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008343 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008344 } else {
8345 // Change: A = select B, C, true --> A = or !B, C
8346 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008348 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008349 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 }
8351 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008352
8353 // select a, b, a -> a&b
8354 // select a, a, b -> a|b
8355 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008356 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008357 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008358 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008359 }
8360
8361 // Selecting between two integer constants?
8362 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8363 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8364 // select C, 1, 0 -> zext C to int
8365 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008366 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008367 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8368 // select C, 0, 1 -> zext !C to int
8369 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008370 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008371 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008372 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008373 }
8374
8375 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8376
8377 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8378
8379 // (x <s 0) ? -1 : 0 -> ashr x, 31
8380 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8381 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8382 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8383 // The comparison constant and the result are not neccessarily the
8384 // same width. Make an all-ones value by inserting a AShr.
8385 Value *X = IC->getOperand(0);
8386 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8387 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008388 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008389 ShAmt, "ones");
8390 InsertNewInstBefore(SRA, SI);
8391
8392 // Finally, convert to the type of the select RHS. We figure out
8393 // if this requires a SExt, Trunc or BitCast based on the sizes.
8394 Instruction::CastOps opc = Instruction::BitCast;
8395 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8396 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8397 if (SRASize < SISize)
8398 opc = Instruction::SExt;
8399 else if (SRASize > SISize)
8400 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008401 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008402 }
8403 }
8404
8405
8406 // If one of the constants is zero (we know they can't both be) and we
8407 // have an icmp instruction with zero, and we have an 'and' with the
8408 // non-constant value, eliminate this whole mess. This corresponds to
8409 // cases like this: ((X & 27) ? 27 : 0)
8410 if (TrueValC->isZero() || FalseValC->isZero())
8411 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8412 cast<Constant>(IC->getOperand(1))->isNullValue())
8413 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8414 if (ICA->getOpcode() == Instruction::And &&
8415 isa<ConstantInt>(ICA->getOperand(1)) &&
8416 (ICA->getOperand(1) == TrueValC ||
8417 ICA->getOperand(1) == FalseValC) &&
8418 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8419 // Okay, now we know that everything is set up, we just don't
8420 // know whether we have a icmp_ne or icmp_eq and whether the
8421 // true or false val is the zero.
8422 bool ShouldNotVal = !TrueValC->isZero();
8423 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8424 Value *V = ICA;
8425 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008426 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 Instruction::Xor, V, ICA->getOperand(1)), SI);
8428 return ReplaceInstUsesWith(SI, V);
8429 }
8430 }
8431 }
8432
8433 // See if we are selecting two values based on a comparison of the two values.
8434 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8435 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8436 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008437 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8438 // This is not safe in general for floating point:
8439 // consider X== -0, Y== +0.
8440 // It becomes safe if either operand is a nonzero constant.
8441 ConstantFP *CFPt, *CFPf;
8442 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8443 !CFPt->getValueAPF().isZero()) ||
8444 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8445 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008446 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008447 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008448 // Transform (X != Y) ? X : Y -> X
8449 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8450 return ReplaceInstUsesWith(SI, TrueVal);
8451 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8452
8453 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8454 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008455 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8456 // This is not safe in general for floating point:
8457 // consider X== -0, Y== +0.
8458 // It becomes safe if either operand is a nonzero constant.
8459 ConstantFP *CFPt, *CFPf;
8460 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8461 !CFPt->getValueAPF().isZero()) ||
8462 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8463 !CFPf->getValueAPF().isZero()))
8464 return ReplaceInstUsesWith(SI, FalseVal);
8465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008466 // Transform (X != Y) ? Y : X -> Y
8467 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8468 return ReplaceInstUsesWith(SI, TrueVal);
8469 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8470 }
8471 }
8472
8473 // See if we are selecting two values based on a comparison of the two values.
8474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8475 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8476 // Transform (X == Y) ? X : Y -> Y
8477 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8478 return ReplaceInstUsesWith(SI, FalseVal);
8479 // Transform (X != Y) ? X : Y -> X
8480 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8481 return ReplaceInstUsesWith(SI, TrueVal);
8482 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8483
8484 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8485 // Transform (X == Y) ? Y : X -> X
8486 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8487 return ReplaceInstUsesWith(SI, FalseVal);
8488 // Transform (X != Y) ? Y : X -> Y
8489 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8490 return ReplaceInstUsesWith(SI, TrueVal);
8491 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8492 }
8493 }
8494
8495 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8496 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8497 if (TI->hasOneUse() && FI->hasOneUse()) {
8498 Instruction *AddOp = 0, *SubOp = 0;
8499
8500 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8501 if (TI->getOpcode() == FI->getOpcode())
8502 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8503 return IV;
8504
8505 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8506 // even legal for FP.
8507 if (TI->getOpcode() == Instruction::Sub &&
8508 FI->getOpcode() == Instruction::Add) {
8509 AddOp = FI; SubOp = TI;
8510 } else if (FI->getOpcode() == Instruction::Sub &&
8511 TI->getOpcode() == Instruction::Add) {
8512 AddOp = TI; SubOp = FI;
8513 }
8514
8515 if (AddOp) {
8516 Value *OtherAddOp = 0;
8517 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8518 OtherAddOp = AddOp->getOperand(1);
8519 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8520 OtherAddOp = AddOp->getOperand(0);
8521 }
8522
8523 if (OtherAddOp) {
8524 // So at this point we know we have (Y -> OtherAddOp):
8525 // select C, (add X, Y), (sub X, Z)
8526 Value *NegVal; // Compute -Z
8527 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8528 NegVal = ConstantExpr::getNeg(C);
8529 } else {
8530 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008531 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008532 }
8533
8534 Value *NewTrueOp = OtherAddOp;
8535 Value *NewFalseOp = NegVal;
8536 if (AddOp != TI)
8537 std::swap(NewTrueOp, NewFalseOp);
8538 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008539 SelectInst::Create(CondVal, NewTrueOp,
8540 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008541
8542 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008543 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008544 }
8545 }
8546 }
8547
8548 // See if we can fold the select into one of our operands.
8549 if (SI.getType()->isInteger()) {
8550 // See the comment above GetSelectFoldableOperands for a description of the
8551 // transformation we are doing here.
8552 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8553 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8554 !isa<Constant>(FalseVal))
8555 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8556 unsigned OpToFold = 0;
8557 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8558 OpToFold = 1;
8559 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8560 OpToFold = 2;
8561 }
8562
8563 if (OpToFold) {
8564 Constant *C = GetSelectFoldableConstant(TVI);
8565 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008566 SelectInst::Create(SI.getCondition(),
8567 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008568 InsertNewInstBefore(NewSel, SI);
8569 NewSel->takeName(TVI);
8570 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008571 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008572 else {
8573 assert(0 && "Unknown instruction!!");
8574 }
8575 }
8576 }
8577
8578 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8579 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8580 !isa<Constant>(TrueVal))
8581 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8582 unsigned OpToFold = 0;
8583 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8584 OpToFold = 1;
8585 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8586 OpToFold = 2;
8587 }
8588
8589 if (OpToFold) {
8590 Constant *C = GetSelectFoldableConstant(FVI);
8591 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008592 SelectInst::Create(SI.getCondition(), C,
8593 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008594 InsertNewInstBefore(NewSel, SI);
8595 NewSel->takeName(FVI);
8596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008597 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008598 else
8599 assert(0 && "Unknown instruction!!");
8600 }
8601 }
8602 }
8603
8604 if (BinaryOperator::isNot(CondVal)) {
8605 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8606 SI.setOperand(1, FalseVal);
8607 SI.setOperand(2, TrueVal);
8608 return &SI;
8609 }
8610
8611 return 0;
8612}
8613
Dan Gohman2d648bb2008-04-10 18:43:06 +00008614/// EnforceKnownAlignment - If the specified pointer points to an object that
8615/// we control, modify the object's alignment to PrefAlign. This isn't
8616/// often possible though. If alignment is important, a more reliable approach
8617/// is to simply align all global variables and allocation instructions to
8618/// their preferred alignment from the beginning.
8619///
8620static unsigned EnforceKnownAlignment(Value *V,
8621 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008622
Dan Gohman2d648bb2008-04-10 18:43:06 +00008623 User *U = dyn_cast<User>(V);
8624 if (!U) return Align;
8625
8626 switch (getOpcode(U)) {
8627 default: break;
8628 case Instruction::BitCast:
8629 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8630 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008631 // If all indexes are zero, it is just the alignment of the base pointer.
8632 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008633 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8634 if (!isa<Constant>(U->getOperand(i)) ||
8635 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008636 AllZeroOperands = false;
8637 break;
8638 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008639
8640 if (AllZeroOperands) {
8641 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008642 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008643 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008644 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008645 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008646 }
8647
8648 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8649 // If there is a large requested alignment and we can, bump up the alignment
8650 // of the global.
8651 if (!GV->isDeclaration()) {
8652 GV->setAlignment(PrefAlign);
8653 Align = PrefAlign;
8654 }
8655 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8656 // If there is a requested alignment and if this is an alloca, round up. We
8657 // don't do this for malloc, because some systems can't respect the request.
8658 if (isa<AllocaInst>(AI)) {
8659 AI->setAlignment(PrefAlign);
8660 Align = PrefAlign;
8661 }
8662 }
8663
8664 return Align;
8665}
8666
8667/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8668/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8669/// and it is more than the alignment of the ultimate object, see if we can
8670/// increase the alignment of the ultimate object, making this check succeed.
8671unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8672 unsigned PrefAlign) {
8673 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8674 sizeof(PrefAlign) * CHAR_BIT;
8675 APInt Mask = APInt::getAllOnesValue(BitWidth);
8676 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8677 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8678 unsigned TrailZ = KnownZero.countTrailingOnes();
8679 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8680
8681 if (PrefAlign > Align)
8682 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8683
8684 // We don't need to make any adjustment.
8685 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008686}
8687
Chris Lattner00ae5132008-01-13 23:50:23 +00008688Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008689 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8690 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008691 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8692 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8693
8694 if (CopyAlign < MinAlign) {
8695 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8696 return MI;
8697 }
8698
8699 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8700 // load/store.
8701 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8702 if (MemOpLength == 0) return 0;
8703
Chris Lattnerc669fb62008-01-14 00:28:35 +00008704 // Source and destination pointer types are always "i8*" for intrinsic. See
8705 // if the size is something we can handle with a single primitive load/store.
8706 // A single load+store correctly handles overlapping memory in the memmove
8707 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008708 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008709 if (Size == 0) return MI; // Delete this mem transfer.
8710
8711 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008712 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008713
Chris Lattnerc669fb62008-01-14 00:28:35 +00008714 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008715 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008716
8717 // Memcpy forces the use of i8* for the source and destination. That means
8718 // that if you're using memcpy to move one double around, you'll get a cast
8719 // from double* to i8*. We'd much rather use a double load+store rather than
8720 // an i64 load+store, here because this improves the odds that the source or
8721 // dest address will be promotable. See if we can find a better type than the
8722 // integer datatype.
8723 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8724 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8725 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8726 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8727 // down through these levels if so.
8728 while (!SrcETy->isFirstClassType()) {
8729 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8730 if (STy->getNumElements() == 1)
8731 SrcETy = STy->getElementType(0);
8732 else
8733 break;
8734 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8735 if (ATy->getNumElements() == 1)
8736 SrcETy = ATy->getElementType();
8737 else
8738 break;
8739 } else
8740 break;
8741 }
8742
8743 if (SrcETy->isFirstClassType())
8744 NewPtrTy = PointerType::getUnqual(SrcETy);
8745 }
8746 }
8747
8748
Chris Lattner00ae5132008-01-13 23:50:23 +00008749 // If the memcpy/memmove provides better alignment info than we can
8750 // infer, use it.
8751 SrcAlign = std::max(SrcAlign, CopyAlign);
8752 DstAlign = std::max(DstAlign, CopyAlign);
8753
8754 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8755 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008756 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8757 InsertNewInstBefore(L, *MI);
8758 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8759
8760 // Set the size of the copy to 0, it will be deleted on the next iteration.
8761 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8762 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008763}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008764
Chris Lattner5af8a912008-04-30 06:39:11 +00008765Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8766 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8767 if (MI->getAlignment()->getZExtValue() < Alignment) {
8768 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8769 return MI;
8770 }
8771
8772 // Extract the length and alignment and fill if they are constant.
8773 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8774 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8775 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8776 return 0;
8777 uint64_t Len = LenC->getZExtValue();
8778 Alignment = MI->getAlignment()->getZExtValue();
8779
8780 // If the length is zero, this is a no-op
8781 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8782
8783 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8784 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8785 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8786
8787 Value *Dest = MI->getDest();
8788 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8789
8790 // Alignment 0 is identity for alignment 1 for memset, but not store.
8791 if (Alignment == 0) Alignment = 1;
8792
8793 // Extract the fill value and store.
8794 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8795 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8796 Alignment), *MI);
8797
8798 // Set the size of the copy to 0, it will be deleted on the next iteration.
8799 MI->setLength(Constant::getNullValue(LenC->getType()));
8800 return MI;
8801 }
8802
8803 return 0;
8804}
8805
8806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008807/// visitCallInst - CallInst simplification. This mostly only handles folding
8808/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8809/// the heavy lifting.
8810///
8811Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8813 if (!II) return visitCallSite(&CI);
8814
8815 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8816 // visitCallSite.
8817 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8818 bool Changed = false;
8819
8820 // memmove/cpy/set of zero bytes is a noop.
8821 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8822 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8823
8824 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8825 if (CI->getZExtValue() == 1) {
8826 // Replace the instruction with just byte operations. We would
8827 // transform other cases to loads/stores, but we don't know if
8828 // alignment is sufficient.
8829 }
8830 }
8831
8832 // If we have a memmove and the source operation is a constant global,
8833 // then the source and dest pointers can't alias, so we can change this
8834 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008835 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008836 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8837 if (GVSrc->isConstant()) {
8838 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008839 Intrinsic::ID MemCpyID;
8840 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8841 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008842 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008843 MemCpyID = Intrinsic::memcpy_i64;
8844 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008845 Changed = true;
8846 }
8847 }
8848
8849 // If we can determine a pointer alignment that is bigger than currently
8850 // set, update the alignment.
8851 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008852 if (Instruction *I = SimplifyMemTransfer(MI))
8853 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008854 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8855 if (Instruction *I = SimplifyMemSet(MSI))
8856 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008857 }
8858
8859 if (Changed) return II;
8860 } else {
8861 switch (II->getIntrinsicID()) {
8862 default: break;
8863 case Intrinsic::ppc_altivec_lvx:
8864 case Intrinsic::ppc_altivec_lvxl:
8865 case Intrinsic::x86_sse_loadu_ps:
8866 case Intrinsic::x86_sse2_loadu_pd:
8867 case Intrinsic::x86_sse2_loadu_dq:
8868 // Turn PPC lvx -> load if the pointer is known aligned.
8869 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008870 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008871 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8872 PointerType::getUnqual(II->getType()),
8873 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008874 return new LoadInst(Ptr);
8875 }
8876 break;
8877 case Intrinsic::ppc_altivec_stvx:
8878 case Intrinsic::ppc_altivec_stvxl:
8879 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008880 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008881 const Type *OpPtrTy =
8882 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008883 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008884 return new StoreInst(II->getOperand(1), Ptr);
8885 }
8886 break;
8887 case Intrinsic::x86_sse_storeu_ps:
8888 case Intrinsic::x86_sse2_storeu_pd:
8889 case Intrinsic::x86_sse2_storeu_dq:
8890 case Intrinsic::x86_sse2_storel_dq:
8891 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008892 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008893 const Type *OpPtrTy =
8894 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008895 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008896 return new StoreInst(II->getOperand(2), Ptr);
8897 }
8898 break;
8899
8900 case Intrinsic::x86_sse_cvttss2si: {
8901 // These intrinsics only demands the 0th element of its input vector. If
8902 // we can simplify the input based on that, do so now.
8903 uint64_t UndefElts;
8904 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8905 UndefElts)) {
8906 II->setOperand(1, V);
8907 return II;
8908 }
8909 break;
8910 }
8911
8912 case Intrinsic::ppc_altivec_vperm:
8913 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8914 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8915 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8916
8917 // Check that all of the elements are integer constants or undefs.
8918 bool AllEltsOk = true;
8919 for (unsigned i = 0; i != 16; ++i) {
8920 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8921 !isa<UndefValue>(Mask->getOperand(i))) {
8922 AllEltsOk = false;
8923 break;
8924 }
8925 }
8926
8927 if (AllEltsOk) {
8928 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008929 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8930 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008931 Value *Result = UndefValue::get(Op0->getType());
8932
8933 // Only extract each element once.
8934 Value *ExtractedElts[32];
8935 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8936
8937 for (unsigned i = 0; i != 16; ++i) {
8938 if (isa<UndefValue>(Mask->getOperand(i)))
8939 continue;
8940 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8941 Idx &= 31; // Match the hardware behavior.
8942
8943 if (ExtractedElts[Idx] == 0) {
8944 Instruction *Elt =
8945 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8946 InsertNewInstBefore(Elt, CI);
8947 ExtractedElts[Idx] = Elt;
8948 }
8949
8950 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008951 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8952 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008953 InsertNewInstBefore(cast<Instruction>(Result), CI);
8954 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008955 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008956 }
8957 }
8958 break;
8959
8960 case Intrinsic::stackrestore: {
8961 // If the save is right next to the restore, remove the restore. This can
8962 // happen when variable allocas are DCE'd.
8963 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8964 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8965 BasicBlock::iterator BI = SS;
8966 if (&*++BI == II)
8967 return EraseInstFromFunction(CI);
8968 }
8969 }
8970
Chris Lattner416d91c2008-02-18 06:12:38 +00008971 // Scan down this block to see if there is another stack restore in the
8972 // same block without an intervening call/alloca.
8973 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008974 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008975 bool CannotRemove = false;
8976 for (++BI; &*BI != TI; ++BI) {
8977 if (isa<AllocaInst>(BI)) {
8978 CannotRemove = true;
8979 break;
8980 }
8981 if (isa<CallInst>(BI)) {
8982 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008983 CannotRemove = true;
8984 break;
8985 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008986 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008987 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008988 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008989 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008990
8991 // If the stack restore is in a return/unwind block and if there are no
8992 // allocas or calls between the restore and the return, nuke the restore.
8993 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8994 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008995 break;
8996 }
8997 }
8998 }
8999
9000 return visitCallSite(II);
9001}
9002
9003// InvokeInst simplification
9004//
9005Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9006 return visitCallSite(&II);
9007}
9008
Dale Johannesen96021832008-04-25 21:16:07 +00009009/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9010/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009011static bool isSafeToEliminateVarargsCast(const CallSite CS,
9012 const CastInst * const CI,
9013 const TargetData * const TD,
9014 const int ix) {
9015 if (!CI->isLosslessCast())
9016 return false;
9017
9018 // The size of ByVal arguments is derived from the type, so we
9019 // can't change to a type with a different size. If the size were
9020 // passed explicitly we could avoid this check.
9021 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9022 return true;
9023
9024 const Type* SrcTy =
9025 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9026 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9027 if (!SrcTy->isSized() || !DstTy->isSized())
9028 return false;
9029 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9030 return false;
9031 return true;
9032}
9033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009034// visitCallSite - Improvements for call and invoke instructions.
9035//
9036Instruction *InstCombiner::visitCallSite(CallSite CS) {
9037 bool Changed = false;
9038
9039 // If the callee is a constexpr cast of a function, attempt to move the cast
9040 // to the arguments of the call/invoke.
9041 if (transformConstExprCastCall(CS)) return 0;
9042
9043 Value *Callee = CS.getCalledValue();
9044
9045 if (Function *CalleeF = dyn_cast<Function>(Callee))
9046 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9047 Instruction *OldCall = CS.getInstruction();
9048 // If the call and callee calling conventions don't match, this call must
9049 // be unreachable, as the call is undefined.
9050 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009051 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9052 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009053 if (!OldCall->use_empty())
9054 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9055 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9056 return EraseInstFromFunction(*OldCall);
9057 return 0;
9058 }
9059
9060 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9061 // This instruction is not reachable, just remove it. We insert a store to
9062 // undef so that we know that this code is not reachable, despite the fact
9063 // that we can't modify the CFG here.
9064 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009065 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009066 CS.getInstruction());
9067
9068 if (!CS.getInstruction()->use_empty())
9069 CS.getInstruction()->
9070 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9071
9072 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9073 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009074 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9075 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 }
9077 return EraseInstFromFunction(*CS.getInstruction());
9078 }
9079
Duncan Sands74833f22007-09-17 10:26:40 +00009080 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9081 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9082 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9083 return transformCallThroughTrampoline(CS);
9084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009085 const PointerType *PTy = cast<PointerType>(Callee->getType());
9086 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9087 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009088 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009089 // See if we can optimize any arguments passed through the varargs area of
9090 // the call.
9091 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009092 E = CS.arg_end(); I != E; ++I, ++ix) {
9093 CastInst *CI = dyn_cast<CastInst>(*I);
9094 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9095 *I = CI->getOperand(0);
9096 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009097 }
Dale Johannesen35615462008-04-23 18:34:37 +00009098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009099 }
9100
Duncan Sands2937e352007-12-19 21:13:37 +00009101 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009102 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009103 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009104 Changed = true;
9105 }
9106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009107 return Changed ? CS.getInstruction() : 0;
9108}
9109
9110// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9111// attempt to move the cast to the arguments of the call/invoke.
9112//
9113bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9114 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9115 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9116 if (CE->getOpcode() != Instruction::BitCast ||
9117 !isa<Function>(CE->getOperand(0)))
9118 return false;
9119 Function *Callee = cast<Function>(CE->getOperand(0));
9120 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009121 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009122
9123 // Okay, this is a cast from a function to a different type. Unless doing so
9124 // would cause a type conversion of one of our arguments, change this call to
9125 // be a direct call with arguments casted to the appropriate types.
9126 //
9127 const FunctionType *FT = Callee->getFunctionType();
9128 const Type *OldRetTy = Caller->getType();
9129
Devang Pateld091d322008-03-11 18:04:06 +00009130 if (isa<StructType>(FT->getReturnType()))
9131 return false; // TODO: Handle multiple return values.
9132
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009133 // Check to see if we are changing the return type...
9134 if (OldRetTy != FT->getReturnType()) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009135 if (Callee->isDeclaration() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009136 // Conversion is ok if changing from pointer to int of same size.
9137 !(isa<PointerType>(FT->getReturnType()) &&
9138 TD->getIntPtrType() == OldRetTy))
9139 return false; // Cannot transform this return value.
9140
Duncan Sands5c489582008-01-06 10:12:28 +00009141 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009142 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00009143 FT->getReturnType() != Type::VoidTy &&
9144 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009145 return false; // Cannot transform this return value.
9146
Chris Lattner1c8733e2008-03-12 17:45:29 +00009147 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9148 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009149 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9150 return false; // Attribute not compatible with transformed value.
9151 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009153 // If the callsite is an invoke instruction, and the return value is used by
9154 // a PHI node in a successor, we cannot change the return type of the call
9155 // because there is no place to put the cast instruction (without breaking
9156 // the critical edge). Bail out in this case.
9157 if (!Caller->use_empty())
9158 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9159 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9160 UI != E; ++UI)
9161 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9162 if (PN->getParent() == II->getNormalDest() ||
9163 PN->getParent() == II->getUnwindDest())
9164 return false;
9165 }
9166
9167 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9168 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9169
9170 CallSite::arg_iterator AI = CS.arg_begin();
9171 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9172 const Type *ParamTy = FT->getParamType(i);
9173 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009174
9175 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009176 return false; // Cannot transform this parameter value.
9177
Chris Lattner1c8733e2008-03-12 17:45:29 +00009178 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9179 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009181 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00009182 // Some conversions are safe even if we do not have a body.
9183 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009184 bool isConvertible = ActTy == ParamTy ||
9185 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9186 (ParamTy->isInteger() && ActTy->isInteger() &&
9187 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9188 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9189 && c->getValue().isStrictlyPositive());
9190 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009191 }
9192
9193 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9194 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009195 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009196
Chris Lattner1c8733e2008-03-12 17:45:29 +00009197 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9198 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009199 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009200 // won't be dropping them. Check that these extra arguments have attributes
9201 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009202 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9203 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009204 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009205 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009206 if (PAttrs & ParamAttr::VarArgsIncompatible)
9207 return false;
9208 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009209
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009210 // Okay, we decided that this is a safe thing to do: go ahead and start
9211 // inserting cast instructions as necessary...
9212 std::vector<Value*> Args;
9213 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009214 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009215 attrVec.reserve(NumCommonArgs);
9216
9217 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009218 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009219
9220 // If the return value is not being used, the type may not be compatible
9221 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009222 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00009223
9224 // Add the new return attributes.
9225 if (RAttrs)
9226 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009227
9228 AI = CS.arg_begin();
9229 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9230 const Type *ParamTy = FT->getParamType(i);
9231 if ((*AI)->getType() == ParamTy) {
9232 Args.push_back(*AI);
9233 } else {
9234 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9235 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009236 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009237 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9238 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009239
9240 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009241 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009242 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009243 }
9244
9245 // If the function takes more arguments than the call was taking, add them
9246 // now...
9247 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9248 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9249
9250 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009251 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009252 if (!FT->isVarArg()) {
9253 cerr << "WARNING: While resolving call to function '"
9254 << Callee->getName() << "' arguments were dropped!\n";
9255 } else {
9256 // Add all of the arguments in their promoted form to the arg list...
9257 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9258 const Type *PTy = getPromotedType((*AI)->getType());
9259 if (PTy != (*AI)->getType()) {
9260 // Must promote to pass through va_arg area!
9261 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9262 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009263 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009264 InsertNewInstBefore(Cast, *Caller);
9265 Args.push_back(Cast);
9266 } else {
9267 Args.push_back(*AI);
9268 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009269
Duncan Sands4ced1f82008-01-13 08:02:44 +00009270 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009271 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009272 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009274 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009275 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009276
9277 if (FT->getReturnType() == Type::VoidTy)
9278 Caller->setName(""); // Void type should not have a name.
9279
Chris Lattner1c8733e2008-03-12 17:45:29 +00009280 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009281
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009282 Instruction *NC;
9283 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009284 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009285 Args.begin(), Args.end(),
9286 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009287 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009288 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009289 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009290 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9291 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009292 CallInst *CI = cast<CallInst>(Caller);
9293 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009295 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009296 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009297 }
9298
9299 // Insert a cast of the return type as necessary.
9300 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009301 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009302 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009303 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009304 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009305 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009306
9307 // If this is an invoke instruction, we should insert it after the first
9308 // non-phi, instruction in the normal successor block.
9309 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9310 BasicBlock::iterator I = II->getNormalDest()->begin();
9311 while (isa<PHINode>(I)) ++I;
9312 InsertNewInstBefore(NC, *I);
9313 } else {
9314 // Otherwise, it's a call, just insert cast right after the call instr
9315 InsertNewInstBefore(NC, *Caller);
9316 }
9317 AddUsersToWorkList(*Caller);
9318 } else {
9319 NV = UndefValue::get(Caller->getType());
9320 }
9321 }
9322
9323 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9324 Caller->replaceAllUsesWith(NV);
9325 Caller->eraseFromParent();
9326 RemoveFromWorkList(Caller);
9327 return true;
9328}
9329
Duncan Sands74833f22007-09-17 10:26:40 +00009330// transformCallThroughTrampoline - Turn a call to a function created by the
9331// init_trampoline intrinsic into a direct call to the underlying function.
9332//
9333Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9334 Value *Callee = CS.getCalledValue();
9335 const PointerType *PTy = cast<PointerType>(Callee->getType());
9336 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009337 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009338
9339 // If the call already has the 'nest' attribute somewhere then give up -
9340 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009341 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009342 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009343
9344 IntrinsicInst *Tramp =
9345 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9346
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009347 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009348 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9349 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9350
Chris Lattner1c8733e2008-03-12 17:45:29 +00009351 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9352 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009353 unsigned NestIdx = 1;
9354 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009355 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009356
9357 // Look for a parameter marked with the 'nest' attribute.
9358 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9359 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009360 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009361 // Record the parameter type and any other attributes.
9362 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009363 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009364 break;
9365 }
9366
9367 if (NestTy) {
9368 Instruction *Caller = CS.getInstruction();
9369 std::vector<Value*> NewArgs;
9370 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9371
Chris Lattner1c8733e2008-03-12 17:45:29 +00009372 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9373 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009374
Duncan Sands74833f22007-09-17 10:26:40 +00009375 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009376 // mean appending it. Likewise for attributes.
9377
9378 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009379 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9380 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009381
Duncan Sands74833f22007-09-17 10:26:40 +00009382 {
9383 unsigned Idx = 1;
9384 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9385 do {
9386 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009387 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009388 Value *NestVal = Tramp->getOperand(3);
9389 if (NestVal->getType() != NestTy)
9390 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9391 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009392 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009393 }
9394
9395 if (I == E)
9396 break;
9397
Duncan Sands48b81112008-01-14 19:52:09 +00009398 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009399 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009400 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009401 NewAttrs.push_back
9402 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009403
9404 ++Idx, ++I;
9405 } while (1);
9406 }
9407
9408 // The trampoline may have been bitcast to a bogus type (FTy).
9409 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009410 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009411
Duncan Sands74833f22007-09-17 10:26:40 +00009412 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009413 NewTypes.reserve(FTy->getNumParams()+1);
9414
Duncan Sands74833f22007-09-17 10:26:40 +00009415 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009416 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009417 {
9418 unsigned Idx = 1;
9419 FunctionType::param_iterator I = FTy->param_begin(),
9420 E = FTy->param_end();
9421
9422 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009423 if (Idx == NestIdx)
9424 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009425 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009426
9427 if (I == E)
9428 break;
9429
Duncan Sands48b81112008-01-14 19:52:09 +00009430 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009431 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009432
9433 ++Idx, ++I;
9434 } while (1);
9435 }
9436
9437 // Replace the trampoline call with a direct call. Let the generic
9438 // code sort out any function type mismatches.
9439 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009440 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009441 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9442 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009443 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009444
9445 Instruction *NewCaller;
9446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009447 NewCaller = InvokeInst::Create(NewCallee,
9448 II->getNormalDest(), II->getUnwindDest(),
9449 NewArgs.begin(), NewArgs.end(),
9450 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009451 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009452 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009453 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009454 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9455 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009456 if (cast<CallInst>(Caller)->isTailCall())
9457 cast<CallInst>(NewCaller)->setTailCall();
9458 cast<CallInst>(NewCaller)->
9459 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009460 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009461 }
9462 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9463 Caller->replaceAllUsesWith(NewCaller);
9464 Caller->eraseFromParent();
9465 RemoveFromWorkList(Caller);
9466 return 0;
9467 }
9468 }
9469
9470 // Replace the trampoline call with a direct call. Since there is no 'nest'
9471 // parameter, there is no need to adjust the argument list. Let the generic
9472 // code sort out any function type mismatches.
9473 Constant *NewCallee =
9474 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9475 CS.setCalledFunction(NewCallee);
9476 return CS.getInstruction();
9477}
9478
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009479/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9480/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9481/// and a single binop.
9482Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9483 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9484 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9485 isa<CmpInst>(FirstInst));
9486 unsigned Opc = FirstInst->getOpcode();
9487 Value *LHSVal = FirstInst->getOperand(0);
9488 Value *RHSVal = FirstInst->getOperand(1);
9489
9490 const Type *LHSType = LHSVal->getType();
9491 const Type *RHSType = RHSVal->getType();
9492
9493 // Scan to see if all operands are the same opcode, all have one use, and all
9494 // kill their operands (i.e. the operands have one use).
9495 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9496 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9497 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9498 // Verify type of the LHS matches so we don't fold cmp's of different
9499 // types or GEP's with different index types.
9500 I->getOperand(0)->getType() != LHSType ||
9501 I->getOperand(1)->getType() != RHSType)
9502 return 0;
9503
9504 // If they are CmpInst instructions, check their predicates
9505 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9506 if (cast<CmpInst>(I)->getPredicate() !=
9507 cast<CmpInst>(FirstInst)->getPredicate())
9508 return 0;
9509
9510 // Keep track of which operand needs a phi node.
9511 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9512 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9513 }
9514
9515 // Otherwise, this is safe to transform, determine if it is profitable.
9516
9517 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9518 // Indexes are often folded into load/store instructions, so we don't want to
9519 // hide them behind a phi.
9520 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9521 return 0;
9522
9523 Value *InLHS = FirstInst->getOperand(0);
9524 Value *InRHS = FirstInst->getOperand(1);
9525 PHINode *NewLHS = 0, *NewRHS = 0;
9526 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009527 NewLHS = PHINode::Create(LHSType,
9528 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009529 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9530 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9531 InsertNewInstBefore(NewLHS, PN);
9532 LHSVal = NewLHS;
9533 }
9534
9535 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009536 NewRHS = PHINode::Create(RHSType,
9537 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009538 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9539 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9540 InsertNewInstBefore(NewRHS, PN);
9541 RHSVal = NewRHS;
9542 }
9543
9544 // Add all operands to the new PHIs.
9545 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9546 if (NewLHS) {
9547 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9548 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9549 }
9550 if (NewRHS) {
9551 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9552 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9553 }
9554 }
9555
9556 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009557 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009558 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009559 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009560 RHSVal);
9561 else {
9562 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009563 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009564 }
9565}
9566
9567/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9568/// of the block that defines it. This means that it must be obvious the value
9569/// of the load is not changed from the point of the load to the end of the
9570/// block it is in.
9571///
9572/// Finally, it is safe, but not profitable, to sink a load targetting a
9573/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9574/// to a register.
9575static bool isSafeToSinkLoad(LoadInst *L) {
9576 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9577
9578 for (++BBI; BBI != E; ++BBI)
9579 if (BBI->mayWriteToMemory())
9580 return false;
9581
9582 // Check for non-address taken alloca. If not address-taken already, it isn't
9583 // profitable to do this xform.
9584 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9585 bool isAddressTaken = false;
9586 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9587 UI != E; ++UI) {
9588 if (isa<LoadInst>(UI)) continue;
9589 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9590 // If storing TO the alloca, then the address isn't taken.
9591 if (SI->getOperand(1) == AI) continue;
9592 }
9593 isAddressTaken = true;
9594 break;
9595 }
9596
9597 if (!isAddressTaken)
9598 return false;
9599 }
9600
9601 return true;
9602}
9603
9604
9605// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9606// operator and they all are only used by the PHI, PHI together their
9607// inputs, and do the operation once, to the result of the PHI.
9608Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9609 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9610
9611 // Scan the instruction, looking for input operations that can be folded away.
9612 // If all input operands to the phi are the same instruction (e.g. a cast from
9613 // the same type or "+42") we can pull the operation through the PHI, reducing
9614 // code size and simplifying code.
9615 Constant *ConstantOp = 0;
9616 const Type *CastSrcTy = 0;
9617 bool isVolatile = false;
9618 if (isa<CastInst>(FirstInst)) {
9619 CastSrcTy = FirstInst->getOperand(0)->getType();
9620 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9621 // Can fold binop, compare or shift here if the RHS is a constant,
9622 // otherwise call FoldPHIArgBinOpIntoPHI.
9623 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9624 if (ConstantOp == 0)
9625 return FoldPHIArgBinOpIntoPHI(PN);
9626 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9627 isVolatile = LI->isVolatile();
9628 // We can't sink the load if the loaded value could be modified between the
9629 // load and the PHI.
9630 if (LI->getParent() != PN.getIncomingBlock(0) ||
9631 !isSafeToSinkLoad(LI))
9632 return 0;
9633 } else if (isa<GetElementPtrInst>(FirstInst)) {
9634 if (FirstInst->getNumOperands() == 2)
9635 return FoldPHIArgBinOpIntoPHI(PN);
9636 // Can't handle general GEPs yet.
9637 return 0;
9638 } else {
9639 return 0; // Cannot fold this operation.
9640 }
9641
9642 // Check to see if all arguments are the same operation.
9643 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9644 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9645 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9646 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9647 return 0;
9648 if (CastSrcTy) {
9649 if (I->getOperand(0)->getType() != CastSrcTy)
9650 return 0; // Cast operation must match.
9651 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9652 // We can't sink the load if the loaded value could be modified between
9653 // the load and the PHI.
9654 if (LI->isVolatile() != isVolatile ||
9655 LI->getParent() != PN.getIncomingBlock(i) ||
9656 !isSafeToSinkLoad(LI))
9657 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009658
9659 // If the PHI is volatile and its block has multiple successors, sinking
9660 // it would remove a load of the volatile value from the path through the
9661 // other successor.
9662 if (isVolatile &&
9663 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9664 return 0;
9665
9666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009667 } else if (I->getOperand(1) != ConstantOp) {
9668 return 0;
9669 }
9670 }
9671
9672 // Okay, they are all the same operation. Create a new PHI node of the
9673 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009674 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9675 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009676 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9677
9678 Value *InVal = FirstInst->getOperand(0);
9679 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9680
9681 // Add all operands to the new PHI.
9682 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9683 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9684 if (NewInVal != InVal)
9685 InVal = 0;
9686 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9687 }
9688
9689 Value *PhiVal;
9690 if (InVal) {
9691 // The new PHI unions all of the same values together. This is really
9692 // common, so we handle it intelligently here for compile-time speed.
9693 PhiVal = InVal;
9694 delete NewPN;
9695 } else {
9696 InsertNewInstBefore(NewPN, PN);
9697 PhiVal = NewPN;
9698 }
9699
9700 // Insert and return the new operation.
9701 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009702 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009703 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009704 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009705 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009706 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009707 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009708 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9709
9710 // If this was a volatile load that we are merging, make sure to loop through
9711 // and mark all the input loads as non-volatile. If we don't do this, we will
9712 // insert a new volatile load and the old ones will not be deletable.
9713 if (isVolatile)
9714 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9715 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9716
9717 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009718}
9719
9720/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9721/// that is dead.
9722static bool DeadPHICycle(PHINode *PN,
9723 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9724 if (PN->use_empty()) return true;
9725 if (!PN->hasOneUse()) return false;
9726
9727 // Remember this node, and if we find the cycle, return.
9728 if (!PotentiallyDeadPHIs.insert(PN))
9729 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009730
9731 // Don't scan crazily complex things.
9732 if (PotentiallyDeadPHIs.size() == 16)
9733 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009734
9735 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9736 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9737
9738 return false;
9739}
9740
Chris Lattner27b695d2007-11-06 21:52:06 +00009741/// PHIsEqualValue - Return true if this phi node is always equal to
9742/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9743/// z = some value; x = phi (y, z); y = phi (x, z)
9744static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9745 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9746 // See if we already saw this PHI node.
9747 if (!ValueEqualPHIs.insert(PN))
9748 return true;
9749
9750 // Don't scan crazily complex things.
9751 if (ValueEqualPHIs.size() == 16)
9752 return false;
9753
9754 // Scan the operands to see if they are either phi nodes or are equal to
9755 // the value.
9756 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9757 Value *Op = PN->getIncomingValue(i);
9758 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9759 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9760 return false;
9761 } else if (Op != NonPhiInVal)
9762 return false;
9763 }
9764
9765 return true;
9766}
9767
9768
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009769// PHINode simplification
9770//
9771Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9772 // If LCSSA is around, don't mess with Phi nodes
9773 if (MustPreserveLCSSA) return 0;
9774
9775 if (Value *V = PN.hasConstantValue())
9776 return ReplaceInstUsesWith(PN, V);
9777
9778 // If all PHI operands are the same operation, pull them through the PHI,
9779 // reducing code size.
9780 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9781 PN.getIncomingValue(0)->hasOneUse())
9782 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9783 return Result;
9784
9785 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9786 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9787 // PHI)... break the cycle.
9788 if (PN.hasOneUse()) {
9789 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9790 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9791 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9792 PotentiallyDeadPHIs.insert(&PN);
9793 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9794 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9795 }
9796
9797 // If this phi has a single use, and if that use just computes a value for
9798 // the next iteration of a loop, delete the phi. This occurs with unused
9799 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9800 // common case here is good because the only other things that catch this
9801 // are induction variable analysis (sometimes) and ADCE, which is only run
9802 // late.
9803 if (PHIUser->hasOneUse() &&
9804 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9805 PHIUser->use_back() == &PN) {
9806 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9807 }
9808 }
9809
Chris Lattner27b695d2007-11-06 21:52:06 +00009810 // We sometimes end up with phi cycles that non-obviously end up being the
9811 // same value, for example:
9812 // z = some value; x = phi (y, z); y = phi (x, z)
9813 // where the phi nodes don't necessarily need to be in the same block. Do a
9814 // quick check to see if the PHI node only contains a single non-phi value, if
9815 // so, scan to see if the phi cycle is actually equal to that value.
9816 {
9817 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9818 // Scan for the first non-phi operand.
9819 while (InValNo != NumOperandVals &&
9820 isa<PHINode>(PN.getIncomingValue(InValNo)))
9821 ++InValNo;
9822
9823 if (InValNo != NumOperandVals) {
9824 Value *NonPhiInVal = PN.getOperand(InValNo);
9825
9826 // Scan the rest of the operands to see if there are any conflicts, if so
9827 // there is no need to recursively scan other phis.
9828 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9829 Value *OpVal = PN.getIncomingValue(InValNo);
9830 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9831 break;
9832 }
9833
9834 // If we scanned over all operands, then we have one unique value plus
9835 // phi values. Scan PHI nodes to see if they all merge in each other or
9836 // the value.
9837 if (InValNo == NumOperandVals) {
9838 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9839 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9840 return ReplaceInstUsesWith(PN, NonPhiInVal);
9841 }
9842 }
9843 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009844 return 0;
9845}
9846
9847static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9848 Instruction *InsertPoint,
9849 InstCombiner *IC) {
9850 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9851 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9852 // We must cast correctly to the pointer type. Ensure that we
9853 // sign extend the integer value if it is smaller as this is
9854 // used for address computation.
9855 Instruction::CastOps opcode =
9856 (VTySize < PtrSize ? Instruction::SExt :
9857 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9858 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9859}
9860
9861
9862Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9863 Value *PtrOp = GEP.getOperand(0);
9864 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9865 // If so, eliminate the noop.
9866 if (GEP.getNumOperands() == 1)
9867 return ReplaceInstUsesWith(GEP, PtrOp);
9868
9869 if (isa<UndefValue>(GEP.getOperand(0)))
9870 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9871
9872 bool HasZeroPointerIndex = false;
9873 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9874 HasZeroPointerIndex = C->isNullValue();
9875
9876 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9877 return ReplaceInstUsesWith(GEP, PtrOp);
9878
9879 // Eliminate unneeded casts for indices.
9880 bool MadeChange = false;
9881
9882 gep_type_iterator GTI = gep_type_begin(GEP);
9883 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9884 if (isa<SequentialType>(*GTI)) {
9885 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9886 if (CI->getOpcode() == Instruction::ZExt ||
9887 CI->getOpcode() == Instruction::SExt) {
9888 const Type *SrcTy = CI->getOperand(0)->getType();
9889 // We can eliminate a cast from i32 to i64 iff the target
9890 // is a 32-bit pointer target.
9891 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9892 MadeChange = true;
9893 GEP.setOperand(i, CI->getOperand(0));
9894 }
9895 }
9896 }
9897 // If we are using a wider index than needed for this platform, shrink it
9898 // to what we need. If the incoming value needs a cast instruction,
9899 // insert it. This explicit cast can make subsequent optimizations more
9900 // obvious.
9901 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009902 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009903 if (Constant *C = dyn_cast<Constant>(Op)) {
9904 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9905 MadeChange = true;
9906 } else {
9907 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9908 GEP);
9909 GEP.setOperand(i, Op);
9910 MadeChange = true;
9911 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009912 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009913 }
9914 }
9915 if (MadeChange) return &GEP;
9916
9917 // If this GEP instruction doesn't move the pointer, and if the input operand
9918 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9919 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009920 if (GEP.hasAllZeroIndices()) {
9921 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9922 // If the bitcast is of an allocation, and the allocation will be
9923 // converted to match the type of the cast, don't touch this.
9924 if (isa<AllocationInst>(BCI->getOperand(0))) {
9925 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009926 if (Instruction *I = visitBitCast(*BCI)) {
9927 if (I != BCI) {
9928 I->takeName(BCI);
9929 BCI->getParent()->getInstList().insert(BCI, I);
9930 ReplaceInstUsesWith(*BCI, I);
9931 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009932 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009933 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009934 }
9935 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9936 }
9937 }
9938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009939 // Combine Indices - If the source pointer to this getelementptr instruction
9940 // is a getelementptr instruction, combine the indices of the two
9941 // getelementptr instructions into a single instruction.
9942 //
9943 SmallVector<Value*, 8> SrcGEPOperands;
9944 if (User *Src = dyn_castGetElementPtr(PtrOp))
9945 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9946
9947 if (!SrcGEPOperands.empty()) {
9948 // Note that if our source is a gep chain itself that we wait for that
9949 // chain to be resolved before we perform this transformation. This
9950 // avoids us creating a TON of code in some cases.
9951 //
9952 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9953 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9954 return 0; // Wait until our source is folded to completion.
9955
9956 SmallVector<Value*, 8> Indices;
9957
9958 // Find out whether the last index in the source GEP is a sequential idx.
9959 bool EndsWithSequential = false;
9960 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9961 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9962 EndsWithSequential = !isa<StructType>(*I);
9963
9964 // Can we combine the two pointer arithmetics offsets?
9965 if (EndsWithSequential) {
9966 // Replace: gep (gep %P, long B), long A, ...
9967 // With: T = long A+B; gep %P, T, ...
9968 //
9969 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9970 if (SO1 == Constant::getNullValue(SO1->getType())) {
9971 Sum = GO1;
9972 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9973 Sum = SO1;
9974 } else {
9975 // If they aren't the same type, convert both to an integer of the
9976 // target's pointer size.
9977 if (SO1->getType() != GO1->getType()) {
9978 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9979 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9980 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9981 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9982 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009983 unsigned PS = TD->getPointerSizeInBits();
9984 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009985 // Convert GO1 to SO1's type.
9986 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9987
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009988 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009989 // Convert SO1 to GO1's type.
9990 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9991 } else {
9992 const Type *PT = TD->getIntPtrType();
9993 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9994 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9995 }
9996 }
9997 }
9998 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9999 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10000 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010001 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010002 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10003 }
10004 }
10005
10006 // Recycle the GEP we already have if possible.
10007 if (SrcGEPOperands.size() == 2) {
10008 GEP.setOperand(0, SrcGEPOperands[0]);
10009 GEP.setOperand(1, Sum);
10010 return &GEP;
10011 } else {
10012 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10013 SrcGEPOperands.end()-1);
10014 Indices.push_back(Sum);
10015 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10016 }
10017 } else if (isa<Constant>(*GEP.idx_begin()) &&
10018 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10019 SrcGEPOperands.size() != 1) {
10020 // Otherwise we can do the fold if the first index of the GEP is a zero
10021 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10022 SrcGEPOperands.end());
10023 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10024 }
10025
10026 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010027 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10028 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010029
10030 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10031 // GEP of global variable. If all of the indices for this GEP are
10032 // constants, we can promote this to a constexpr instead of an instruction.
10033
10034 // Scan for nonconstants...
10035 SmallVector<Constant*, 8> Indices;
10036 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10037 for (; I != E && isa<Constant>(*I); ++I)
10038 Indices.push_back(cast<Constant>(*I));
10039
10040 if (I == E) { // If they are all constants...
10041 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10042 &Indices[0],Indices.size());
10043
10044 // Replace all uses of the GEP with the new constexpr...
10045 return ReplaceInstUsesWith(GEP, CE);
10046 }
10047 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10048 if (!isa<PointerType>(X->getType())) {
10049 // Not interesting. Source pointer must be a cast from pointer.
10050 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010051 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10052 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010053 //
10054 // This occurs when the program declares an array extern like "int X[];"
10055 //
10056 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10057 const PointerType *XTy = cast<PointerType>(X->getType());
10058 if (const ArrayType *XATy =
10059 dyn_cast<ArrayType>(XTy->getElementType()))
10060 if (const ArrayType *CATy =
10061 dyn_cast<ArrayType>(CPTy->getElementType()))
10062 if (CATy->getElementType() == XATy->getElementType()) {
10063 // At this point, we know that the cast source type is a pointer
10064 // to an array of the same type as the destination pointer
10065 // array. Because the array type is never stepped over (there
10066 // is a leading zero) we can fold the cast into this GEP.
10067 GEP.setOperand(0, X);
10068 return &GEP;
10069 }
10070 } else if (GEP.getNumOperands() == 2) {
10071 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010072 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10073 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10075 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10076 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010077 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10078 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010079 Value *Idx[2];
10080 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10081 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010083 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010084 // V and GEP are both pointer types --> BitCast
10085 return new BitCastInst(V, GEP.getType());
10086 }
10087
10088 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010089 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010090 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010091 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010092
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010093 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010094 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010095 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010096
10097 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10098 // allow either a mul, shift, or constant here.
10099 Value *NewIdx = 0;
10100 ConstantInt *Scale = 0;
10101 if (ArrayEltSize == 1) {
10102 NewIdx = GEP.getOperand(1);
10103 Scale = ConstantInt::get(NewIdx->getType(), 1);
10104 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10105 NewIdx = ConstantInt::get(CI->getType(), 1);
10106 Scale = CI;
10107 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10108 if (Inst->getOpcode() == Instruction::Shl &&
10109 isa<ConstantInt>(Inst->getOperand(1))) {
10110 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10111 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10112 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10113 NewIdx = Inst->getOperand(0);
10114 } else if (Inst->getOpcode() == Instruction::Mul &&
10115 isa<ConstantInt>(Inst->getOperand(1))) {
10116 Scale = cast<ConstantInt>(Inst->getOperand(1));
10117 NewIdx = Inst->getOperand(0);
10118 }
10119 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010120
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010121 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010122 // out, perform the transformation. Note, we don't know whether Scale is
10123 // signed or not. We'll use unsigned version of division/modulo
10124 // operation after making sure Scale doesn't have the sign bit set.
10125 if (Scale && Scale->getSExtValue() >= 0LL &&
10126 Scale->getZExtValue() % ArrayEltSize == 0) {
10127 Scale = ConstantInt::get(Scale->getType(),
10128 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010129 if (Scale->getZExtValue() != 1) {
10130 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010131 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010132 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010133 NewIdx = InsertNewInstBefore(Sc, GEP);
10134 }
10135
10136 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010137 Value *Idx[2];
10138 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10139 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010141 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010142 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10143 // The NewGEP must be pointer typed, so must the old one -> BitCast
10144 return new BitCastInst(NewGEP, GEP.getType());
10145 }
10146 }
10147 }
10148 }
10149
10150 return 0;
10151}
10152
10153Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10154 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010155 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10157 const Type *NewTy =
10158 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10159 AllocationInst *New = 0;
10160
10161 // Create and insert the replacement instruction...
10162 if (isa<MallocInst>(AI))
10163 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10164 else {
10165 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10166 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10167 }
10168
10169 InsertNewInstBefore(New, AI);
10170
10171 // Scan to the end of the allocation instructions, to skip over a block of
10172 // allocas if possible...
10173 //
10174 BasicBlock::iterator It = New;
10175 while (isa<AllocationInst>(*It)) ++It;
10176
10177 // Now that I is pointing to the first non-allocation-inst in the block,
10178 // insert our getelementptr instruction...
10179 //
10180 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010181 Value *Idx[2];
10182 Idx[0] = NullIdx;
10183 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010184 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10185 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010186
10187 // Now make everything use the getelementptr instead of the original
10188 // allocation.
10189 return ReplaceInstUsesWith(AI, V);
10190 } else if (isa<UndefValue>(AI.getArraySize())) {
10191 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10192 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010193 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010194
10195 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10196 // Note that we only do this for alloca's, because malloc should allocate and
10197 // return a unique pointer, even for a zero byte allocation.
10198 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010199 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10201
10202 return 0;
10203}
10204
10205Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10206 Value *Op = FI.getOperand(0);
10207
10208 // free undef -> unreachable.
10209 if (isa<UndefValue>(Op)) {
10210 // Insert a new store to null because we cannot modify the CFG here.
10211 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010212 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010213 return EraseInstFromFunction(FI);
10214 }
10215
10216 // If we have 'free null' delete the instruction. This can happen in stl code
10217 // when lots of inlining happens.
10218 if (isa<ConstantPointerNull>(Op))
10219 return EraseInstFromFunction(FI);
10220
10221 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10222 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10223 FI.setOperand(0, CI->getOperand(0));
10224 return &FI;
10225 }
10226
10227 // Change free (gep X, 0,0,0,0) into free(X)
10228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10229 if (GEPI->hasAllZeroIndices()) {
10230 AddToWorkList(GEPI);
10231 FI.setOperand(0, GEPI->getOperand(0));
10232 return &FI;
10233 }
10234 }
10235
10236 // Change free(malloc) into nothing, if the malloc has a single use.
10237 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10238 if (MI->hasOneUse()) {
10239 EraseInstFromFunction(FI);
10240 return EraseInstFromFunction(*MI);
10241 }
10242
10243 return 0;
10244}
10245
10246
10247/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010248static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010249 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010250 User *CI = cast<User>(LI.getOperand(0));
10251 Value *CastOp = CI->getOperand(0);
10252
Devang Patela0f8ea82007-10-18 19:52:32 +000010253 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10254 // Instead of loading constant c string, use corresponding integer value
10255 // directly if string length is small enough.
10256 const std::string &Str = CE->getOperand(0)->getStringValue();
10257 if (!Str.empty()) {
10258 unsigned len = Str.length();
10259 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10260 unsigned numBits = Ty->getPrimitiveSizeInBits();
10261 // Replace LI with immediate integer store.
10262 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010263 APInt StrVal(numBits, 0);
10264 APInt SingleChar(numBits, 0);
10265 if (TD->isLittleEndian()) {
10266 for (signed i = len-1; i >= 0; i--) {
10267 SingleChar = (uint64_t) Str[i];
10268 StrVal = (StrVal << 8) | SingleChar;
10269 }
10270 } else {
10271 for (unsigned i = 0; i < len; i++) {
10272 SingleChar = (uint64_t) Str[i];
10273 StrVal = (StrVal << 8) | SingleChar;
10274 }
10275 // Append NULL at the end.
10276 SingleChar = 0;
10277 StrVal = (StrVal << 8) | SingleChar;
10278 }
10279 Value *NL = ConstantInt::get(StrVal);
10280 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010281 }
10282 }
10283 }
10284
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010285 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10286 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10287 const Type *SrcPTy = SrcTy->getElementType();
10288
10289 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10290 isa<VectorType>(DestPTy)) {
10291 // If the source is an array, the code below will not succeed. Check to
10292 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10293 // constants.
10294 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10295 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10296 if (ASrcTy->getNumElements() != 0) {
10297 Value *Idxs[2];
10298 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10299 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10300 SrcTy = cast<PointerType>(CastOp->getType());
10301 SrcPTy = SrcTy->getElementType();
10302 }
10303
10304 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10305 isa<VectorType>(SrcPTy)) &&
10306 // Do not allow turning this into a load of an integer, which is then
10307 // casted to a pointer, this pessimizes pointer analysis a lot.
10308 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10309 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10310 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10311
10312 // Okay, we are casting from one integer or pointer type to another of
10313 // the same size. Instead of casting the pointer before the load, cast
10314 // the result of the loaded value.
10315 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10316 CI->getName(),
10317 LI.isVolatile()),LI);
10318 // Now cast the result of the load.
10319 return new BitCastInst(NewLoad, LI.getType());
10320 }
10321 }
10322 }
10323 return 0;
10324}
10325
10326/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10327/// from this value cannot trap. If it is not obviously safe to load from the
10328/// specified pointer, we do a quick local scan of the basic block containing
10329/// ScanFrom, to determine if the address is already accessed.
10330static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010331 // If it is an alloca it is always safe to load from.
10332 if (isa<AllocaInst>(V)) return true;
10333
Duncan Sandse40a94a2007-09-19 10:25:38 +000010334 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010335 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010336 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010337 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010338
10339 // Otherwise, be a little bit agressive by scanning the local block where we
10340 // want to check to see if the pointer is already being loaded or stored
10341 // from/to. If so, the previous load or store would have already trapped,
10342 // so there is no harm doing an extra load (also, CSE will later eliminate
10343 // the load entirely).
10344 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10345
10346 while (BBI != E) {
10347 --BBI;
10348
10349 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10350 if (LI->getOperand(0) == V) return true;
10351 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10352 if (SI->getOperand(1) == V) return true;
10353
10354 }
10355 return false;
10356}
10357
Chris Lattner0270a112007-08-11 18:48:48 +000010358/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10359/// until we find the underlying object a pointer is referring to or something
10360/// we don't understand. Note that the returned pointer may be offset from the
10361/// input, because we ignore GEP indices.
10362static Value *GetUnderlyingObject(Value *Ptr) {
10363 while (1) {
10364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10365 if (CE->getOpcode() == Instruction::BitCast ||
10366 CE->getOpcode() == Instruction::GetElementPtr)
10367 Ptr = CE->getOperand(0);
10368 else
10369 return Ptr;
10370 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10371 Ptr = BCI->getOperand(0);
10372 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10373 Ptr = GEP->getOperand(0);
10374 } else {
10375 return Ptr;
10376 }
10377 }
10378}
10379
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010380Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10381 Value *Op = LI.getOperand(0);
10382
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010383 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010384 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10385 if (KnownAlign >
10386 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10387 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010388 LI.setAlignment(KnownAlign);
10389
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010390 // load (cast X) --> cast (load X) iff safe
10391 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010392 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010393 return Res;
10394
10395 // None of the following transforms are legal for volatile loads.
10396 if (LI.isVolatile()) return 0;
10397
10398 if (&LI.getParent()->front() != &LI) {
10399 BasicBlock::iterator BBI = &LI; --BBI;
10400 // If the instruction immediately before this is a store to the same
10401 // address, do a simple form of store->load forwarding.
10402 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10403 if (SI->getOperand(1) == LI.getOperand(0))
10404 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10405 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10406 if (LIB->getOperand(0) == LI.getOperand(0))
10407 return ReplaceInstUsesWith(LI, LIB);
10408 }
10409
Christopher Lamb2c175392007-12-29 07:56:53 +000010410 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10411 const Value *GEPI0 = GEPI->getOperand(0);
10412 // TODO: Consider a target hook for valid address spaces for this xform.
10413 if (isa<ConstantPointerNull>(GEPI0) &&
10414 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010415 // Insert a new store to null instruction before the load to indicate
10416 // that this code is not reachable. We do this instead of inserting
10417 // an unreachable instruction directly because we cannot modify the
10418 // CFG.
10419 new StoreInst(UndefValue::get(LI.getType()),
10420 Constant::getNullValue(Op->getType()), &LI);
10421 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10422 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010423 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010424
10425 if (Constant *C = dyn_cast<Constant>(Op)) {
10426 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010427 // TODO: Consider a target hook for valid address spaces for this xform.
10428 if (isa<UndefValue>(C) || (C->isNullValue() &&
10429 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010430 // Insert a new store to null instruction before the load to indicate that
10431 // this code is not reachable. We do this instead of inserting an
10432 // unreachable instruction directly because we cannot modify the CFG.
10433 new StoreInst(UndefValue::get(LI.getType()),
10434 Constant::getNullValue(Op->getType()), &LI);
10435 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10436 }
10437
10438 // Instcombine load (constant global) into the value loaded.
10439 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10440 if (GV->isConstant() && !GV->isDeclaration())
10441 return ReplaceInstUsesWith(LI, GV->getInitializer());
10442
10443 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010444 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010445 if (CE->getOpcode() == Instruction::GetElementPtr) {
10446 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10447 if (GV->isConstant() && !GV->isDeclaration())
10448 if (Constant *V =
10449 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10450 return ReplaceInstUsesWith(LI, V);
10451 if (CE->getOperand(0)->isNullValue()) {
10452 // Insert a new store to null instruction before the load to indicate
10453 // that this code is not reachable. We do this instead of inserting
10454 // an unreachable instruction directly because we cannot modify the
10455 // CFG.
10456 new StoreInst(UndefValue::get(LI.getType()),
10457 Constant::getNullValue(Op->getType()), &LI);
10458 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10459 }
10460
10461 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010462 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010463 return Res;
10464 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010466 }
Chris Lattner0270a112007-08-11 18:48:48 +000010467
10468 // If this load comes from anywhere in a constant global, and if the global
10469 // is all undef or zero, we know what it loads.
10470 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10471 if (GV->isConstant() && GV->hasInitializer()) {
10472 if (GV->getInitializer()->isNullValue())
10473 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10474 else if (isa<UndefValue>(GV->getInitializer()))
10475 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10476 }
10477 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010478
10479 if (Op->hasOneUse()) {
10480 // Change select and PHI nodes to select values instead of addresses: this
10481 // helps alias analysis out a lot, allows many others simplifications, and
10482 // exposes redundancy in the code.
10483 //
10484 // Note that we cannot do the transformation unless we know that the
10485 // introduced loads cannot trap! Something like this is valid as long as
10486 // the condition is always false: load (select bool %C, int* null, int* %G),
10487 // but it would not be valid if we transformed it to load from null
10488 // unconditionally.
10489 //
10490 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10491 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10492 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10493 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10494 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10495 SI->getOperand(1)->getName()+".val"), LI);
10496 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10497 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010498 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010499 }
10500
10501 // load (select (cond, null, P)) -> load P
10502 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10503 if (C->isNullValue()) {
10504 LI.setOperand(0, SI->getOperand(2));
10505 return &LI;
10506 }
10507
10508 // load (select (cond, P, null)) -> load P
10509 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10510 if (C->isNullValue()) {
10511 LI.setOperand(0, SI->getOperand(1));
10512 return &LI;
10513 }
10514 }
10515 }
10516 return 0;
10517}
10518
10519/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10520/// when possible.
10521static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10522 User *CI = cast<User>(SI.getOperand(1));
10523 Value *CastOp = CI->getOperand(0);
10524
10525 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10526 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10527 const Type *SrcPTy = SrcTy->getElementType();
10528
10529 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10530 // If the source is an array, the code below will not succeed. Check to
10531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10532 // constants.
10533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10535 if (ASrcTy->getNumElements() != 0) {
10536 Value* Idxs[2];
10537 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10538 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10539 SrcTy = cast<PointerType>(CastOp->getType());
10540 SrcPTy = SrcTy->getElementType();
10541 }
10542
10543 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10544 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10545 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10546
10547 // Okay, we are casting from one integer or pointer type to another of
10548 // the same size. Instead of casting the pointer before
10549 // the store, cast the value to be stored.
10550 Value *NewCast;
10551 Value *SIOp0 = SI.getOperand(0);
10552 Instruction::CastOps opcode = Instruction::BitCast;
10553 const Type* CastSrcTy = SIOp0->getType();
10554 const Type* CastDstTy = SrcPTy;
10555 if (isa<PointerType>(CastDstTy)) {
10556 if (CastSrcTy->isInteger())
10557 opcode = Instruction::IntToPtr;
10558 } else if (isa<IntegerType>(CastDstTy)) {
10559 if (isa<PointerType>(SIOp0->getType()))
10560 opcode = Instruction::PtrToInt;
10561 }
10562 if (Constant *C = dyn_cast<Constant>(SIOp0))
10563 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10564 else
10565 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010566 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010567 SI);
10568 return new StoreInst(NewCast, CastOp);
10569 }
10570 }
10571 }
10572 return 0;
10573}
10574
10575Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10576 Value *Val = SI.getOperand(0);
10577 Value *Ptr = SI.getOperand(1);
10578
10579 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10580 EraseInstFromFunction(SI);
10581 ++NumCombined;
10582 return 0;
10583 }
10584
10585 // If the RHS is an alloca with a single use, zapify the store, making the
10586 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010587 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588 if (isa<AllocaInst>(Ptr)) {
10589 EraseInstFromFunction(SI);
10590 ++NumCombined;
10591 return 0;
10592 }
10593
10594 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10595 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10596 GEP->getOperand(0)->hasOneUse()) {
10597 EraseInstFromFunction(SI);
10598 ++NumCombined;
10599 return 0;
10600 }
10601 }
10602
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010603 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010604 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10605 if (KnownAlign >
10606 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10607 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010608 SI.setAlignment(KnownAlign);
10609
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010610 // Do really simple DSE, to catch cases where there are several consequtive
10611 // stores to the same location, separated by a few arithmetic operations. This
10612 // situation often occurs with bitfield accesses.
10613 BasicBlock::iterator BBI = &SI;
10614 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10615 --ScanInsts) {
10616 --BBI;
10617
10618 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10619 // Prev store isn't volatile, and stores to the same location?
10620 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10621 ++NumDeadStore;
10622 ++BBI;
10623 EraseInstFromFunction(*PrevSI);
10624 continue;
10625 }
10626 break;
10627 }
10628
10629 // If this is a load, we have to stop. However, if the loaded value is from
10630 // the pointer we're loading and is producing the pointer we're storing,
10631 // then *this* store is dead (X = load P; store X -> P).
10632 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010633 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010634 EraseInstFromFunction(SI);
10635 ++NumCombined;
10636 return 0;
10637 }
10638 // Otherwise, this is a load from some other location. Stores before it
10639 // may not be dead.
10640 break;
10641 }
10642
10643 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010644 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010645 break;
10646 }
10647
10648
10649 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10650
10651 // store X, null -> turns into 'unreachable' in SimplifyCFG
10652 if (isa<ConstantPointerNull>(Ptr)) {
10653 if (!isa<UndefValue>(Val)) {
10654 SI.setOperand(0, UndefValue::get(Val->getType()));
10655 if (Instruction *U = dyn_cast<Instruction>(Val))
10656 AddToWorkList(U); // Dropped a use.
10657 ++NumCombined;
10658 }
10659 return 0; // Do not modify these!
10660 }
10661
10662 // store undef, Ptr -> noop
10663 if (isa<UndefValue>(Val)) {
10664 EraseInstFromFunction(SI);
10665 ++NumCombined;
10666 return 0;
10667 }
10668
10669 // If the pointer destination is a cast, see if we can fold the cast into the
10670 // source instead.
10671 if (isa<CastInst>(Ptr))
10672 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10673 return Res;
10674 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10675 if (CE->isCast())
10676 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10677 return Res;
10678
10679
10680 // If this store is the last instruction in the basic block, and if the block
10681 // ends with an unconditional branch, try to move it to the successor block.
10682 BBI = &SI; ++BBI;
10683 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10684 if (BI->isUnconditional())
10685 if (SimplifyStoreAtEndOfBlock(SI))
10686 return 0; // xform done!
10687
10688 return 0;
10689}
10690
10691/// SimplifyStoreAtEndOfBlock - Turn things like:
10692/// if () { *P = v1; } else { *P = v2 }
10693/// into a phi node with a store in the successor.
10694///
10695/// Simplify things like:
10696/// *P = v1; if () { *P = v2; }
10697/// into a phi node with a store in the successor.
10698///
10699bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10700 BasicBlock *StoreBB = SI.getParent();
10701
10702 // Check to see if the successor block has exactly two incoming edges. If
10703 // so, see if the other predecessor contains a store to the same location.
10704 // if so, insert a PHI node (if needed) and move the stores down.
10705 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10706
10707 // Determine whether Dest has exactly two predecessors and, if so, compute
10708 // the other predecessor.
10709 pred_iterator PI = pred_begin(DestBB);
10710 BasicBlock *OtherBB = 0;
10711 if (*PI != StoreBB)
10712 OtherBB = *PI;
10713 ++PI;
10714 if (PI == pred_end(DestBB))
10715 return false;
10716
10717 if (*PI != StoreBB) {
10718 if (OtherBB)
10719 return false;
10720 OtherBB = *PI;
10721 }
10722 if (++PI != pred_end(DestBB))
10723 return false;
10724
10725
10726 // Verify that the other block ends in a branch and is not otherwise empty.
10727 BasicBlock::iterator BBI = OtherBB->getTerminator();
10728 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10729 if (!OtherBr || BBI == OtherBB->begin())
10730 return false;
10731
10732 // If the other block ends in an unconditional branch, check for the 'if then
10733 // else' case. there is an instruction before the branch.
10734 StoreInst *OtherStore = 0;
10735 if (OtherBr->isUnconditional()) {
10736 // If this isn't a store, or isn't a store to the same location, bail out.
10737 --BBI;
10738 OtherStore = dyn_cast<StoreInst>(BBI);
10739 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10740 return false;
10741 } else {
10742 // Otherwise, the other block ended with a conditional branch. If one of the
10743 // destinations is StoreBB, then we have the if/then case.
10744 if (OtherBr->getSuccessor(0) != StoreBB &&
10745 OtherBr->getSuccessor(1) != StoreBB)
10746 return false;
10747
10748 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10749 // if/then triangle. See if there is a store to the same ptr as SI that
10750 // lives in OtherBB.
10751 for (;; --BBI) {
10752 // Check to see if we find the matching store.
10753 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10754 if (OtherStore->getOperand(1) != SI.getOperand(1))
10755 return false;
10756 break;
10757 }
10758 // If we find something that may be using the stored value, or if we run
10759 // out of instructions, we can't do the xform.
10760 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10761 BBI == OtherBB->begin())
10762 return false;
10763 }
10764
10765 // In order to eliminate the store in OtherBr, we have to
10766 // make sure nothing reads the stored value in StoreBB.
10767 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10768 // FIXME: This should really be AA driven.
10769 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10770 return false;
10771 }
10772 }
10773
10774 // Insert a PHI node now if we need it.
10775 Value *MergedVal = OtherStore->getOperand(0);
10776 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010777 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010778 PN->reserveOperandSpace(2);
10779 PN->addIncoming(SI.getOperand(0), SI.getParent());
10780 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10781 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10782 }
10783
10784 // Advance to a place where it is safe to insert the new store and
10785 // insert it.
10786 BBI = DestBB->begin();
10787 while (isa<PHINode>(BBI)) ++BBI;
10788 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10789 OtherStore->isVolatile()), *BBI);
10790
10791 // Nuke the old stores.
10792 EraseInstFromFunction(SI);
10793 EraseInstFromFunction(*OtherStore);
10794 ++NumCombined;
10795 return true;
10796}
10797
10798
10799Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10800 // Change br (not X), label True, label False to: br X, label False, True
10801 Value *X = 0;
10802 BasicBlock *TrueDest;
10803 BasicBlock *FalseDest;
10804 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10805 !isa<Constant>(X)) {
10806 // Swap Destinations and condition...
10807 BI.setCondition(X);
10808 BI.setSuccessor(0, FalseDest);
10809 BI.setSuccessor(1, TrueDest);
10810 return &BI;
10811 }
10812
10813 // Cannonicalize fcmp_one -> fcmp_oeq
10814 FCmpInst::Predicate FPred; Value *Y;
10815 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10816 TrueDest, FalseDest)))
10817 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10818 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10819 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10820 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10821 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10822 NewSCC->takeName(I);
10823 // Swap Destinations and condition...
10824 BI.setCondition(NewSCC);
10825 BI.setSuccessor(0, FalseDest);
10826 BI.setSuccessor(1, TrueDest);
10827 RemoveFromWorkList(I);
10828 I->eraseFromParent();
10829 AddToWorkList(NewSCC);
10830 return &BI;
10831 }
10832
10833 // Cannonicalize icmp_ne -> icmp_eq
10834 ICmpInst::Predicate IPred;
10835 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10836 TrueDest, FalseDest)))
10837 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10838 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10839 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10840 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10841 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10842 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10843 NewSCC->takeName(I);
10844 // Swap Destinations and condition...
10845 BI.setCondition(NewSCC);
10846 BI.setSuccessor(0, FalseDest);
10847 BI.setSuccessor(1, TrueDest);
10848 RemoveFromWorkList(I);
10849 I->eraseFromParent();;
10850 AddToWorkList(NewSCC);
10851 return &BI;
10852 }
10853
10854 return 0;
10855}
10856
10857Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10858 Value *Cond = SI.getCondition();
10859 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10860 if (I->getOpcode() == Instruction::Add)
10861 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10862 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10863 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10864 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10865 AddRHS));
10866 SI.setOperand(0, I->getOperand(0));
10867 AddToWorkList(I);
10868 return &SI;
10869 }
10870 }
10871 return 0;
10872}
10873
10874/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10875/// is to leave as a vector operation.
10876static bool CheapToScalarize(Value *V, bool isConstant) {
10877 if (isa<ConstantAggregateZero>(V))
10878 return true;
10879 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10880 if (isConstant) return true;
10881 // If all elts are the same, we can extract.
10882 Constant *Op0 = C->getOperand(0);
10883 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10884 if (C->getOperand(i) != Op0)
10885 return false;
10886 return true;
10887 }
10888 Instruction *I = dyn_cast<Instruction>(V);
10889 if (!I) return false;
10890
10891 // Insert element gets simplified to the inserted element or is deleted if
10892 // this is constant idx extract element and its a constant idx insertelt.
10893 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10894 isa<ConstantInt>(I->getOperand(2)))
10895 return true;
10896 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10897 return true;
10898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10899 if (BO->hasOneUse() &&
10900 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10901 CheapToScalarize(BO->getOperand(1), isConstant)))
10902 return true;
10903 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10904 if (CI->hasOneUse() &&
10905 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10906 CheapToScalarize(CI->getOperand(1), isConstant)))
10907 return true;
10908
10909 return false;
10910}
10911
10912/// Read and decode a shufflevector mask.
10913///
10914/// It turns undef elements into values that are larger than the number of
10915/// elements in the input.
10916static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10917 unsigned NElts = SVI->getType()->getNumElements();
10918 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10919 return std::vector<unsigned>(NElts, 0);
10920 if (isa<UndefValue>(SVI->getOperand(2)))
10921 return std::vector<unsigned>(NElts, 2*NElts);
10922
10923 std::vector<unsigned> Result;
10924 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10925 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10926 if (isa<UndefValue>(CP->getOperand(i)))
10927 Result.push_back(NElts*2); // undef -> 8
10928 else
10929 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10930 return Result;
10931}
10932
10933/// FindScalarElement - Given a vector and an element number, see if the scalar
10934/// value is already around as a register, for example if it were inserted then
10935/// extracted from the vector.
10936static Value *FindScalarElement(Value *V, unsigned EltNo) {
10937 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10938 const VectorType *PTy = cast<VectorType>(V->getType());
10939 unsigned Width = PTy->getNumElements();
10940 if (EltNo >= Width) // Out of range access.
10941 return UndefValue::get(PTy->getElementType());
10942
10943 if (isa<UndefValue>(V))
10944 return UndefValue::get(PTy->getElementType());
10945 else if (isa<ConstantAggregateZero>(V))
10946 return Constant::getNullValue(PTy->getElementType());
10947 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10948 return CP->getOperand(EltNo);
10949 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10950 // If this is an insert to a variable element, we don't know what it is.
10951 if (!isa<ConstantInt>(III->getOperand(2)))
10952 return 0;
10953 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10954
10955 // If this is an insert to the element we are looking for, return the
10956 // inserted value.
10957 if (EltNo == IIElt)
10958 return III->getOperand(1);
10959
10960 // Otherwise, the insertelement doesn't modify the value, recurse on its
10961 // vector input.
10962 return FindScalarElement(III->getOperand(0), EltNo);
10963 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10964 unsigned InEl = getShuffleMask(SVI)[EltNo];
10965 if (InEl < Width)
10966 return FindScalarElement(SVI->getOperand(0), InEl);
10967 else if (InEl < Width*2)
10968 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10969 else
10970 return UndefValue::get(PTy->getElementType());
10971 }
10972
10973 // Otherwise, we don't know.
10974 return 0;
10975}
10976
10977Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10978
10979 // If vector val is undef, replace extract with scalar undef.
10980 if (isa<UndefValue>(EI.getOperand(0)))
10981 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10982
10983 // If vector val is constant 0, replace extract with scalar 0.
10984 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10985 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10986
10987 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10988 // If vector val is constant with uniform operands, replace EI
10989 // with that operand
10990 Constant *op0 = C->getOperand(0);
10991 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10992 if (C->getOperand(i) != op0) {
10993 op0 = 0;
10994 break;
10995 }
10996 if (op0)
10997 return ReplaceInstUsesWith(EI, op0);
10998 }
10999
11000 // If extracting a specified index from the vector, see if we can recursively
11001 // find a previously computed scalar that was inserted into the vector.
11002 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11003 unsigned IndexVal = IdxC->getZExtValue();
11004 unsigned VectorWidth =
11005 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11006
11007 // If this is extracting an invalid index, turn this into undef, to avoid
11008 // crashing the code below.
11009 if (IndexVal >= VectorWidth)
11010 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11011
11012 // This instruction only demands the single element from the input vector.
11013 // If the input vector has a single use, simplify it based on this use
11014 // property.
11015 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11016 uint64_t UndefElts;
11017 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11018 1 << IndexVal,
11019 UndefElts)) {
11020 EI.setOperand(0, V);
11021 return &EI;
11022 }
11023 }
11024
11025 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11026 return ReplaceInstUsesWith(EI, Elt);
11027
11028 // If the this extractelement is directly using a bitcast from a vector of
11029 // the same number of elements, see if we can find the source element from
11030 // it. In this case, we will end up needing to bitcast the scalars.
11031 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11032 if (const VectorType *VT =
11033 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11034 if (VT->getNumElements() == VectorWidth)
11035 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11036 return new BitCastInst(Elt, EI.getType());
11037 }
11038 }
11039
11040 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11041 if (I->hasOneUse()) {
11042 // Push extractelement into predecessor operation if legal and
11043 // profitable to do so
11044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11045 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11046 if (CheapToScalarize(BO, isConstantElt)) {
11047 ExtractElementInst *newEI0 =
11048 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11049 EI.getName()+".lhs");
11050 ExtractElementInst *newEI1 =
11051 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11052 EI.getName()+".rhs");
11053 InsertNewInstBefore(newEI0, EI);
11054 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011055 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011056 }
11057 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011058 unsigned AS =
11059 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011060 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11061 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011062 GetElementPtrInst *GEP =
11063 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011064 InsertNewInstBefore(GEP, EI);
11065 return new LoadInst(GEP);
11066 }
11067 }
11068 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11069 // Extracting the inserted element?
11070 if (IE->getOperand(2) == EI.getOperand(1))
11071 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11072 // If the inserted and extracted elements are constants, they must not
11073 // be the same value, extract from the pre-inserted value instead.
11074 if (isa<Constant>(IE->getOperand(2)) &&
11075 isa<Constant>(EI.getOperand(1))) {
11076 AddUsesToWorkList(EI);
11077 EI.setOperand(0, IE->getOperand(0));
11078 return &EI;
11079 }
11080 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11081 // If this is extracting an element from a shufflevector, figure out where
11082 // it came from and extract from the appropriate input element instead.
11083 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11084 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11085 Value *Src;
11086 if (SrcIdx < SVI->getType()->getNumElements())
11087 Src = SVI->getOperand(0);
11088 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11089 SrcIdx -= SVI->getType()->getNumElements();
11090 Src = SVI->getOperand(1);
11091 } else {
11092 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11093 }
11094 return new ExtractElementInst(Src, SrcIdx);
11095 }
11096 }
11097 }
11098 return 0;
11099}
11100
11101/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11102/// elements from either LHS or RHS, return the shuffle mask and true.
11103/// Otherwise, return false.
11104static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11105 std::vector<Constant*> &Mask) {
11106 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11107 "Invalid CollectSingleShuffleElements");
11108 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11109
11110 if (isa<UndefValue>(V)) {
11111 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11112 return true;
11113 } else if (V == LHS) {
11114 for (unsigned i = 0; i != NumElts; ++i)
11115 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11116 return true;
11117 } else if (V == RHS) {
11118 for (unsigned i = 0; i != NumElts; ++i)
11119 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11120 return true;
11121 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11122 // If this is an insert of an extract from some other vector, include it.
11123 Value *VecOp = IEI->getOperand(0);
11124 Value *ScalarOp = IEI->getOperand(1);
11125 Value *IdxOp = IEI->getOperand(2);
11126
11127 if (!isa<ConstantInt>(IdxOp))
11128 return false;
11129 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11130
11131 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11132 // Okay, we can handle this if the vector we are insertinting into is
11133 // transitively ok.
11134 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11135 // If so, update the mask to reflect the inserted undef.
11136 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11137 return true;
11138 }
11139 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11140 if (isa<ConstantInt>(EI->getOperand(1)) &&
11141 EI->getOperand(0)->getType() == V->getType()) {
11142 unsigned ExtractedIdx =
11143 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11144
11145 // This must be extracting from either LHS or RHS.
11146 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11147 // Okay, we can handle this if the vector we are insertinting into is
11148 // transitively ok.
11149 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11150 // If so, update the mask to reflect the inserted value.
11151 if (EI->getOperand(0) == LHS) {
11152 Mask[InsertedIdx & (NumElts-1)] =
11153 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11154 } else {
11155 assert(EI->getOperand(0) == RHS);
11156 Mask[InsertedIdx & (NumElts-1)] =
11157 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11158
11159 }
11160 return true;
11161 }
11162 }
11163 }
11164 }
11165 }
11166 // TODO: Handle shufflevector here!
11167
11168 return false;
11169}
11170
11171/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11172/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11173/// that computes V and the LHS value of the shuffle.
11174static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11175 Value *&RHS) {
11176 assert(isa<VectorType>(V->getType()) &&
11177 (RHS == 0 || V->getType() == RHS->getType()) &&
11178 "Invalid shuffle!");
11179 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11180
11181 if (isa<UndefValue>(V)) {
11182 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11183 return V;
11184 } else if (isa<ConstantAggregateZero>(V)) {
11185 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11186 return V;
11187 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11188 // If this is an insert of an extract from some other vector, include it.
11189 Value *VecOp = IEI->getOperand(0);
11190 Value *ScalarOp = IEI->getOperand(1);
11191 Value *IdxOp = IEI->getOperand(2);
11192
11193 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11194 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11195 EI->getOperand(0)->getType() == V->getType()) {
11196 unsigned ExtractedIdx =
11197 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11198 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11199
11200 // Either the extracted from or inserted into vector must be RHSVec,
11201 // otherwise we'd end up with a shuffle of three inputs.
11202 if (EI->getOperand(0) == RHS || RHS == 0) {
11203 RHS = EI->getOperand(0);
11204 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11205 Mask[InsertedIdx & (NumElts-1)] =
11206 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11207 return V;
11208 }
11209
11210 if (VecOp == RHS) {
11211 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11212 // Everything but the extracted element is replaced with the RHS.
11213 for (unsigned i = 0; i != NumElts; ++i) {
11214 if (i != InsertedIdx)
11215 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11216 }
11217 return V;
11218 }
11219
11220 // If this insertelement is a chain that comes from exactly these two
11221 // vectors, return the vector and the effective shuffle.
11222 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11223 return EI->getOperand(0);
11224
11225 }
11226 }
11227 }
11228 // TODO: Handle shufflevector here!
11229
11230 // Otherwise, can't do anything fancy. Return an identity vector.
11231 for (unsigned i = 0; i != NumElts; ++i)
11232 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11233 return V;
11234}
11235
11236Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11237 Value *VecOp = IE.getOperand(0);
11238 Value *ScalarOp = IE.getOperand(1);
11239 Value *IdxOp = IE.getOperand(2);
11240
11241 // Inserting an undef or into an undefined place, remove this.
11242 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11243 ReplaceInstUsesWith(IE, VecOp);
11244
11245 // If the inserted element was extracted from some other vector, and if the
11246 // indexes are constant, try to turn this into a shufflevector operation.
11247 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11248 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11249 EI->getOperand(0)->getType() == IE.getType()) {
11250 unsigned NumVectorElts = IE.getType()->getNumElements();
11251 unsigned ExtractedIdx =
11252 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11253 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11254
11255 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11256 return ReplaceInstUsesWith(IE, VecOp);
11257
11258 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11259 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11260
11261 // If we are extracting a value from a vector, then inserting it right
11262 // back into the same place, just use the input vector.
11263 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11264 return ReplaceInstUsesWith(IE, VecOp);
11265
11266 // We could theoretically do this for ANY input. However, doing so could
11267 // turn chains of insertelement instructions into a chain of shufflevector
11268 // instructions, and right now we do not merge shufflevectors. As such,
11269 // only do this in a situation where it is clear that there is benefit.
11270 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11271 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11272 // the values of VecOp, except then one read from EIOp0.
11273 // Build a new shuffle mask.
11274 std::vector<Constant*> Mask;
11275 if (isa<UndefValue>(VecOp))
11276 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11277 else {
11278 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11279 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11280 NumVectorElts));
11281 }
11282 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11283 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11284 ConstantVector::get(Mask));
11285 }
11286
11287 // If this insertelement isn't used by some other insertelement, turn it
11288 // (and any insertelements it points to), into one big shuffle.
11289 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11290 std::vector<Constant*> Mask;
11291 Value *RHS = 0;
11292 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11293 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11294 // We now have a shuffle of LHS, RHS, Mask.
11295 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11296 }
11297 }
11298 }
11299
11300 return 0;
11301}
11302
11303
11304Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11305 Value *LHS = SVI.getOperand(0);
11306 Value *RHS = SVI.getOperand(1);
11307 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11308
11309 bool MadeChange = false;
11310
11311 // Undefined shuffle mask -> undefined value.
11312 if (isa<UndefValue>(SVI.getOperand(2)))
11313 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11314
11315 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11316 // the undef, change them to undefs.
11317 if (isa<UndefValue>(SVI.getOperand(1))) {
11318 // Scan to see if there are any references to the RHS. If so, replace them
11319 // with undef element refs and set MadeChange to true.
11320 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11321 if (Mask[i] >= e && Mask[i] != 2*e) {
11322 Mask[i] = 2*e;
11323 MadeChange = true;
11324 }
11325 }
11326
11327 if (MadeChange) {
11328 // Remap any references to RHS to use LHS.
11329 std::vector<Constant*> Elts;
11330 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11331 if (Mask[i] == 2*e)
11332 Elts.push_back(UndefValue::get(Type::Int32Ty));
11333 else
11334 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11335 }
11336 SVI.setOperand(2, ConstantVector::get(Elts));
11337 }
11338 }
11339
11340 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11341 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11342 if (LHS == RHS || isa<UndefValue>(LHS)) {
11343 if (isa<UndefValue>(LHS) && LHS == RHS) {
11344 // shuffle(undef,undef,mask) -> undef.
11345 return ReplaceInstUsesWith(SVI, LHS);
11346 }
11347
11348 // Remap any references to RHS to use LHS.
11349 std::vector<Constant*> Elts;
11350 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11351 if (Mask[i] >= 2*e)
11352 Elts.push_back(UndefValue::get(Type::Int32Ty));
11353 else {
11354 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11355 (Mask[i] < e && isa<UndefValue>(LHS)))
11356 Mask[i] = 2*e; // Turn into undef.
11357 else
11358 Mask[i] &= (e-1); // Force to LHS.
11359 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11360 }
11361 }
11362 SVI.setOperand(0, SVI.getOperand(1));
11363 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11364 SVI.setOperand(2, ConstantVector::get(Elts));
11365 LHS = SVI.getOperand(0);
11366 RHS = SVI.getOperand(1);
11367 MadeChange = true;
11368 }
11369
11370 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11371 bool isLHSID = true, isRHSID = true;
11372
11373 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11374 if (Mask[i] >= e*2) continue; // Ignore undef values.
11375 // Is this an identity shuffle of the LHS value?
11376 isLHSID &= (Mask[i] == i);
11377
11378 // Is this an identity shuffle of the RHS value?
11379 isRHSID &= (Mask[i]-e == i);
11380 }
11381
11382 // Eliminate identity shuffles.
11383 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11384 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11385
11386 // If the LHS is a shufflevector itself, see if we can combine it with this
11387 // one without producing an unusual shuffle. Here we are really conservative:
11388 // we are absolutely afraid of producing a shuffle mask not in the input
11389 // program, because the code gen may not be smart enough to turn a merged
11390 // shuffle into two specific shuffles: it may produce worse code. As such,
11391 // we only merge two shuffles if the result is one of the two input shuffle
11392 // masks. In this case, merging the shuffles just removes one instruction,
11393 // which we know is safe. This is good for things like turning:
11394 // (splat(splat)) -> splat.
11395 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11396 if (isa<UndefValue>(RHS)) {
11397 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11398
11399 std::vector<unsigned> NewMask;
11400 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11401 if (Mask[i] >= 2*e)
11402 NewMask.push_back(2*e);
11403 else
11404 NewMask.push_back(LHSMask[Mask[i]]);
11405
11406 // If the result mask is equal to the src shuffle or this shuffle mask, do
11407 // the replacement.
11408 if (NewMask == LHSMask || NewMask == Mask) {
11409 std::vector<Constant*> Elts;
11410 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11411 if (NewMask[i] >= e*2) {
11412 Elts.push_back(UndefValue::get(Type::Int32Ty));
11413 } else {
11414 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11415 }
11416 }
11417 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11418 LHSSVI->getOperand(1),
11419 ConstantVector::get(Elts));
11420 }
11421 }
11422 }
11423
11424 return MadeChange ? &SVI : 0;
11425}
11426
11427
11428
11429
11430/// TryToSinkInstruction - Try to move the specified instruction from its
11431/// current block into the beginning of DestBlock, which can only happen if it's
11432/// safe to move the instruction past all of the instructions between it and the
11433/// end of its block.
11434static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11435 assert(I->hasOneUse() && "Invariants didn't hold!");
11436
11437 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011438 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11439 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011440
11441 // Do not sink alloca instructions out of the entry block.
11442 if (isa<AllocaInst>(I) && I->getParent() ==
11443 &DestBlock->getParent()->getEntryBlock())
11444 return false;
11445
11446 // We can only sink load instructions if there is nothing between the load and
11447 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011448 if (I->mayReadFromMemory()) {
11449 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011450 Scan != E; ++Scan)
11451 if (Scan->mayWriteToMemory())
11452 return false;
11453 }
11454
11455 BasicBlock::iterator InsertPos = DestBlock->begin();
11456 while (isa<PHINode>(InsertPos)) ++InsertPos;
11457
11458 I->moveBefore(InsertPos);
11459 ++NumSunkInst;
11460 return true;
11461}
11462
11463
11464/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11465/// all reachable code to the worklist.
11466///
11467/// This has a couple of tricks to make the code faster and more powerful. In
11468/// particular, we constant fold and DCE instructions as we go, to avoid adding
11469/// them to the worklist (this significantly speeds up instcombine on code where
11470/// many instructions are dead or constant). Additionally, if we find a branch
11471/// whose condition is a known constant, we only visit the reachable successors.
11472///
11473static void AddReachableCodeToWorklist(BasicBlock *BB,
11474 SmallPtrSet<BasicBlock*, 64> &Visited,
11475 InstCombiner &IC,
11476 const TargetData *TD) {
11477 std::vector<BasicBlock*> Worklist;
11478 Worklist.push_back(BB);
11479
11480 while (!Worklist.empty()) {
11481 BB = Worklist.back();
11482 Worklist.pop_back();
11483
11484 // We have now visited this block! If we've already been here, ignore it.
11485 if (!Visited.insert(BB)) continue;
11486
11487 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11488 Instruction *Inst = BBI++;
11489
11490 // DCE instruction if trivially dead.
11491 if (isInstructionTriviallyDead(Inst)) {
11492 ++NumDeadInst;
11493 DOUT << "IC: DCE: " << *Inst;
11494 Inst->eraseFromParent();
11495 continue;
11496 }
11497
11498 // ConstantProp instruction if trivially constant.
11499 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11500 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11501 Inst->replaceAllUsesWith(C);
11502 ++NumConstProp;
11503 Inst->eraseFromParent();
11504 continue;
11505 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011506
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011507 IC.AddToWorkList(Inst);
11508 }
11509
11510 // Recursively visit successors. If this is a branch or switch on a
11511 // constant, only visit the reachable successor.
11512 TerminatorInst *TI = BB->getTerminator();
11513 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11514 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11515 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011516 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011517 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011518 continue;
11519 }
11520 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11521 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11522 // See if this is an explicit destination.
11523 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11524 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011525 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011526 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011527 continue;
11528 }
11529
11530 // Otherwise it is the default destination.
11531 Worklist.push_back(SI->getSuccessor(0));
11532 continue;
11533 }
11534 }
11535
11536 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11537 Worklist.push_back(TI->getSuccessor(i));
11538 }
11539}
11540
11541bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11542 bool Changed = false;
11543 TD = &getAnalysis<TargetData>();
11544
11545 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11546 << F.getNameStr() << "\n");
11547
11548 {
11549 // Do a depth-first traversal of the function, populate the worklist with
11550 // the reachable instructions. Ignore blocks that are not reachable. Keep
11551 // track of which blocks we visit.
11552 SmallPtrSet<BasicBlock*, 64> Visited;
11553 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11554
11555 // Do a quick scan over the function. If we find any blocks that are
11556 // unreachable, remove any instructions inside of them. This prevents
11557 // the instcombine code from having to deal with some bad special cases.
11558 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11559 if (!Visited.count(BB)) {
11560 Instruction *Term = BB->getTerminator();
11561 while (Term != BB->begin()) { // Remove instrs bottom-up
11562 BasicBlock::iterator I = Term; --I;
11563
11564 DOUT << "IC: DCE: " << *I;
11565 ++NumDeadInst;
11566
11567 if (!I->use_empty())
11568 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11569 I->eraseFromParent();
11570 }
11571 }
11572 }
11573
11574 while (!Worklist.empty()) {
11575 Instruction *I = RemoveOneFromWorkList();
11576 if (I == 0) continue; // skip null values.
11577
11578 // Check to see if we can DCE the instruction.
11579 if (isInstructionTriviallyDead(I)) {
11580 // Add operands to the worklist.
11581 if (I->getNumOperands() < 4)
11582 AddUsesToWorkList(*I);
11583 ++NumDeadInst;
11584
11585 DOUT << "IC: DCE: " << *I;
11586
11587 I->eraseFromParent();
11588 RemoveFromWorkList(I);
11589 continue;
11590 }
11591
11592 // Instruction isn't dead, see if we can constant propagate it.
11593 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11594 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11595
11596 // Add operands to the worklist.
11597 AddUsesToWorkList(*I);
11598 ReplaceInstUsesWith(*I, C);
11599
11600 ++NumConstProp;
11601 I->eraseFromParent();
11602 RemoveFromWorkList(I);
11603 continue;
11604 }
11605
11606 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011607 // FIXME: Remove GetResultInst test when first class support for aggregates
11608 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011609 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011610 BasicBlock *BB = I->getParent();
11611 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11612 if (UserParent != BB) {
11613 bool UserIsSuccessor = false;
11614 // See if the user is one of our successors.
11615 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11616 if (*SI == UserParent) {
11617 UserIsSuccessor = true;
11618 break;
11619 }
11620
11621 // If the user is one of our immediate successors, and if that successor
11622 // only has us as a predecessors (we'd have to split the critical edge
11623 // otherwise), we can keep going.
11624 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11625 next(pred_begin(UserParent)) == pred_end(UserParent))
11626 // Okay, the CFG is simple enough, try to sink this instruction.
11627 Changed |= TryToSinkInstruction(I, UserParent);
11628 }
11629 }
11630
11631 // Now that we have an instruction, try combining it to simplify it...
11632#ifndef NDEBUG
11633 std::string OrigI;
11634#endif
11635 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11636 if (Instruction *Result = visit(*I)) {
11637 ++NumCombined;
11638 // Should we replace the old instruction with a new one?
11639 if (Result != I) {
11640 DOUT << "IC: Old = " << *I
11641 << " New = " << *Result;
11642
11643 // Everything uses the new instruction now.
11644 I->replaceAllUsesWith(Result);
11645
11646 // Push the new instruction and any users onto the worklist.
11647 AddToWorkList(Result);
11648 AddUsersToWorkList(*Result);
11649
11650 // Move the name to the new instruction first.
11651 Result->takeName(I);
11652
11653 // Insert the new instruction into the basic block...
11654 BasicBlock *InstParent = I->getParent();
11655 BasicBlock::iterator InsertPos = I;
11656
11657 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11658 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11659 ++InsertPos;
11660
11661 InstParent->getInstList().insert(InsertPos, Result);
11662
11663 // Make sure that we reprocess all operands now that we reduced their
11664 // use counts.
11665 AddUsesToWorkList(*I);
11666
11667 // Instructions can end up on the worklist more than once. Make sure
11668 // we do not process an instruction that has been deleted.
11669 RemoveFromWorkList(I);
11670
11671 // Erase the old instruction.
11672 InstParent->getInstList().erase(I);
11673 } else {
11674#ifndef NDEBUG
11675 DOUT << "IC: Mod = " << OrigI
11676 << " New = " << *I;
11677#endif
11678
11679 // If the instruction was modified, it's possible that it is now dead.
11680 // if so, remove it.
11681 if (isInstructionTriviallyDead(I)) {
11682 // Make sure we process all operands now that we are reducing their
11683 // use counts.
11684 AddUsesToWorkList(*I);
11685
11686 // Instructions may end up in the worklist more than once. Erase all
11687 // occurrences of this instruction.
11688 RemoveFromWorkList(I);
11689 I->eraseFromParent();
11690 } else {
11691 AddToWorkList(I);
11692 AddUsersToWorkList(*I);
11693 }
11694 }
11695 Changed = true;
11696 }
11697 }
11698
11699 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011700
11701 // Do an explicit clear, this shrinks the map if needed.
11702 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011703 return Changed;
11704}
11705
11706
11707bool InstCombiner::runOnFunction(Function &F) {
11708 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11709
11710 bool EverMadeChange = false;
11711
11712 // Iterate while there is work to do.
11713 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011714 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011715 EverMadeChange = true;
11716 return EverMadeChange;
11717}
11718
11719FunctionPass *llvm::createInstructionCombiningPass() {
11720 return new InstCombiner();
11721}
11722