blob: fff6dba7ee42bbb8a0aee139250aca019e60ecdb [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);
211 Instruction *visitFPToUI(CastInst &CI);
212 Instruction *visitFPToSI(CastInst &CI);
213 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;
837 // Fall through and handle them the same as zext/trunc.
838 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 case Instruction::Trunc: {
840 // All these have integer operands
Dan Gohman2d648bb2008-04-10 18:43:06 +0000841 const Type *SrcTy = I->getOperand(0)->getType();
842 uint32_t SrcBitWidth = TD ?
843 TD->getTypeSizeInBits(SrcTy) :
844 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000846 MaskIn.zextOrTrunc(SrcBitWidth);
847 KnownZero.zextOrTrunc(SrcBitWidth);
848 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000850 KnownZero.zextOrTrunc(BitWidth);
851 KnownOne.zextOrTrunc(BitWidth);
852 // Any top bits are known to be zero.
853 if (BitWidth > SrcBitWidth)
854 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 return;
856 }
857 case Instruction::BitCast: {
858 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000859 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
861 return;
862 }
863 break;
864 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 case Instruction::SExt: {
866 // Compute the bits in the result that are not present in the input.
867 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
868 uint32_t SrcBitWidth = SrcTy->getBitWidth();
869
870 APInt MaskIn(Mask);
871 MaskIn.trunc(SrcBitWidth);
872 KnownZero.trunc(SrcBitWidth);
873 KnownOne.trunc(SrcBitWidth);
874 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
875 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
876 KnownZero.zext(BitWidth);
877 KnownOne.zext(BitWidth);
878
879 // If the sign bit of the input is known set or clear, then we know the
880 // top bits of the result.
881 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
882 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
883 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
884 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
885 return;
886 }
887 case Instruction::Shl:
888 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
889 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
891 APInt Mask2(Mask.lshr(ShiftAmt));
892 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 KnownZero <<= ShiftAmt;
895 KnownOne <<= ShiftAmt;
896 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
897 return;
898 }
899 break;
900 case Instruction::LShr:
901 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
902 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
903 // Compute the new bits that are at the top now.
904 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
905
906 // Unsigned shift right.
907 APInt Mask2(Mask.shl(ShiftAmt));
908 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
909 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
910 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
911 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
912 // high bits known zero.
913 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
914 return;
915 }
916 break;
917 case Instruction::AShr:
918 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
919 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
920 // Compute the new bits that are at the top now.
921 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
922
923 // Signed shift right.
924 APInt Mask2(Mask.shl(ShiftAmt));
925 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
926 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
927 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
928 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
929
930 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
931 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
932 KnownZero |= HighBits;
933 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
934 KnownOne |= HighBits;
935 return;
936 }
937 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000938 case Instruction::Sub: {
939 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
940 // We know that the top bits of C-X are clear if X contains less bits
941 // than C (i.e. no wrap-around can happen). For example, 20-X is
942 // positive if we can prove that X is >= 0 and < 16.
943 if (!CLHS->getValue().isNegative()) {
944 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
945 // NLZ can't be BitWidth with no sign bit
946 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000947 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
948 Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000949
Dan Gohmanbec16052008-04-28 17:02:21 +0000950 // If all of the MaskV bits are known to be zero, then we know the
951 // output top bits are zero, because we now know that the output is
952 // from [0-C].
953 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman2d648bb2008-04-10 18:43:06 +0000954 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
955 // Top bits known zero.
956 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000957 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000958 }
959 }
960 }
961 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000962 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000963 // Output known-0 bits are known if clear or set in both the low clear bits
964 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
965 // low 3 bits clear.
Dan Gohmanbec16052008-04-28 17:02:21 +0000966 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
967 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
968 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
969 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
970
971 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
972 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
973 KnownZeroOut = std::min(KnownZeroOut,
974 KnownZero2.countTrailingOnes());
975
976 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000977 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000978 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000979 case Instruction::SRem:
980 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
981 APInt RA = Rem->getValue();
982 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +0000983 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000984 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
985 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
986
987 // The sign of a remainder is equal to the sign of the first
988 // operand (zero being positive).
989 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
990 KnownZero2 |= ~LowBits;
991 else if (KnownOne2[BitWidth-1])
992 KnownOne2 |= ~LowBits;
993
994 KnownZero |= KnownZero2 & Mask;
995 KnownOne |= KnownOne2 & Mask;
996
997 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
998 }
999 }
1000 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001001 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001002 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1003 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001004 if (RA.isPowerOf2()) {
1005 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001006 APInt Mask2 = LowBits & Mask;
1007 KnownZero |= ~LowBits & Mask;
1008 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1009 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001010 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001011 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001012 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001013
1014 // Since the result is less than or equal to either operand, any leading
1015 // zero bits in either operand must also exist in the result.
1016 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1017 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1018 Depth+1);
1019 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1020 Depth+1);
1021
1022 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1023 KnownZero2.countLeadingOnes());
1024 KnownOne.clear();
1025 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001026 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001027 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00001028
1029 case Instruction::Alloca:
1030 case Instruction::Malloc: {
1031 AllocationInst *AI = cast<AllocationInst>(V);
1032 unsigned Align = AI->getAlignment();
1033 if (Align == 0 && TD) {
1034 if (isa<AllocaInst>(AI))
1035 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1036 else if (isa<MallocInst>(AI)) {
1037 // Malloc returns maximally aligned memory.
1038 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1042 Align =
1043 std::max(Align,
1044 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1045 }
1046 }
1047
1048 if (Align > 0)
1049 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1050 CountTrailingZeros_32(Align));
1051 break;
1052 }
1053 case Instruction::GetElementPtr: {
1054 // Analyze all of the subscripts of this getelementptr instruction
1055 // to determine if we can prove known low zero bits.
1056 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1057 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1058 ComputeMaskedBits(I->getOperand(0), LocalMask,
1059 LocalKnownZero, LocalKnownOne, Depth+1);
1060 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1061
1062 gep_type_iterator GTI = gep_type_begin(I);
1063 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1064 Value *Index = I->getOperand(i);
1065 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1066 // Handle struct member offset arithmetic.
1067 if (!TD) return;
1068 const StructLayout *SL = TD->getStructLayout(STy);
1069 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1070 uint64_t Offset = SL->getElementOffset(Idx);
1071 TrailZ = std::min(TrailZ,
1072 CountTrailingZeros_64(Offset));
1073 } else {
1074 // Handle array index arithmetic.
1075 const Type *IndexedTy = GTI.getIndexedType();
1076 if (!IndexedTy->isSized()) return;
1077 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1078 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1079 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1080 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1081 ComputeMaskedBits(Index, LocalMask,
1082 LocalKnownZero, LocalKnownOne, Depth+1);
1083 TrailZ = std::min(TrailZ,
1084 CountTrailingZeros_64(TypeSize) +
1085 LocalKnownZero.countTrailingOnes());
1086 }
1087 }
1088
1089 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1090 break;
1091 }
1092 case Instruction::PHI: {
1093 PHINode *P = cast<PHINode>(I);
1094 // Handle the case of a simple two-predecessor recurrence PHI.
1095 // There's a lot more that could theoretically be done here, but
1096 // this is sufficient to catch some interesting cases.
1097 if (P->getNumIncomingValues() == 2) {
1098 for (unsigned i = 0; i != 2; ++i) {
1099 Value *L = P->getIncomingValue(i);
1100 Value *R = P->getIncomingValue(!i);
1101 User *LU = dyn_cast<User>(L);
1102 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1103 // Check for operations that have the property that if
1104 // both their operands have low zero bits, the result
1105 // will have low zero bits.
1106 if (Opcode == Instruction::Add ||
1107 Opcode == Instruction::Sub ||
1108 Opcode == Instruction::And ||
1109 Opcode == Instruction::Or ||
1110 Opcode == Instruction::Mul) {
1111 Value *LL = LU->getOperand(0);
1112 Value *LR = LU->getOperand(1);
1113 // Find a recurrence.
1114 if (LL == I)
1115 L = LR;
1116 else if (LR == I)
1117 L = LL;
1118 else
1119 break;
1120 // Ok, we have a PHI of the form L op= R. Check for low
1121 // zero bits.
1122 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1123 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1124 Mask2 = APInt::getLowBitsSet(BitWidth,
1125 KnownZero2.countTrailingOnes());
1126 KnownOne2.clear();
1127 KnownZero2.clear();
1128 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1129 KnownZero = Mask &
1130 APInt::getLowBitsSet(BitWidth,
1131 KnownZero2.countTrailingOnes());
1132 break;
1133 }
1134 }
1135 }
1136 break;
1137 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001138 case Instruction::Call:
1139 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1140 switch (II->getIntrinsicID()) {
1141 default: break;
1142 case Intrinsic::ctpop:
1143 case Intrinsic::ctlz:
1144 case Intrinsic::cttz: {
1145 unsigned LowBits = Log2_32(BitWidth)+1;
1146 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1147 break;
1148 }
1149 }
1150 }
1151 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 }
1153}
1154
1155/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1156/// this predicate to simplify operations downstream. Mask is known to be zero
1157/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001158bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1159 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1161 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1163 return (KnownZero & Mask) == Mask;
1164}
1165
1166/// ShrinkDemandedConstant - Check to see if the specified operand of the
1167/// specified instruction is a constant integer. If so, check to see if there
1168/// are any bits set in the constant that are not demanded. If so, shrink the
1169/// constant and return true.
1170static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1171 APInt Demanded) {
1172 assert(I && "No instruction?");
1173 assert(OpNo < I->getNumOperands() && "Operand index too large");
1174
1175 // If the operand is not a constant integer, nothing to do.
1176 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1177 if (!OpC) return false;
1178
1179 // If there are no bits set that aren't demanded, nothing to do.
1180 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1181 if ((~Demanded & OpC->getValue()) == 0)
1182 return false;
1183
1184 // This instruction is producing bits that are not demanded. Shrink the RHS.
1185 Demanded &= OpC->getValue();
1186 I->setOperand(OpNo, ConstantInt::get(Demanded));
1187 return true;
1188}
1189
1190// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1191// set of known zero and one bits, compute the maximum and minimum values that
1192// could have the specified known zero and known one bits, returning them in
1193// min/max.
1194static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1195 const APInt& KnownZero,
1196 const APInt& KnownOne,
1197 APInt& Min, APInt& Max) {
1198 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1199 assert(KnownZero.getBitWidth() == BitWidth &&
1200 KnownOne.getBitWidth() == BitWidth &&
1201 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1202 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1203 APInt UnknownBits = ~(KnownZero|KnownOne);
1204
1205 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1206 // bit if it is unknown.
1207 Min = KnownOne;
1208 Max = KnownOne|UnknownBits;
1209
1210 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1211 Min.set(BitWidth-1);
1212 Max.clear(BitWidth-1);
1213 }
1214}
1215
1216// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1217// a set of known zero and one bits, compute the maximum and minimum values that
1218// could have the specified known zero and known one bits, returning them in
1219// min/max.
1220static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001221 const APInt &KnownZero,
1222 const APInt &KnownOne,
1223 APInt &Min, APInt &Max) {
1224 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 assert(KnownZero.getBitWidth() == BitWidth &&
1226 KnownOne.getBitWidth() == BitWidth &&
1227 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1228 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1229 APInt UnknownBits = ~(KnownZero|KnownOne);
1230
1231 // The minimum value is when the unknown bits are all zeros.
1232 Min = KnownOne;
1233 // The maximum value is when the unknown bits are all ones.
1234 Max = KnownOne|UnknownBits;
1235}
1236
1237/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1238/// value based on the demanded bits. When this function is called, it is known
1239/// that only the bits set in DemandedMask of the result of V are ever used
1240/// downstream. Consequently, depending on the mask and V, it may be possible
1241/// to replace V with a constant or one of its operands. In such cases, this
1242/// function does the replacement and returns true. In all other cases, it
1243/// returns false after analyzing the expression and setting KnownOne and known
1244/// to be one in the expression. KnownZero contains all the bits that are known
1245/// to be zero in the expression. These are provided to potentially allow the
1246/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1247/// the expression. KnownOne and KnownZero always follow the invariant that
1248/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1249/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1250/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1251/// and KnownOne must all be the same.
1252bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1253 APInt& KnownZero, APInt& KnownOne,
1254 unsigned Depth) {
1255 assert(V != 0 && "Null pointer of Value???");
1256 assert(Depth <= 6 && "Limit Search Depth");
1257 uint32_t BitWidth = DemandedMask.getBitWidth();
1258 const IntegerType *VTy = cast<IntegerType>(V->getType());
1259 assert(VTy->getBitWidth() == BitWidth &&
1260 KnownZero.getBitWidth() == BitWidth &&
1261 KnownOne.getBitWidth() == BitWidth &&
1262 "Value *V, DemandedMask, KnownZero and KnownOne \
1263 must have same BitWidth");
1264 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1265 // We know all of the bits for a constant!
1266 KnownOne = CI->getValue() & DemandedMask;
1267 KnownZero = ~KnownOne & DemandedMask;
1268 return false;
1269 }
1270
1271 KnownZero.clear();
1272 KnownOne.clear();
1273 if (!V->hasOneUse()) { // Other users may use these bits.
1274 if (Depth != 0) { // Not at the root.
1275 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1276 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1277 return false;
1278 }
1279 // If this is the root being simplified, allow it to have multiple uses,
1280 // just set the DemandedMask to all bits.
1281 DemandedMask = APInt::getAllOnesValue(BitWidth);
1282 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1283 if (V != UndefValue::get(VTy))
1284 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1285 return false;
1286 } else if (Depth == 6) { // Limit search depth.
1287 return false;
1288 }
1289
1290 Instruction *I = dyn_cast<Instruction>(V);
1291 if (!I) return false; // Only analyze instructions.
1292
1293 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1294 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1295 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001296 default:
1297 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1298 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 case Instruction::And:
1300 // If either the LHS or the RHS are Zero, the result is zero.
1301 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1302 RHSKnownZero, RHSKnownOne, Depth+1))
1303 return true;
1304 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1305 "Bits known to be one AND zero?");
1306
1307 // If something is known zero on the RHS, the bits aren't demanded on the
1308 // LHS.
1309 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1310 LHSKnownZero, LHSKnownOne, Depth+1))
1311 return true;
1312 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1313 "Bits known to be one AND zero?");
1314
1315 // If all of the demanded bits are known 1 on one side, return the other.
1316 // These bits cannot contribute to the result of the 'and'.
1317 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1318 (DemandedMask & ~LHSKnownZero))
1319 return UpdateValueUsesWith(I, I->getOperand(0));
1320 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1321 (DemandedMask & ~RHSKnownZero))
1322 return UpdateValueUsesWith(I, I->getOperand(1));
1323
1324 // If all of the demanded bits in the inputs are known zeros, return zero.
1325 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1326 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1327
1328 // If the RHS is a constant, see if we can simplify it.
1329 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1330 return UpdateValueUsesWith(I, I);
1331
1332 // Output known-1 bits are only known if set in both the LHS & RHS.
1333 RHSKnownOne &= LHSKnownOne;
1334 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1335 RHSKnownZero |= LHSKnownZero;
1336 break;
1337 case Instruction::Or:
1338 // If either the LHS or the RHS are One, the result is One.
1339 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1340 RHSKnownZero, RHSKnownOne, Depth+1))
1341 return true;
1342 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1343 "Bits known to be one AND zero?");
1344 // If something is known one on the RHS, the bits aren't demanded on the
1345 // LHS.
1346 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1347 LHSKnownZero, LHSKnownOne, Depth+1))
1348 return true;
1349 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1350 "Bits known to be one AND zero?");
1351
1352 // If all of the demanded bits are known zero on one side, return the other.
1353 // These bits cannot contribute to the result of the 'or'.
1354 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1355 (DemandedMask & ~LHSKnownOne))
1356 return UpdateValueUsesWith(I, I->getOperand(0));
1357 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1358 (DemandedMask & ~RHSKnownOne))
1359 return UpdateValueUsesWith(I, I->getOperand(1));
1360
1361 // If all of the potentially set bits on one side are known to be set on
1362 // the other side, just use the 'other' side.
1363 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1364 (DemandedMask & (~RHSKnownZero)))
1365 return UpdateValueUsesWith(I, I->getOperand(0));
1366 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1367 (DemandedMask & (~LHSKnownZero)))
1368 return UpdateValueUsesWith(I, I->getOperand(1));
1369
1370 // If the RHS is a constant, see if we can simplify it.
1371 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1372 return UpdateValueUsesWith(I, I);
1373
1374 // Output known-0 bits are only known if clear in both the LHS & RHS.
1375 RHSKnownZero &= LHSKnownZero;
1376 // Output known-1 are known to be set if set in either the LHS | RHS.
1377 RHSKnownOne |= LHSKnownOne;
1378 break;
1379 case Instruction::Xor: {
1380 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1381 RHSKnownZero, RHSKnownOne, Depth+1))
1382 return true;
1383 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1384 "Bits known to be one AND zero?");
1385 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1386 LHSKnownZero, LHSKnownOne, Depth+1))
1387 return true;
1388 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1389 "Bits known to be one AND zero?");
1390
1391 // If all of the demanded bits are known zero on one side, return the other.
1392 // These bits cannot contribute to the result of the 'xor'.
1393 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1394 return UpdateValueUsesWith(I, I->getOperand(0));
1395 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1396 return UpdateValueUsesWith(I, I->getOperand(1));
1397
1398 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1399 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1400 (RHSKnownOne & LHSKnownOne);
1401 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1402 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1403 (RHSKnownOne & LHSKnownZero);
1404
1405 // If all of the demanded bits are known to be zero on one side or the
1406 // other, turn this into an *inclusive* or.
1407 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1408 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1409 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001410 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 I->getName());
1412 InsertNewInstBefore(Or, *I);
1413 return UpdateValueUsesWith(I, Or);
1414 }
1415
1416 // If all of the demanded bits on one side are known, and all of the set
1417 // bits on that side are also known to be set on the other side, turn this
1418 // into an AND, as we know the bits will be cleared.
1419 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1420 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1421 // all known
1422 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1423 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1424 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001425 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 InsertNewInstBefore(And, *I);
1427 return UpdateValueUsesWith(I, And);
1428 }
1429 }
1430
1431 // If the RHS is a constant, see if we can simplify it.
1432 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1433 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1434 return UpdateValueUsesWith(I, I);
1435
1436 RHSKnownZero = KnownZeroOut;
1437 RHSKnownOne = KnownOneOut;
1438 break;
1439 }
1440 case Instruction::Select:
1441 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1442 RHSKnownZero, RHSKnownOne, Depth+1))
1443 return true;
1444 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1445 LHSKnownZero, LHSKnownOne, Depth+1))
1446 return true;
1447 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1448 "Bits known to be one AND zero?");
1449 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1450 "Bits known to be one AND zero?");
1451
1452 // If the operands are constants, see if we can simplify them.
1453 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1454 return UpdateValueUsesWith(I, I);
1455 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1456 return UpdateValueUsesWith(I, I);
1457
1458 // Only known if known in both the LHS and RHS.
1459 RHSKnownOne &= LHSKnownOne;
1460 RHSKnownZero &= LHSKnownZero;
1461 break;
1462 case Instruction::Trunc: {
1463 uint32_t truncBf =
1464 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1465 DemandedMask.zext(truncBf);
1466 RHSKnownZero.zext(truncBf);
1467 RHSKnownOne.zext(truncBf);
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
1470 return true;
1471 DemandedMask.trunc(BitWidth);
1472 RHSKnownZero.trunc(BitWidth);
1473 RHSKnownOne.trunc(BitWidth);
1474 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1475 "Bits known to be one AND zero?");
1476 break;
1477 }
1478 case Instruction::BitCast:
1479 if (!I->getOperand(0)->getType()->isInteger())
1480 return false;
1481
1482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
1484 return true;
1485 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1486 "Bits known to be one AND zero?");
1487 break;
1488 case Instruction::ZExt: {
1489 // Compute the bits in the result that are not present in the input.
1490 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1491 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1492
1493 DemandedMask.trunc(SrcBitWidth);
1494 RHSKnownZero.trunc(SrcBitWidth);
1495 RHSKnownOne.trunc(SrcBitWidth);
1496 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1497 RHSKnownZero, RHSKnownOne, Depth+1))
1498 return true;
1499 DemandedMask.zext(BitWidth);
1500 RHSKnownZero.zext(BitWidth);
1501 RHSKnownOne.zext(BitWidth);
1502 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1503 "Bits known to be one AND zero?");
1504 // The top bits are known to be zero.
1505 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1506 break;
1507 }
1508 case Instruction::SExt: {
1509 // Compute the bits in the result that are not present in the input.
1510 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1511 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1512
1513 APInt InputDemandedBits = DemandedMask &
1514 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1515
1516 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1517 // If any of the sign extended bits are demanded, we know that the sign
1518 // bit is demanded.
1519 if ((NewBits & DemandedMask) != 0)
1520 InputDemandedBits.set(SrcBitWidth-1);
1521
1522 InputDemandedBits.trunc(SrcBitWidth);
1523 RHSKnownZero.trunc(SrcBitWidth);
1524 RHSKnownOne.trunc(SrcBitWidth);
1525 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1526 RHSKnownZero, RHSKnownOne, Depth+1))
1527 return true;
1528 InputDemandedBits.zext(BitWidth);
1529 RHSKnownZero.zext(BitWidth);
1530 RHSKnownOne.zext(BitWidth);
1531 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1532 "Bits known to be one AND zero?");
1533
1534 // If the sign bit of the input is known set or clear, then we know the
1535 // top bits of the result.
1536
1537 // If the input sign bit is known zero, or if the NewBits are not demanded
1538 // convert this into a zero extension.
1539 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1540 {
1541 // Convert to ZExt cast
1542 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1543 return UpdateValueUsesWith(I, NewCast);
1544 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1545 RHSKnownOne |= NewBits;
1546 }
1547 break;
1548 }
1549 case Instruction::Add: {
1550 // Figure out what the input bits are. If the top bits of the and result
1551 // are not demanded, then the add doesn't demand them from its input
1552 // either.
1553 uint32_t NLZ = DemandedMask.countLeadingZeros();
1554
1555 // If there is a constant on the RHS, there are a variety of xformations
1556 // we can do.
1557 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1558 // If null, this should be simplified elsewhere. Some of the xforms here
1559 // won't work if the RHS is zero.
1560 if (RHS->isZero())
1561 break;
1562
1563 // If the top bit of the output is demanded, demand everything from the
1564 // input. Otherwise, we demand all the input bits except NLZ top bits.
1565 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1566
1567 // Find information about known zero/one bits in the input.
1568 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1569 LHSKnownZero, LHSKnownOne, Depth+1))
1570 return true;
1571
1572 // If the RHS of the add has bits set that can't affect the input, reduce
1573 // the constant.
1574 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1575 return UpdateValueUsesWith(I, I);
1576
1577 // Avoid excess work.
1578 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1579 break;
1580
1581 // Turn it into OR if input bits are zero.
1582 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1583 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001584 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585 I->getName());
1586 InsertNewInstBefore(Or, *I);
1587 return UpdateValueUsesWith(I, Or);
1588 }
1589
1590 // We can say something about the output known-zero and known-one bits,
1591 // depending on potential carries from the input constant and the
1592 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1593 // bits set and the RHS constant is 0x01001, then we know we have a known
1594 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1595
1596 // To compute this, we first compute the potential carry bits. These are
1597 // the bits which may be modified. I'm not aware of a better way to do
1598 // this scan.
1599 const APInt& RHSVal = RHS->getValue();
1600 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1601
1602 // Now that we know which bits have carries, compute the known-1/0 sets.
1603
1604 // Bits are known one if they are known zero in one operand and one in the
1605 // other, and there is no input carry.
1606 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1607 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1608
1609 // Bits are known zero if they are known zero in both operands and there
1610 // is no input carry.
1611 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1612 } else {
1613 // If the high-bits of this ADD are not demanded, then it does not demand
1614 // the high bits of its LHS or RHS.
1615 if (DemandedMask[BitWidth-1] == 0) {
1616 // Right fill the mask of bits for this ADD to demand the most
1617 // significant bit and all those below it.
1618 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1619 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1620 LHSKnownZero, LHSKnownOne, Depth+1))
1621 return true;
1622 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1623 LHSKnownZero, LHSKnownOne, Depth+1))
1624 return true;
1625 }
1626 }
1627 break;
1628 }
1629 case Instruction::Sub:
1630 // If the high-bits of this SUB are not demanded, then it does not demand
1631 // the high bits of its LHS or RHS.
1632 if (DemandedMask[BitWidth-1] == 0) {
1633 // Right fill the mask of bits for this SUB to demand the most
1634 // significant bit and all those below it.
1635 uint32_t NLZ = DemandedMask.countLeadingZeros();
1636 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1637 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1638 LHSKnownZero, LHSKnownOne, Depth+1))
1639 return true;
1640 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1641 LHSKnownZero, LHSKnownOne, Depth+1))
1642 return true;
1643 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001644 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1645 // the known zeros and ones.
1646 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 break;
1648 case Instruction::Shl:
1649 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1650 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1651 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1652 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1653 RHSKnownZero, RHSKnownOne, Depth+1))
1654 return true;
1655 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1656 "Bits known to be one AND zero?");
1657 RHSKnownZero <<= ShiftAmt;
1658 RHSKnownOne <<= ShiftAmt;
1659 // low bits known zero.
1660 if (ShiftAmt)
1661 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1662 }
1663 break;
1664 case Instruction::LShr:
1665 // For a logical shift right
1666 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1667 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1668
1669 // Unsigned shift right.
1670 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1671 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1672 RHSKnownZero, RHSKnownOne, Depth+1))
1673 return true;
1674 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1675 "Bits known to be one AND zero?");
1676 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1677 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1678 if (ShiftAmt) {
1679 // Compute the new bits that are at the top now.
1680 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1681 RHSKnownZero |= HighBits; // high bits known zero.
1682 }
1683 }
1684 break;
1685 case Instruction::AShr:
1686 // If this is an arithmetic shift right and only the low-bit is set, we can
1687 // always convert this into a logical shr, even if the shift amount is
1688 // variable. The low bit of the shift cannot be an input sign bit unless
1689 // the shift amount is >= the size of the datatype, which is undefined.
1690 if (DemandedMask == 1) {
1691 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001692 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693 I->getOperand(0), I->getOperand(1), I->getName());
1694 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1695 return UpdateValueUsesWith(I, NewVal);
1696 }
1697
1698 // If the sign bit is the only bit demanded by this ashr, then there is no
1699 // need to do it, the shift doesn't change the high bit.
1700 if (DemandedMask.isSignBit())
1701 return UpdateValueUsesWith(I, I->getOperand(0));
1702
1703 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1704 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1705
1706 // Signed shift right.
1707 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1708 // If any of the "high bits" are demanded, we should set the sign bit as
1709 // demanded.
1710 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1711 DemandedMaskIn.set(BitWidth-1);
1712 if (SimplifyDemandedBits(I->getOperand(0),
1713 DemandedMaskIn,
1714 RHSKnownZero, RHSKnownOne, Depth+1))
1715 return true;
1716 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1717 "Bits known to be one AND zero?");
1718 // Compute the new bits that are at the top now.
1719 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1720 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1721 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1722
1723 // Handle the sign bits.
1724 APInt SignBit(APInt::getSignBit(BitWidth));
1725 // Adjust to where it is now in the mask.
1726 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1727
1728 // If the input sign bit is known to be zero, or if none of the top bits
1729 // are demanded, turn this into an unsigned shift right.
1730 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1731 (HighBits & ~DemandedMask) == HighBits) {
1732 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001733 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 I->getOperand(0), SA, I->getName());
1735 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1736 return UpdateValueUsesWith(I, NewVal);
1737 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1738 RHSKnownOne |= HighBits;
1739 }
1740 }
1741 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001742 case Instruction::SRem:
1743 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1744 APInt RA = Rem->getValue();
1745 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001746 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001747 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1748 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1749 LHSKnownZero, LHSKnownOne, Depth+1))
1750 return true;
1751
1752 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1753 LHSKnownZero |= ~LowBits;
1754 else if (LHSKnownOne[BitWidth-1])
1755 LHSKnownOne |= ~LowBits;
1756
1757 KnownZero |= LHSKnownZero & DemandedMask;
1758 KnownOne |= LHSKnownOne & DemandedMask;
1759
1760 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1761 }
1762 }
1763 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001764 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001765 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1766 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001767 if (RA.isPowerOf2()) {
1768 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001769 APInt Mask2 = LowBits & DemandedMask;
1770 KnownZero |= ~LowBits & DemandedMask;
1771 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1772 KnownZero, KnownOne, Depth+1))
1773 return true;
1774
1775 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001776 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001777 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001778 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001779
1780 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1781 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001782 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1783 KnownZero2, KnownOne2, Depth+1))
1784 return true;
1785
Dan Gohmanbec16052008-04-28 17:02:21 +00001786 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001787 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001788 KnownZero2, KnownOne2, Depth+1))
1789 return true;
1790
1791 Leaders = std::max(Leaders,
1792 KnownZero2.countLeadingOnes());
1793 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001794 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001796 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001797
1798 // If the client is only demanding bits that we know, return the known
1799 // constant.
1800 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1801 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1802 return false;
1803}
1804
1805
1806/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1807/// 64 or fewer elements. DemandedElts contains the set of elements that are
1808/// actually used by the caller. This method analyzes which elements of the
1809/// operand are undef and returns that information in UndefElts.
1810///
1811/// If the information about demanded elements can be used to simplify the
1812/// operation, the operation is simplified, then the resultant value is
1813/// returned. This returns null if no change was made.
1814Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1815 uint64_t &UndefElts,
1816 unsigned Depth) {
1817 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1818 assert(VWidth <= 64 && "Vector too wide to analyze!");
1819 uint64_t EltMask = ~0ULL >> (64-VWidth);
1820 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1821 "Invalid DemandedElts!");
1822
1823 if (isa<UndefValue>(V)) {
1824 // If the entire vector is undefined, just return this info.
1825 UndefElts = EltMask;
1826 return 0;
1827 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1828 UndefElts = EltMask;
1829 return UndefValue::get(V->getType());
1830 }
1831
1832 UndefElts = 0;
1833 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1834 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1835 Constant *Undef = UndefValue::get(EltTy);
1836
1837 std::vector<Constant*> Elts;
1838 for (unsigned i = 0; i != VWidth; ++i)
1839 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1840 Elts.push_back(Undef);
1841 UndefElts |= (1ULL << i);
1842 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1843 Elts.push_back(Undef);
1844 UndefElts |= (1ULL << i);
1845 } else { // Otherwise, defined.
1846 Elts.push_back(CP->getOperand(i));
1847 }
1848
1849 // If we changed the constant, return it.
1850 Constant *NewCP = ConstantVector::get(Elts);
1851 return NewCP != CP ? NewCP : 0;
1852 } else if (isa<ConstantAggregateZero>(V)) {
1853 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1854 // set to undef.
1855 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1856 Constant *Zero = Constant::getNullValue(EltTy);
1857 Constant *Undef = UndefValue::get(EltTy);
1858 std::vector<Constant*> Elts;
1859 for (unsigned i = 0; i != VWidth; ++i)
1860 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1861 UndefElts = DemandedElts ^ EltMask;
1862 return ConstantVector::get(Elts);
1863 }
1864
1865 if (!V->hasOneUse()) { // Other users may use these bits.
1866 if (Depth != 0) { // Not at the root.
1867 // TODO: Just compute the UndefElts information recursively.
1868 return false;
1869 }
1870 return false;
1871 } else if (Depth == 10) { // Limit search depth.
1872 return false;
1873 }
1874
1875 Instruction *I = dyn_cast<Instruction>(V);
1876 if (!I) return false; // Only analyze instructions.
1877
1878 bool MadeChange = false;
1879 uint64_t UndefElts2;
1880 Value *TmpV;
1881 switch (I->getOpcode()) {
1882 default: break;
1883
1884 case Instruction::InsertElement: {
1885 // If this is a variable index, we don't know which element it overwrites.
1886 // demand exactly the same input as we produce.
1887 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1888 if (Idx == 0) {
1889 // Note that we can't propagate undef elt info, because we don't know
1890 // which elt is getting updated.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1892 UndefElts2, Depth+1);
1893 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1894 break;
1895 }
1896
1897 // If this is inserting an element that isn't demanded, remove this
1898 // insertelement.
1899 unsigned IdxNo = Idx->getZExtValue();
1900 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1901 return AddSoonDeadInstToWorklist(*I, 0);
1902
1903 // Otherwise, the element inserted overwrites whatever was there, so the
1904 // input demanded set is simpler than the output set.
1905 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1906 DemandedElts & ~(1ULL << IdxNo),
1907 UndefElts, Depth+1);
1908 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1909
1910 // The inserted element is defined.
1911 UndefElts |= 1ULL << IdxNo;
1912 break;
1913 }
1914 case Instruction::BitCast: {
1915 // Vector->vector casts only.
1916 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1917 if (!VTy) break;
1918 unsigned InVWidth = VTy->getNumElements();
1919 uint64_t InputDemandedElts = 0;
1920 unsigned Ratio;
1921
1922 if (VWidth == InVWidth) {
1923 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1924 // elements as are demanded of us.
1925 Ratio = 1;
1926 InputDemandedElts = DemandedElts;
1927 } else if (VWidth > InVWidth) {
1928 // Untested so far.
1929 break;
1930
1931 // If there are more elements in the result than there are in the source,
1932 // then an input element is live if any of the corresponding output
1933 // elements are live.
1934 Ratio = VWidth/InVWidth;
1935 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1936 if (DemandedElts & (1ULL << OutIdx))
1937 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1938 }
1939 } else {
1940 // Untested so far.
1941 break;
1942
1943 // If there are more elements in the source than there are in the result,
1944 // then an input element is live if the corresponding output element is
1945 // live.
1946 Ratio = InVWidth/VWidth;
1947 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1948 if (DemandedElts & (1ULL << InIdx/Ratio))
1949 InputDemandedElts |= 1ULL << InIdx;
1950 }
1951
1952 // div/rem demand all inputs, because they don't want divide by zero.
1953 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1954 UndefElts2, Depth+1);
1955 if (TmpV) {
1956 I->setOperand(0, TmpV);
1957 MadeChange = true;
1958 }
1959
1960 UndefElts = UndefElts2;
1961 if (VWidth > InVWidth) {
1962 assert(0 && "Unimp");
1963 // If there are more elements in the result than there are in the source,
1964 // then an output element is undef if the corresponding input element is
1965 // undef.
1966 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1967 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1968 UndefElts |= 1ULL << OutIdx;
1969 } else if (VWidth < InVWidth) {
1970 assert(0 && "Unimp");
1971 // If there are more elements in the source than there are in the result,
1972 // then a result element is undef if all of the corresponding input
1973 // elements are undef.
1974 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1975 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1976 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1977 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1978 }
1979 break;
1980 }
1981 case Instruction::And:
1982 case Instruction::Or:
1983 case Instruction::Xor:
1984 case Instruction::Add:
1985 case Instruction::Sub:
1986 case Instruction::Mul:
1987 // div/rem demand all inputs, because they don't want divide by zero.
1988 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1989 UndefElts, Depth+1);
1990 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1991 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1992 UndefElts2, Depth+1);
1993 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1994
1995 // Output elements are undefined if both are undefined. Consider things
1996 // like undef&0. The result is known zero, not undef.
1997 UndefElts &= UndefElts2;
1998 break;
1999
2000 case Instruction::Call: {
2001 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2002 if (!II) break;
2003 switch (II->getIntrinsicID()) {
2004 default: break;
2005
2006 // Binary vector operations that work column-wise. A dest element is a
2007 // function of the corresponding input elements from the two inputs.
2008 case Intrinsic::x86_sse_sub_ss:
2009 case Intrinsic::x86_sse_mul_ss:
2010 case Intrinsic::x86_sse_min_ss:
2011 case Intrinsic::x86_sse_max_ss:
2012 case Intrinsic::x86_sse2_sub_sd:
2013 case Intrinsic::x86_sse2_mul_sd:
2014 case Intrinsic::x86_sse2_min_sd:
2015 case Intrinsic::x86_sse2_max_sd:
2016 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2017 UndefElts, Depth+1);
2018 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2019 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2020 UndefElts2, Depth+1);
2021 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2022
2023 // If only the low elt is demanded and this is a scalarizable intrinsic,
2024 // scalarize it now.
2025 if (DemandedElts == 1) {
2026 switch (II->getIntrinsicID()) {
2027 default: break;
2028 case Intrinsic::x86_sse_sub_ss:
2029 case Intrinsic::x86_sse_mul_ss:
2030 case Intrinsic::x86_sse2_sub_sd:
2031 case Intrinsic::x86_sse2_mul_sd:
2032 // TODO: Lower MIN/MAX/ABS/etc
2033 Value *LHS = II->getOperand(1);
2034 Value *RHS = II->getOperand(2);
2035 // Extract the element as scalars.
2036 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2037 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2038
2039 switch (II->getIntrinsicID()) {
2040 default: assert(0 && "Case stmts out of sync!");
2041 case Intrinsic::x86_sse_sub_ss:
2042 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002043 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044 II->getName()), *II);
2045 break;
2046 case Intrinsic::x86_sse_mul_ss:
2047 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002048 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049 II->getName()), *II);
2050 break;
2051 }
2052
2053 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00002054 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2055 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056 InsertNewInstBefore(New, *II);
2057 AddSoonDeadInstToWorklist(*II, 0);
2058 return New;
2059 }
2060 }
2061
2062 // Output elements are undefined if both are undefined. Consider things
2063 // like undef&0. The result is known zero, not undef.
2064 UndefElts &= UndefElts2;
2065 break;
2066 }
2067 break;
2068 }
2069 }
2070 return MadeChange ? I : 0;
2071}
2072
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073/// AssociativeOpt - Perform an optimization on an associative operator. This
2074/// function is designed to check a chain of associative operators for a
2075/// potential to apply a certain optimization. Since the optimization may be
2076/// applicable if the expression was reassociated, this checks the chain, then
2077/// reassociates the expression as necessary to expose the optimization
2078/// opportunity. This makes use of a special Functor, which must define
2079/// 'shouldApply' and 'apply' methods.
2080///
2081template<typename Functor>
2082Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2083 unsigned Opcode = Root.getOpcode();
2084 Value *LHS = Root.getOperand(0);
2085
2086 // Quick check, see if the immediate LHS matches...
2087 if (F.shouldApply(LHS))
2088 return F.apply(Root);
2089
2090 // Otherwise, if the LHS is not of the same opcode as the root, return.
2091 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2092 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2093 // Should we apply this transform to the RHS?
2094 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2095
2096 // If not to the RHS, check to see if we should apply to the LHS...
2097 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2098 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2099 ShouldApply = true;
2100 }
2101
2102 // If the functor wants to apply the optimization to the RHS of LHSI,
2103 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2104 if (ShouldApply) {
2105 BasicBlock *BB = Root.getParent();
2106
2107 // Now all of the instructions are in the current basic block, go ahead
2108 // and perform the reassociation.
2109 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2110
2111 // First move the selected RHS to the LHS of the root...
2112 Root.setOperand(0, LHSI->getOperand(1));
2113
2114 // Make what used to be the LHS of the root be the user of the root...
2115 Value *ExtraOperand = TmpLHSI->getOperand(1);
2116 if (&Root == TmpLHSI) {
2117 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2118 return 0;
2119 }
2120 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2121 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2122 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2123 BasicBlock::iterator ARI = &Root; ++ARI;
2124 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2125 ARI = Root;
2126
2127 // Now propagate the ExtraOperand down the chain of instructions until we
2128 // get to LHSI.
2129 while (TmpLHSI != LHSI) {
2130 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2131 // Move the instruction to immediately before the chain we are
2132 // constructing to avoid breaking dominance properties.
2133 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2134 BB->getInstList().insert(ARI, NextLHSI);
2135 ARI = NextLHSI;
2136
2137 Value *NextOp = NextLHSI->getOperand(1);
2138 NextLHSI->setOperand(1, ExtraOperand);
2139 TmpLHSI = NextLHSI;
2140 ExtraOperand = NextOp;
2141 }
2142
2143 // Now that the instructions are reassociated, have the functor perform
2144 // the transformation...
2145 return F.apply(Root);
2146 }
2147
2148 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2149 }
2150 return 0;
2151}
2152
Dan Gohman089efff2008-05-13 00:00:25 +00002153namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154
2155// AddRHS - Implements: X + X --> X << 1
2156struct AddRHS {
2157 Value *RHS;
2158 AddRHS(Value *rhs) : RHS(rhs) {}
2159 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2160 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateShl(Add.getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162 ConstantInt::get(Add.getType(), 1));
2163 }
2164};
2165
2166// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2167// iff C1&C2 == 0
2168struct AddMaskingAnd {
2169 Constant *C2;
2170 AddMaskingAnd(Constant *c) : C2(c) {}
2171 bool shouldApply(Value *LHS) const {
2172 ConstantInt *C1;
2173 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2174 ConstantExpr::getAnd(C1, C2)->isNullValue();
2175 }
2176 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002177 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178 }
2179};
2180
Dan Gohman089efff2008-05-13 00:00:25 +00002181}
2182
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2184 InstCombiner *IC) {
2185 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2186 if (Constant *SOC = dyn_cast<Constant>(SO))
2187 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2188
Gabor Greifa645dd32008-05-16 19:29:10 +00002189 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2191 }
2192
2193 // Figure out if the constant is the left or the right argument.
2194 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2195 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2196
2197 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2198 if (ConstIsRHS)
2199 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2200 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2201 }
2202
2203 Value *Op0 = SO, *Op1 = ConstOperand;
2204 if (!ConstIsRHS)
2205 std::swap(Op0, Op1);
2206 Instruction *New;
2207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002208 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002210 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211 SO->getName()+".cmp");
2212 else {
2213 assert(0 && "Unknown binary instruction type!");
2214 abort();
2215 }
2216 return IC->InsertNewInstBefore(New, I);
2217}
2218
2219// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2220// constant as the other operand, try to fold the binary operator into the
2221// select arguments. This also works for Cast instructions, which obviously do
2222// not have a second operand.
2223static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2224 InstCombiner *IC) {
2225 // Don't modify shared select instructions
2226 if (!SI->hasOneUse()) return 0;
2227 Value *TV = SI->getOperand(1);
2228 Value *FV = SI->getOperand(2);
2229
2230 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2231 // Bool selects with constant operands can be folded to logical ops.
2232 if (SI->getType() == Type::Int1Ty) return 0;
2233
2234 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2235 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2236
Gabor Greifd6da1d02008-04-06 20:25:17 +00002237 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2238 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002239 }
2240 return 0;
2241}
2242
2243
2244/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2245/// node as operand #0, see if we can fold the instruction into the PHI (which
2246/// is only possible if all operands to the PHI are constants).
2247Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2248 PHINode *PN = cast<PHINode>(I.getOperand(0));
2249 unsigned NumPHIValues = PN->getNumIncomingValues();
2250 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2251
2252 // Check to see if all of the operands of the PHI are constants. If there is
2253 // one non-constant value, remember the BB it is. If there is more than one
2254 // or if *it* is a PHI, bail out.
2255 BasicBlock *NonConstBB = 0;
2256 for (unsigned i = 0; i != NumPHIValues; ++i)
2257 if (!isa<Constant>(PN->getIncomingValue(i))) {
2258 if (NonConstBB) return 0; // More than one non-const value.
2259 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2260 NonConstBB = PN->getIncomingBlock(i);
2261
2262 // If the incoming non-constant value is in I's block, we have an infinite
2263 // loop.
2264 if (NonConstBB == I.getParent())
2265 return 0;
2266 }
2267
2268 // If there is exactly one non-constant value, we can insert a copy of the
2269 // operation in that block. However, if this is a critical edge, we would be
2270 // inserting the computation one some other paths (e.g. inside a loop). Only
2271 // do this if the pred block is unconditionally branching into the phi block.
2272 if (NonConstBB) {
2273 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2274 if (!BI || !BI->isUnconditional()) return 0;
2275 }
2276
2277 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002278 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2280 InsertNewInstBefore(NewPN, *PN);
2281 NewPN->takeName(PN);
2282
2283 // Next, add all of the operands to the PHI.
2284 if (I.getNumOperands() == 2) {
2285 Constant *C = cast<Constant>(I.getOperand(1));
2286 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002287 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2289 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2290 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2291 else
2292 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2293 } else {
2294 assert(PN->getIncomingBlock(i) == NonConstBB);
2295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002296 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 PN->getIncomingValue(i), C, "phitmp",
2298 NonConstBB->getTerminator());
2299 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002300 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301 CI->getPredicate(),
2302 PN->getIncomingValue(i), C, "phitmp",
2303 NonConstBB->getTerminator());
2304 else
2305 assert(0 && "Unknown binop!");
2306
2307 AddToWorkList(cast<Instruction>(InV));
2308 }
2309 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2310 }
2311 } else {
2312 CastInst *CI = cast<CastInst>(&I);
2313 const Type *RetTy = CI->getType();
2314 for (unsigned i = 0; i != NumPHIValues; ++i) {
2315 Value *InV;
2316 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2317 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2318 } else {
2319 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002320 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 I.getType(), "phitmp",
2322 NonConstBB->getTerminator());
2323 AddToWorkList(cast<Instruction>(InV));
2324 }
2325 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2326 }
2327 }
2328 return ReplaceInstUsesWith(I, NewPN);
2329}
2330
Chris Lattner55476162008-01-29 06:52:45 +00002331
2332/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2333/// value is never equal to -0.0.
2334///
2335/// Note that this function will need to be revisited when we support nondefault
2336/// rounding modes!
2337///
2338static bool CannotBeNegativeZero(const Value *V) {
2339 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2340 return !CFP->getValueAPF().isNegZero();
2341
2342 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2343 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2344 if (I->getOpcode() == Instruction::Add &&
2345 isa<ConstantFP>(I->getOperand(1)) &&
2346 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2347 return true;
2348
2349 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2350 if (II->getIntrinsicID() == Intrinsic::sqrt)
2351 return CannotBeNegativeZero(II->getOperand(1));
2352
2353 if (const CallInst *CI = dyn_cast<CallInst>(I))
2354 if (const Function *F = CI->getCalledFunction()) {
2355 if (F->isDeclaration()) {
2356 switch (F->getNameLen()) {
2357 case 3: // abs(x) != -0.0
2358 if (!strcmp(F->getNameStart(), "abs")) return true;
2359 break;
2360 case 4: // abs[lf](x) != -0.0
2361 if (!strcmp(F->getNameStart(), "absf")) return true;
2362 if (!strcmp(F->getNameStart(), "absl")) return true;
2363 break;
2364 }
2365 }
2366 }
2367 }
2368
2369 return false;
2370}
2371
2372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2374 bool Changed = SimplifyCommutative(I);
2375 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2376
2377 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2378 // X + undef -> undef
2379 if (isa<UndefValue>(RHS))
2380 return ReplaceInstUsesWith(I, RHS);
2381
2382 // X + 0 --> X
2383 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2384 if (RHSC->isNullValue())
2385 return ReplaceInstUsesWith(I, LHS);
2386 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002387 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2388 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 return ReplaceInstUsesWith(I, LHS);
2390 }
2391
2392 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2393 // X + (signbit) --> X ^ signbit
2394 const APInt& Val = CI->getValue();
2395 uint32_t BitWidth = Val.getBitWidth();
2396 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398
2399 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2400 // (X & 254)+1 -> (X&254)|1
2401 if (!isa<VectorType>(I.getType())) {
2402 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2403 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2404 KnownZero, KnownOne))
2405 return &I;
2406 }
2407 }
2408
2409 if (isa<PHINode>(LHS))
2410 if (Instruction *NV = FoldOpIntoPhi(I))
2411 return NV;
2412
2413 ConstantInt *XorRHS = 0;
2414 Value *XorLHS = 0;
2415 if (isa<ConstantInt>(RHSC) &&
2416 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2417 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2418 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2419
2420 uint32_t Size = TySizeBits / 2;
2421 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2422 APInt CFF80Val(-C0080Val);
2423 do {
2424 if (TySizeBits > Size) {
2425 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2426 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2427 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2428 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2429 // This is a sign extend if the top bits are known zero.
2430 if (!MaskedValueIsZero(XorLHS,
2431 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2432 Size = 0; // Not a sign ext, but can't be any others either.
2433 break;
2434 }
2435 }
2436 Size >>= 1;
2437 C0080Val = APIntOps::lshr(C0080Val, Size);
2438 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2439 } while (Size >= 1);
2440
2441 // FIXME: This shouldn't be necessary. When the backends can handle types
2442 // with funny bit widths then this whole cascade of if statements should
2443 // be removed. It is just here to get the size of the "middle" type back
2444 // up to something that the back ends can handle.
2445 const Type *MiddleType = 0;
2446 switch (Size) {
2447 default: break;
2448 case 32: MiddleType = Type::Int32Ty; break;
2449 case 16: MiddleType = Type::Int16Ty; break;
2450 case 8: MiddleType = Type::Int8Ty; break;
2451 }
2452 if (MiddleType) {
2453 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2454 InsertNewInstBefore(NewTrunc, I);
2455 return new SExtInst(NewTrunc, I.getType(), I.getName());
2456 }
2457 }
2458 }
2459
2460 // X + X --> X << 1
2461 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2462 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2463
2464 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2465 if (RHSI->getOpcode() == Instruction::Sub)
2466 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2467 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2468 }
2469 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2470 if (LHSI->getOpcode() == Instruction::Sub)
2471 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2472 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2473 }
2474 }
2475
2476 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002477 // -A + -B --> -(A + B)
2478 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002479 if (LHS->getType()->isIntOrIntVector()) {
2480 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002481 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002482 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002483 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002484 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002485 }
2486
Gabor Greifa645dd32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002488 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489
2490 // A + -B --> A - B
2491 if (!isa<Constant>(RHS))
2492 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002493 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494
2495
2496 ConstantInt *C2;
2497 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2498 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002499 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500
2501 // X*C1 + X*C2 --> X * (C1+C2)
2502 ConstantInt *C1;
2503 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 }
2506
2507 // X + X*C --> X * (C+1)
2508 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002510
2511 // X + ~X --> -1 since ~X = -X-1
2512 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2513 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2514
2515
2516 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2517 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2518 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2519 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002520
2521 // A+B --> A|B iff A and B have no bits set in common.
2522 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2523 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2524 APInt LHSKnownOne(IT->getBitWidth(), 0);
2525 APInt LHSKnownZero(IT->getBitWidth(), 0);
2526 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2527 if (LHSKnownZero != 0) {
2528 APInt RHSKnownOne(IT->getBitWidth(), 0);
2529 APInt RHSKnownZero(IT->getBitWidth(), 0);
2530 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2531
2532 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002533 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002534 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002535 }
2536 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537
Nick Lewycky83598a72008-02-03 07:42:09 +00002538 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002539 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002540 Value *W, *X, *Y, *Z;
2541 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2542 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2543 if (W != Y) {
2544 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002545 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002546 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002547 std::swap(W, X);
2548 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002549 std::swap(Y, Z);
2550 std::swap(W, X);
2551 }
2552 }
2553
2554 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002555 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002556 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002558 }
2559 }
2560 }
2561
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2563 Value *X = 0;
2564 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002565 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566
2567 // (X & FF00) + xx00 -> (X+xx00) & FF00
2568 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2569 Constant *Anded = And(CRHS, C2);
2570 if (Anded == CRHS) {
2571 // See if all bits from the first bit set in the Add RHS up are included
2572 // in the mask. First, get the rightmost bit.
2573 const APInt& AddRHSV = CRHS->getValue();
2574
2575 // Form a mask of all bits from the lowest bit added through the top.
2576 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2577
2578 // See if the and mask includes all of these bits.
2579 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2580
2581 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2582 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002583 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 }
2587 }
2588 }
2589
2590 // Try to fold constant add into select arguments.
2591 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2592 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2593 return R;
2594 }
2595
2596 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002597 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 {
2599 CastInst *CI = dyn_cast<CastInst>(LHS);
2600 Value *Other = RHS;
2601 if (!CI) {
2602 CI = dyn_cast<CastInst>(RHS);
2603 Other = LHS;
2604 }
2605 if (CI && CI->getType()->isSized() &&
2606 (CI->getType()->getPrimitiveSizeInBits() ==
2607 TD->getIntPtrType()->getPrimitiveSizeInBits())
2608 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002609 unsigned AS =
2610 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002611 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2612 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002613 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002614 return new PtrToIntInst(I2, CI->getType());
2615 }
2616 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002617
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002618 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002619 {
2620 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2621 Value *Other = RHS;
2622 if (!SI) {
2623 SI = dyn_cast<SelectInst>(RHS);
2624 Other = LHS;
2625 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002626 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002627 Value *TV = SI->getTrueValue();
2628 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002629 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002630
2631 // Can we fold the add into the argument of the select?
2632 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002633 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2634 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002635 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002636 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2637 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002638 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002639 }
2640 }
Chris Lattner55476162008-01-29 06:52:45 +00002641
2642 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2643 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2644 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2645 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002646
2647 return Changed ? &I : 0;
2648}
2649
2650// isSignBit - Return true if the value represented by the constant only has the
2651// highest order bit set.
2652static bool isSignBit(ConstantInt *CI) {
2653 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2654 return CI->getValue() == APInt::getSignBit(NumBits);
2655}
2656
2657Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2659
2660 if (Op0 == Op1) // sub X, X -> 0
2661 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662
2663 // If this is a 'B = x-(-A)', change to B = x+A...
2664 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002666
2667 if (isa<UndefValue>(Op0))
2668 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2669 if (isa<UndefValue>(Op1))
2670 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2671
2672 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2673 // Replace (-1 - A) with (~A)...
2674 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002675 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002676
2677 // C - ~X == X + (1+C)
2678 Value *X = 0;
2679 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681
2682 // -(X >>u 31) -> (X >>s 31)
2683 // -(X >>s 31) -> (X >>u 31)
2684 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002685 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 if (SI->getOpcode() == Instruction::LShr) {
2687 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2688 // Check to see if we are shifting out everything but the sign bit.
2689 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2690 SI->getType()->getPrimitiveSizeInBits()-1) {
2691 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002692 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 SI->getOperand(0), CU, SI->getName());
2694 }
2695 }
2696 }
2697 else if (SI->getOpcode() == Instruction::AShr) {
2698 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2699 // Check to see if we are shifting out everything but the sign bit.
2700 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2701 SI->getType()->getPrimitiveSizeInBits()-1) {
2702 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002703 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704 SI->getOperand(0), CU, SI->getName());
2705 }
2706 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002707 }
2708 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709 }
2710
2711 // Try to fold constant sub into select arguments.
2712 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2713 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2714 return R;
2715
2716 if (isa<PHINode>(Op0))
2717 if (Instruction *NV = FoldOpIntoPhi(I))
2718 return NV;
2719 }
2720
2721 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2722 if (Op1I->getOpcode() == Instruction::Add &&
2723 !Op0->getType()->isFPOrFPVector()) {
2724 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2729 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2730 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 Op1I->getOperand(0));
2733 }
2734 }
2735
2736 if (Op1I->hasOneUse()) {
2737 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2738 // is not used by anyone else...
2739 //
2740 if (Op1I->getOpcode() == Instruction::Sub &&
2741 !Op1I->getType()->isFPOrFPVector()) {
2742 // Swap the two operands of the subexpr...
2743 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2744 Op1I->setOperand(0, IIOp1);
2745 Op1I->setOperand(1, IIOp0);
2746
2747 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002748 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749 }
2750
2751 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2752 //
2753 if (Op1I->getOpcode() == Instruction::And &&
2754 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2755 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2756
2757 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002758 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2759 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760 }
2761
2762 // 0 - (X sdiv C) -> (X sdiv -C)
2763 if (Op1I->getOpcode() == Instruction::SDiv)
2764 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2765 if (CSI->isZero())
2766 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 ConstantExpr::getNeg(DivRHS));
2769
2770 // X - X*C --> X * (1-C)
2771 ConstantInt *C2 = 0;
2772 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2773 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002774 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 }
Dan Gohmanda338742007-09-17 17:31:57 +00002776
2777 // X - ((X / Y) * Y) --> X % Y
2778 if (Op1I->getOpcode() == Instruction::Mul)
2779 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2780 if (Op0 == I->getOperand(0) &&
2781 Op1I->getOperand(1) == I->getOperand(1)) {
2782 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002784 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002786 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787 }
2788 }
2789
2790 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002791 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002792 if (Op0I->getOpcode() == Instruction::Add) {
2793 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2794 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2795 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2796 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2797 } else if (Op0I->getOpcode() == Instruction::Sub) {
2798 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002801 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802
2803 ConstantInt *C1;
2804 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2805 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807
2808 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2809 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002810 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002811 }
2812 return 0;
2813}
2814
2815/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2816/// comparison only checks the sign bit. If it only checks the sign bit, set
2817/// TrueIfSigned if the result of the comparison is true when the input value is
2818/// signed.
2819static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2820 bool &TrueIfSigned) {
2821 switch (pred) {
2822 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2823 TrueIfSigned = true;
2824 return RHS->isZero();
2825 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2826 TrueIfSigned = true;
2827 return RHS->isAllOnesValue();
2828 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2829 TrueIfSigned = false;
2830 return RHS->isAllOnesValue();
2831 case ICmpInst::ICMP_UGT:
2832 // True if LHS u> RHS and RHS == high-bit-mask - 1
2833 TrueIfSigned = true;
2834 return RHS->getValue() ==
2835 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2836 case ICmpInst::ICMP_UGE:
2837 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2838 TrueIfSigned = true;
2839 return RHS->getValue() ==
2840 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2841 default:
2842 return false;
2843 }
2844}
2845
2846Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2847 bool Changed = SimplifyCommutative(I);
2848 Value *Op0 = I.getOperand(0);
2849
2850 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2852
2853 // Simplify mul instructions with a constant RHS...
2854 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2856
2857 // ((X << C1)*C2) == (X * (C2 << C1))
2858 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2859 if (SI->getOpcode() == Instruction::Shl)
2860 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002861 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 ConstantExpr::getShl(CI, ShOp));
2863
2864 if (CI->isZero())
2865 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2866 if (CI->equalsInt(1)) // X * 1 == X
2867 return ReplaceInstUsesWith(I, Op0);
2868 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002869 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002870
2871 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2872 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002873 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002874 ConstantInt::get(Op0->getType(), Val.logBase2()));
2875 }
2876 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2877 if (Op1F->isNullValue())
2878 return ReplaceInstUsesWith(I, Op1);
2879
2880 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2881 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002882 // We need a better interface for long double here.
2883 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2884 if (Op1F->isExactlyValue(1.0))
2885 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 }
2887
2888 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2889 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002890 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002892 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 Op1, "tmp");
2894 InsertNewInstBefore(Add, I);
2895 Value *C1C2 = ConstantExpr::getMul(Op1,
2896 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002897 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002898
2899 }
2900
2901 // Try to fold constant mul into select arguments.
2902 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2903 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2904 return R;
2905
2906 if (isa<PHINode>(Op0))
2907 if (Instruction *NV = FoldOpIntoPhi(I))
2908 return NV;
2909 }
2910
2911 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2912 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002913 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914
2915 // If one of the operands of the multiply is a cast from a boolean value, then
2916 // we know the bool is either zero or one, so this is a 'masking' multiply.
2917 // See if we can simplify things based on how the boolean was originally
2918 // formed.
2919 CastInst *BoolCast = 0;
2920 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2921 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2922 BoolCast = CI;
2923 if (!BoolCast)
2924 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2925 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2926 BoolCast = CI;
2927 if (BoolCast) {
2928 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2929 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2930 const Type *SCOpTy = SCIOp0->getType();
2931 bool TIS = false;
2932
2933 // If the icmp is true iff the sign bit of X is set, then convert this
2934 // multiply into a shift/and combination.
2935 if (isa<ConstantInt>(SCIOp1) &&
2936 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2937 TIS) {
2938 // Shift the X value right to turn it into "all signbits".
2939 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2940 SCOpTy->getPrimitiveSizeInBits()-1);
2941 Value *V =
2942 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002943 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 BoolCast->getOperand(0)->getName()+
2945 ".mask"), I);
2946
2947 // If the multiply type is not the same as the source type, sign extend
2948 // or truncate to the multiply type.
2949 if (I.getType() != V->getType()) {
2950 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2951 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2952 Instruction::CastOps opcode =
2953 (SrcBits == DstBits ? Instruction::BitCast :
2954 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2955 V = InsertCastBefore(opcode, V, I.getType(), I);
2956 }
2957
2958 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 }
2961 }
2962 }
2963
2964 return Changed ? &I : 0;
2965}
2966
2967/// This function implements the transforms on div instructions that work
2968/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2969/// used by the visitors to those instructions.
2970/// @brief Transforms common to all three div instructions
2971Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2972 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973
Chris Lattner653ef3c2008-02-19 06:12:18 +00002974 // undef / X -> 0 for integer.
2975 // undef / X -> undef for FP (the undef could be a snan).
2976 if (isa<UndefValue>(Op0)) {
2977 if (Op0->getType()->isFPOrFPVector())
2978 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002980 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981
2982 // X / undef -> undef
2983 if (isa<UndefValue>(Op1))
2984 return ReplaceInstUsesWith(I, Op1);
2985
Chris Lattner5be238b2008-01-28 00:58:18 +00002986 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2987 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002989 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2990 // the same basic block, then we replace the select with Y, and the
2991 // condition of the select with false (if the cond value is in the same BB).
2992 // If the select has uses other than the div, this allows them to be
2993 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2994 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 if (ST->isNullValue()) {
2996 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2997 if (CondI && CondI->getParent() == I.getParent())
2998 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2999 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3000 I.setOperand(1, SI->getOperand(2));
3001 else
3002 UpdateValueUsesWith(SI, SI->getOperand(2));
3003 return &I;
3004 }
3005
Chris Lattner5be238b2008-01-28 00:58:18 +00003006 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3007 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008 if (ST->isNullValue()) {
3009 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3010 if (CondI && CondI->getParent() == I.getParent())
3011 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3012 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3013 I.setOperand(1, SI->getOperand(1));
3014 else
3015 UpdateValueUsesWith(SI, SI->getOperand(1));
3016 return &I;
3017 }
3018 }
3019
3020 return 0;
3021}
3022
3023/// This function implements the transforms common to both integer division
3024/// instructions (udiv and sdiv). It is called by the visitors to those integer
3025/// division instructions.
3026/// @brief Common integer divide transforms
3027Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3029
Chris Lattnercefb36c2008-05-16 02:59:42 +00003030 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3031 if (Op0 == Op1)
3032 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 if (Instruction *Common = commonDivTransforms(I))
3035 return Common;
3036
3037 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3038 // div X, 1 == X
3039 if (RHS->equalsInt(1))
3040 return ReplaceInstUsesWith(I, Op0);
3041
3042 // (X / C1) / C2 -> X / (C1*C2)
3043 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3044 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3045 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00003046 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3048 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003049 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00003050 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 }
3052
3053 if (!RHS->isZero()) { // avoid X udiv 0
3054 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3055 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3056 return R;
3057 if (isa<PHINode>(Op0))
3058 if (Instruction *NV = FoldOpIntoPhi(I))
3059 return NV;
3060 }
3061 }
3062
3063 // 0 / X == 0, we don't need to preserve faults!
3064 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3065 if (LHS->equalsInt(0))
3066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
3068 return 0;
3069}
3070
3071Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3073
3074 // Handle the integer div common cases
3075 if (Instruction *Common = commonIDivTransforms(I))
3076 return Common;
3077
3078 // X udiv C^2 -> X >> C
3079 // Check to see if this is an unsigned division with an exact power of 2,
3080 // if so, convert to a right shift.
3081 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3082 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003083 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003084 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3085 }
3086
3087 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3088 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3089 if (RHSI->getOpcode() == Instruction::Shl &&
3090 isa<ConstantInt>(RHSI->getOperand(0))) {
3091 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3092 if (C1.isPowerOf2()) {
3093 Value *N = RHSI->getOperand(1);
3094 const Type *NTy = N->getType();
3095 if (uint32_t C2 = C1.logBase2()) {
3096 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003097 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003099 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100 }
3101 }
3102 }
3103
3104 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3105 // where C1&C2 are powers of two.
3106 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3107 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3108 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3109 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3110 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3111 // Compute the shift amounts
3112 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3113 // Construct the "on true" case of the select
3114 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003115 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003116 Op0, TC, SI->getName()+".t");
3117 TSI = InsertNewInstBefore(TSI, I);
3118
3119 // Construct the "on false" case of the select
3120 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003121 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003122 Op0, FC, SI->getName()+".f");
3123 FSI = InsertNewInstBefore(FSI, I);
3124
3125 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003126 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003127 }
3128 }
3129 return 0;
3130}
3131
3132Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135 // Handle the integer div common cases
3136 if (Instruction *Common = commonIDivTransforms(I))
3137 return Common;
3138
3139 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3140 // sdiv X, -1 == -X
3141 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003142 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143
3144 // -X/C -> X/-C
3145 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00003146 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 }
3148
3149 // If the sign bits of both operands are zero (i.e. we can prove they are
3150 // unsigned inputs), turn this into a udiv.
3151 if (I.getType()->isInteger()) {
3152 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3153 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003154 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003155 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 }
3157 }
3158
3159 return 0;
3160}
3161
3162Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3163 return commonDivTransforms(I);
3164}
3165
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166/// This function implements the transforms on rem instructions that work
3167/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3168/// is used by the visitors to those instructions.
3169/// @brief Transforms common to all three rem instructions
3170Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3172
Chris Lattner653ef3c2008-02-19 06:12:18 +00003173 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174 if (Constant *LHS = dyn_cast<Constant>(Op0))
3175 if (LHS->isNullValue())
3176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3177
Chris Lattner653ef3c2008-02-19 06:12:18 +00003178 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3179 if (I.getType()->isFPOrFPVector())
3180 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003182 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003183 if (isa<UndefValue>(Op1))
3184 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3185
3186 // Handle cases involving: rem X, (select Cond, Y, Z)
3187 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3188 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3189 // the same basic block, then we replace the select with Y, and the
3190 // condition of the select with false (if the cond value is in the same
3191 // BB). If the select has uses other than the div, this allows them to be
3192 // simplified also.
3193 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3194 if (ST->isNullValue()) {
3195 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3196 if (CondI && CondI->getParent() == I.getParent())
3197 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3198 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3199 I.setOperand(1, SI->getOperand(2));
3200 else
3201 UpdateValueUsesWith(SI, SI->getOperand(2));
3202 return &I;
3203 }
3204 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3205 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3206 if (ST->isNullValue()) {
3207 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3208 if (CondI && CondI->getParent() == I.getParent())
3209 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3210 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3211 I.setOperand(1, SI->getOperand(1));
3212 else
3213 UpdateValueUsesWith(SI, SI->getOperand(1));
3214 return &I;
3215 }
3216 }
3217
3218 return 0;
3219}
3220
3221/// This function implements the transforms common to both integer remainder
3222/// instructions (urem and srem). It is called by the visitors to those integer
3223/// remainder instructions.
3224/// @brief Common integer remainder transforms
3225Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227
3228 if (Instruction *common = commonRemTransforms(I))
3229 return common;
3230
3231 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3232 // X % 0 == undef, we don't need to preserve faults!
3233 if (RHS->equalsInt(0))
3234 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3235
3236 if (RHS->equalsInt(1)) // X % 1 == 0
3237 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3238
3239 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3240 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3241 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3242 return R;
3243 } else if (isa<PHINode>(Op0I)) {
3244 if (Instruction *NV = FoldOpIntoPhi(I))
3245 return NV;
3246 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003247
3248 // See if we can fold away this rem instruction.
3249 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3250 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3251 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3252 KnownZero, KnownOne))
3253 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 }
3255 }
3256
3257 return 0;
3258}
3259
3260Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3261 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3262
3263 if (Instruction *common = commonIRemTransforms(I))
3264 return common;
3265
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3267 // X urem C^2 -> X and C
3268 // Check to see if this is an unsigned remainder with an exact power of 2,
3269 // if so, convert to a bitwise and.
3270 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3271 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003272 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273 }
3274
3275 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3276 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3277 if (RHSI->getOpcode() == Instruction::Shl &&
3278 isa<ConstantInt>(RHSI->getOperand(0))) {
3279 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3280 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003281 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003283 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 }
3285 }
3286 }
3287
3288 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289 // where C1&C2 are powers of two.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293 // STO == 0 and SFO == 0 handled above.
3294 if ((STO->getValue().isPowerOf2()) &&
3295 (SFO->getValue().isPowerOf2())) {
3296 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003297 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003299 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003300 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003301 }
3302 }
3303 }
3304
3305 return 0;
3306}
3307
3308Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
Dan Gohmandb3dd962007-11-05 23:16:33 +00003311 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312 if (Instruction *common = commonIRemTransforms(I))
3313 return common;
3314
3315 if (Value *RHSNeg = dyn_castNegVal(Op1))
3316 if (!isa<ConstantInt>(RHSNeg) ||
3317 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3318 // X % -Y -> X % Y
3319 AddUsesToWorkList(I);
3320 I.setOperand(1, RHSNeg);
3321 return &I;
3322 }
3323
Dan Gohmandb3dd962007-11-05 23:16:33 +00003324 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003325 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003326 if (I.getType()->isInteger()) {
3327 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3328 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3329 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003330 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332 }
3333
3334 return 0;
3335}
3336
3337Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3338 return commonRemTransforms(I);
3339}
3340
3341// isMaxValueMinusOne - return true if this is Max-1
3342static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3343 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3344 if (!isSigned)
3345 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3346 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3347}
3348
3349// isMinValuePlusOne - return true if this is Min+1
3350static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3351 if (!isSigned)
3352 return C->getValue() == 1; // unsigned
3353
3354 // Calculate 1111111111000000000000
3355 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3356 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3357}
3358
3359// isOneBitSet - Return true if there is exactly one bit set in the specified
3360// constant.
3361static bool isOneBitSet(const ConstantInt *CI) {
3362 return CI->getValue().isPowerOf2();
3363}
3364
3365// isHighOnes - Return true if the constant is of the form 1+0+.
3366// This is the same as lowones(~X).
3367static bool isHighOnes(const ConstantInt *CI) {
3368 return (~CI->getValue() + 1).isPowerOf2();
3369}
3370
3371/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3372/// are carefully arranged to allow folding of expressions such as:
3373///
3374/// (A < B) | (A > B) --> (A != B)
3375///
3376/// Note that this is only valid if the first and second predicates have the
3377/// same sign. Is illegal to do: (A u< B) | (A s> B)
3378///
3379/// Three bits are used to represent the condition, as follows:
3380/// 0 A > B
3381/// 1 A == B
3382/// 2 A < B
3383///
3384/// <=> Value Definition
3385/// 000 0 Always false
3386/// 001 1 A > B
3387/// 010 2 A == B
3388/// 011 3 A >= B
3389/// 100 4 A < B
3390/// 101 5 A != B
3391/// 110 6 A <= B
3392/// 111 7 Always true
3393///
3394static unsigned getICmpCode(const ICmpInst *ICI) {
3395 switch (ICI->getPredicate()) {
3396 // False -> 0
3397 case ICmpInst::ICMP_UGT: return 1; // 001
3398 case ICmpInst::ICMP_SGT: return 1; // 001
3399 case ICmpInst::ICMP_EQ: return 2; // 010
3400 case ICmpInst::ICMP_UGE: return 3; // 011
3401 case ICmpInst::ICMP_SGE: return 3; // 011
3402 case ICmpInst::ICMP_ULT: return 4; // 100
3403 case ICmpInst::ICMP_SLT: return 4; // 100
3404 case ICmpInst::ICMP_NE: return 5; // 101
3405 case ICmpInst::ICMP_ULE: return 6; // 110
3406 case ICmpInst::ICMP_SLE: return 6; // 110
3407 // True -> 7
3408 default:
3409 assert(0 && "Invalid ICmp predicate!");
3410 return 0;
3411 }
3412}
3413
3414/// getICmpValue - This is the complement of getICmpCode, which turns an
3415/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003416/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417/// of predicate to use in new icmp instructions.
3418static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3419 switch (code) {
3420 default: assert(0 && "Illegal ICmp code!");
3421 case 0: return ConstantInt::getFalse();
3422 case 1:
3423 if (sign)
3424 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3425 else
3426 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3427 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3428 case 3:
3429 if (sign)
3430 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3431 else
3432 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3433 case 4:
3434 if (sign)
3435 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3436 else
3437 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3438 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3439 case 6:
3440 if (sign)
3441 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3442 else
3443 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3444 case 7: return ConstantInt::getTrue();
3445 }
3446}
3447
3448static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3449 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3450 (ICmpInst::isSignedPredicate(p1) &&
3451 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3452 (ICmpInst::isSignedPredicate(p2) &&
3453 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3454}
3455
3456namespace {
3457// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3458struct FoldICmpLogical {
3459 InstCombiner &IC;
3460 Value *LHS, *RHS;
3461 ICmpInst::Predicate pred;
3462 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3463 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3464 pred(ICI->getPredicate()) {}
3465 bool shouldApply(Value *V) const {
3466 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3467 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003468 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3469 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470 return false;
3471 }
3472 Instruction *apply(Instruction &Log) const {
3473 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3474 if (ICI->getOperand(0) != LHS) {
3475 assert(ICI->getOperand(1) == LHS);
3476 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3477 }
3478
3479 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3480 unsigned LHSCode = getICmpCode(ICI);
3481 unsigned RHSCode = getICmpCode(RHSICI);
3482 unsigned Code;
3483 switch (Log.getOpcode()) {
3484 case Instruction::And: Code = LHSCode & RHSCode; break;
3485 case Instruction::Or: Code = LHSCode | RHSCode; break;
3486 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3487 default: assert(0 && "Illegal logical opcode!"); return 0;
3488 }
3489
3490 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3491 ICmpInst::isSignedPredicate(ICI->getPredicate());
3492
3493 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3494 if (Instruction *I = dyn_cast<Instruction>(RV))
3495 return I;
3496 // Otherwise, it's a constant boolean value...
3497 return IC.ReplaceInstUsesWith(Log, RV);
3498 }
3499};
3500} // end anonymous namespace
3501
3502// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3503// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3504// guaranteed to be a binary operator.
3505Instruction *InstCombiner::OptAndOp(Instruction *Op,
3506 ConstantInt *OpRHS,
3507 ConstantInt *AndRHS,
3508 BinaryOperator &TheAnd) {
3509 Value *X = Op->getOperand(0);
3510 Constant *Together = 0;
3511 if (!Op->isShift())
3512 Together = And(AndRHS, OpRHS);
3513
3514 switch (Op->getOpcode()) {
3515 case Instruction::Xor:
3516 if (Op->hasOneUse()) {
3517 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003518 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 InsertNewInstBefore(And, TheAnd);
3520 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522 }
3523 break;
3524 case Instruction::Or:
3525 if (Together == AndRHS) // (X | C) & C --> C
3526 return ReplaceInstUsesWith(TheAnd, AndRHS);
3527
3528 if (Op->hasOneUse() && Together != OpRHS) {
3529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003530 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003531 InsertNewInstBefore(Or, TheAnd);
3532 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 }
3535 break;
3536 case Instruction::Add:
3537 if (Op->hasOneUse()) {
3538 // Adding a one to a single bit bit-field should be turned into an XOR
3539 // of the bit. First thing to check is to see if this AND is with a
3540 // single bit constant.
3541 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3542
3543 // If there is only one bit set...
3544 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3545 // Ok, at this point, we know that we are masking the result of the
3546 // ADD down to exactly one bit. If the constant we are adding has
3547 // no bits set below this bit, then we can eliminate the ADD.
3548 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3549
3550 // Check to see if any bits below the one bit set in AndRHSV are set.
3551 if ((AddRHS & (AndRHSV-1)) == 0) {
3552 // If not, the only thing that can effect the output of the AND is
3553 // the bit specified by AndRHSV. If that bit is set, the effect of
3554 // the XOR is to toggle the bit. If it is clear, then the ADD has
3555 // no effect.
3556 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3557 TheAnd.setOperand(0, X);
3558 return &TheAnd;
3559 } else {
3560 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003561 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 InsertNewInstBefore(NewAnd, TheAnd);
3563 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003564 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565 }
3566 }
3567 }
3568 }
3569 break;
3570
3571 case Instruction::Shl: {
3572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now!
3574 //
3575 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3576 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3577 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3578 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3579
3580 if (CI->getValue() == ShlMask) {
3581 // Masking out bits that the shift already masks
3582 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3583 } else if (CI != AndRHS) { // Reducing bits set in and.
3584 TheAnd.setOperand(1, CI);
3585 return &TheAnd;
3586 }
3587 break;
3588 }
3589 case Instruction::LShr:
3590 {
3591 // We know that the AND will not produce any of the bits shifted in, so if
3592 // the anded constant includes them, clear them now! This only applies to
3593 // unsigned shifts, because a signed shr may bring in set bits!
3594 //
3595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3599
3600 if (CI->getValue() == ShrMask) {
3601 // Masking out bits that the shift already masks.
3602 return ReplaceInstUsesWith(TheAnd, Op);
3603 } else if (CI != AndRHS) {
3604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3605 return &TheAnd;
3606 }
3607 break;
3608 }
3609 case Instruction::AShr:
3610 // Signed shr.
3611 // See if this is shifting in some sign extension, then masking it out
3612 // with an and.
3613 if (Op->hasOneUse()) {
3614 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3615 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3616 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3618 if (C == AndRHS) { // Masking out bits shifted in.
3619 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3620 // Make the argument unsigned.
3621 Value *ShVal = Op->getOperand(0);
3622 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003623 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003625 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003626 }
3627 }
3628 break;
3629 }
3630 return 0;
3631}
3632
3633
3634/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3635/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3636/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3637/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3638/// insert new instructions.
3639Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3640 bool isSigned, bool Inside,
3641 Instruction &IB) {
3642 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3643 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3644 "Lo is not <= Hi in range emission code!");
3645
3646 if (Inside) {
3647 if (Lo == Hi) // Trivially false.
3648 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3649
3650 // V >= Min && V < Hi --> V < Hi
3651 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3652 ICmpInst::Predicate pred = (isSigned ?
3653 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3654 return new ICmpInst(pred, V, Hi);
3655 }
3656
3657 // Emit V-Lo <u Hi-Lo
3658 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003659 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660 InsertNewInstBefore(Add, IB);
3661 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3662 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3663 }
3664
3665 if (Lo == Hi) // Trivially true.
3666 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3667
3668 // V < Min || V >= Hi -> V > Hi-1
3669 Hi = SubOne(cast<ConstantInt>(Hi));
3670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3671 ICmpInst::Predicate pred = (isSigned ?
3672 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3673 return new ICmpInst(pred, V, Hi);
3674 }
3675
3676 // Emit V-Lo >u Hi-1-Lo
3677 // Note that Hi has already had one subtracted from it, above.
3678 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003679 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003680 InsertNewInstBefore(Add, IB);
3681 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3682 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3683}
3684
3685// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3687// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3688// not, since all 1s are not contiguous.
3689static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3690 const APInt& V = Val->getValue();
3691 uint32_t BitWidth = Val->getType()->getBitWidth();
3692 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3693
3694 // look for the first zero bit after the run of ones
3695 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3696 // look for the first non-zero bit
3697 ME = V.getActiveBits();
3698 return true;
3699}
3700
3701/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702/// where isSub determines whether the operator is a sub. If we can fold one of
3703/// the following xforms:
3704///
3705/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708///
3709/// return (A +/- B).
3710///
3711Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3712 ConstantInt *Mask, bool isSub,
3713 Instruction &I) {
3714 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715 if (!LHSI || LHSI->getNumOperands() != 2 ||
3716 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3717
3718 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3719
3720 switch (LHSI->getOpcode()) {
3721 default: return 0;
3722 case Instruction::And:
3723 if (And(N, Mask) == Mask) {
3724 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3725 if ((Mask->getValue().countLeadingZeros() +
3726 Mask->getValue().countPopulation()) ==
3727 Mask->getValue().getBitWidth())
3728 break;
3729
3730 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731 // part, we don't need any explicit masks to take them out of A. If that
3732 // is all N is, ignore it.
3733 uint32_t MB = 0, ME = 0;
3734 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3735 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3736 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3737 if (MaskedValueIsZero(RHS, Mask))
3738 break;
3739 }
3740 }
3741 return 0;
3742 case Instruction::Or:
3743 case Instruction::Xor:
3744 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3745 if ((Mask->getValue().countLeadingZeros() +
3746 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3747 && And(N, Mask)->isZero())
3748 break;
3749 return 0;
3750 }
3751
3752 Instruction *New;
3753 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003754 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003756 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757 return InsertNewInstBefore(New, I);
3758}
3759
3760Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3761 bool Changed = SimplifyCommutative(I);
3762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3763
3764 if (isa<UndefValue>(Op1)) // X & undef -> 0
3765 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3766
3767 // and X, X = X
3768 if (Op0 == Op1)
3769 return ReplaceInstUsesWith(I, Op1);
3770
3771 // See if we can simplify any instructions used by the instruction whose sole
3772 // purpose is to compute bits we don't care about.
3773 if (!isa<VectorType>(I.getType())) {
3774 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3775 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3776 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3777 KnownZero, KnownOne))
3778 return &I;
3779 } else {
3780 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3781 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3782 return ReplaceInstUsesWith(I, I.getOperand(0));
3783 } else if (isa<ConstantAggregateZero>(Op1)) {
3784 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3785 }
3786 }
3787
3788 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3789 const APInt& AndRHSMask = AndRHS->getValue();
3790 APInt NotAndRHS(~AndRHSMask);
3791
3792 // Optimize a variety of ((val OP C1) & C2) combinations...
3793 if (isa<BinaryOperator>(Op0)) {
3794 Instruction *Op0I = cast<Instruction>(Op0);
3795 Value *Op0LHS = Op0I->getOperand(0);
3796 Value *Op0RHS = Op0I->getOperand(1);
3797 switch (Op0I->getOpcode()) {
3798 case Instruction::Xor:
3799 case Instruction::Or:
3800 // If the mask is only needed on one incoming arm, push it up.
3801 if (Op0I->hasOneUse()) {
3802 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3803 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003804 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 Op0RHS->getName()+".masked");
3806 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003807 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3809 }
3810 if (!isa<Constant>(Op0RHS) &&
3811 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3812 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003813 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003814 Op0LHS->getName()+".masked");
3815 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003816 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3818 }
3819 }
3820
3821 break;
3822 case Instruction::Add:
3823 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3824 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3825 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3826 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003828 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003829 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003830 break;
3831
3832 case Instruction::Sub:
3833 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3834 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3835 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3836 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003837 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003838 break;
3839 }
3840
3841 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3842 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3843 return Res;
3844 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3845 // If this is an integer truncation or change from signed-to-unsigned, and
3846 // if the source is an and/or with immediate, transform it. This
3847 // frequently occurs for bitfield accesses.
3848 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3849 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3850 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003851 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003852 if (CastOp->getOpcode() == Instruction::And) {
3853 // Change: and (cast (and X, C1) to T), C2
3854 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3855 // This will fold the two constants together, which may allow
3856 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003857 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 CastOp->getOperand(0), I.getType(),
3859 CastOp->getName()+".shrunk");
3860 NewCast = InsertNewInstBefore(NewCast, I);
3861 // trunc_or_bitcast(C1)&C2
3862 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3863 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003864 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003865 } else if (CastOp->getOpcode() == Instruction::Or) {
3866 // Change: and (cast (or X, C1) to T), C2
3867 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3868 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3869 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3870 return ReplaceInstUsesWith(I, AndRHS);
3871 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003872 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003873 }
3874 }
3875
3876 // Try to fold constant and into select arguments.
3877 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3878 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3879 return R;
3880 if (isa<PHINode>(Op0))
3881 if (Instruction *NV = FoldOpIntoPhi(I))
3882 return NV;
3883 }
3884
3885 Value *Op0NotVal = dyn_castNotVal(Op0);
3886 Value *Op1NotVal = dyn_castNotVal(Op1);
3887
3888 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3890
3891 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3892 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003893 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 I.getName()+".demorgan");
3895 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003896 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003897 }
3898
3899 {
3900 Value *A = 0, *B = 0, *C = 0, *D = 0;
3901 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3902 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3903 return ReplaceInstUsesWith(I, Op1);
3904
3905 // (A|B) & ~(A&B) -> A^B
3906 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3907 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003908 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909 }
3910 }
3911
3912 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3913 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3914 return ReplaceInstUsesWith(I, Op0);
3915
3916 // ~(A&B) & (A|B) -> A^B
3917 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3918 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003919 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003920 }
3921 }
3922
3923 if (Op0->hasOneUse() &&
3924 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3925 if (A == Op1) { // (A^B)&A -> A&(A^B)
3926 I.swapOperands(); // Simplify below
3927 std::swap(Op0, Op1);
3928 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3929 cast<BinaryOperator>(Op0)->swapOperands();
3930 I.swapOperands(); // Simplify below
3931 std::swap(Op0, Op1);
3932 }
3933 }
3934 if (Op1->hasOneUse() &&
3935 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3936 if (B == Op0) { // B&(A^B) -> B&(B^A)
3937 cast<BinaryOperator>(Op1)->swapOperands();
3938 std::swap(A, B);
3939 }
3940 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003941 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003943 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003944 }
3945 }
3946 }
3947
3948 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3949 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3950 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3951 return R;
3952
3953 Value *LHSVal, *RHSVal;
3954 ConstantInt *LHSCst, *RHSCst;
3955 ICmpInst::Predicate LHSCC, RHSCC;
3956 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3957 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3958 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3959 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3960 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3961 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3962 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003963 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3964
3965 // Don't try to fold ICMP_SLT + ICMP_ULT.
3966 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3967 ICmpInst::isSignedPredicate(LHSCC) ==
3968 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003969 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003970 ICmpInst::Predicate GT;
3971 if (ICmpInst::isSignedPredicate(LHSCC) ||
3972 (ICmpInst::isEquality(LHSCC) &&
3973 ICmpInst::isSignedPredicate(RHSCC)))
3974 GT = ICmpInst::ICMP_SGT;
3975 else
3976 GT = ICmpInst::ICMP_UGT;
3977
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3979 ICmpInst *LHS = cast<ICmpInst>(Op0);
3980 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3981 std::swap(LHS, RHS);
3982 std::swap(LHSCst, RHSCst);
3983 std::swap(LHSCC, RHSCC);
3984 }
3985
3986 // At this point, we know we have have two icmp instructions
3987 // comparing a value against two constants and and'ing the result
3988 // together. Because of the above check, we know that we only have
3989 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3990 // (from the FoldICmpLogical check above), that the two constants
3991 // are not equal and that the larger constant is on the RHS
3992 assert(LHSCst != RHSCst && "Compares not folded above?");
3993
3994 switch (LHSCC) {
3995 default: assert(0 && "Unknown integer condition code!");
3996 case ICmpInst::ICMP_EQ:
3997 switch (RHSCC) {
3998 default: assert(0 && "Unknown integer condition code!");
3999 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4000 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4001 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4002 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4003 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4004 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4005 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4006 return ReplaceInstUsesWith(I, LHS);
4007 }
4008 case ICmpInst::ICMP_NE:
4009 switch (RHSCC) {
4010 default: assert(0 && "Unknown integer condition code!");
4011 case ICmpInst::ICMP_ULT:
4012 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4013 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4014 break; // (X != 13 & X u< 15) -> no change
4015 case ICmpInst::ICMP_SLT:
4016 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4017 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4018 break; // (X != 13 & X s< 15) -> no change
4019 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4020 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4021 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4022 return ReplaceInstUsesWith(I, RHS);
4023 case ICmpInst::ICMP_NE:
4024 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4025 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004026 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027 LHSVal->getName()+".off");
4028 InsertNewInstBefore(Add, I);
4029 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4030 ConstantInt::get(Add->getType(), 1));
4031 }
4032 break; // (X != 13 & X != 15) -> no change
4033 }
4034 break;
4035 case ICmpInst::ICMP_ULT:
4036 switch (RHSCC) {
4037 default: assert(0 && "Unknown integer condition code!");
4038 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4039 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4040 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4041 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4042 break;
4043 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4044 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4045 return ReplaceInstUsesWith(I, LHS);
4046 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4047 break;
4048 }
4049 break;
4050 case ICmpInst::ICMP_SLT:
4051 switch (RHSCC) {
4052 default: assert(0 && "Unknown integer condition code!");
4053 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4054 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4057 break;
4058 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4059 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4060 return ReplaceInstUsesWith(I, LHS);
4061 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4062 break;
4063 }
4064 break;
4065 case ICmpInst::ICMP_UGT:
4066 switch (RHSCC) {
4067 default: assert(0 && "Unknown integer condition code!");
4068 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4069 return ReplaceInstUsesWith(I, LHS);
4070 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4071 return ReplaceInstUsesWith(I, RHS);
4072 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4073 break;
4074 case ICmpInst::ICMP_NE:
4075 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4076 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4077 break; // (X u> 13 & X != 15) -> no change
4078 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4079 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4080 true, I);
4081 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4082 break;
4083 }
4084 break;
4085 case ICmpInst::ICMP_SGT:
4086 switch (RHSCC) {
4087 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004088 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4090 return ReplaceInstUsesWith(I, RHS);
4091 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4092 break;
4093 case ICmpInst::ICMP_NE:
4094 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4095 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4096 break; // (X s> 13 & X != 15) -> no change
4097 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4098 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4099 true, I);
4100 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4101 break;
4102 }
4103 break;
4104 }
4105 }
4106 }
4107
4108 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4109 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4110 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4111 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4112 const Type *SrcTy = Op0C->getOperand(0)->getType();
4113 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4114 // Only do this if the casts both really cause code to be generated.
4115 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4116 I.getType(), TD) &&
4117 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4118 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004119 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004120 Op1C->getOperand(0),
4121 I.getName());
4122 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004123 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004124 }
4125 }
4126
4127 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4128 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4129 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4130 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4131 SI0->getOperand(1) == SI1->getOperand(1) &&
4132 (SI0->hasOneUse() || SI1->hasOneUse())) {
4133 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004134 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 SI1->getOperand(0),
4136 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004137 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004138 SI1->getOperand(1));
4139 }
4140 }
4141
Chris Lattner91882432007-10-24 05:38:08 +00004142 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4143 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4144 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4145 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4146 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4147 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4148 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4149 // If either of the constants are nans, then the whole thing returns
4150 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004151 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004152 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4153 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4154 RHS->getOperand(0));
4155 }
4156 }
4157 }
4158
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159 return Changed ? &I : 0;
4160}
4161
4162/// CollectBSwapParts - Look to see if the specified value defines a single byte
4163/// in the result. If it does, and if the specified byte hasn't been filled in
4164/// yet, fill it in and return false.
4165static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4166 Instruction *I = dyn_cast<Instruction>(V);
4167 if (I == 0) return true;
4168
4169 // If this is an or instruction, it is an inner node of the bswap.
4170 if (I->getOpcode() == Instruction::Or)
4171 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4172 CollectBSwapParts(I->getOperand(1), ByteValues);
4173
4174 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4175 // If this is a shift by a constant int, and it is "24", then its operand
4176 // defines a byte. We only handle unsigned types here.
4177 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4178 // Not shifting the entire input by N-1 bytes?
4179 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4180 8*(ByteValues.size()-1))
4181 return true;
4182
4183 unsigned DestNo;
4184 if (I->getOpcode() == Instruction::Shl) {
4185 // X << 24 defines the top byte with the lowest of the input bytes.
4186 DestNo = ByteValues.size()-1;
4187 } else {
4188 // X >>u 24 defines the low byte with the highest of the input bytes.
4189 DestNo = 0;
4190 }
4191
4192 // If the destination byte value is already defined, the values are or'd
4193 // together, which isn't a bswap (unless it's an or of the same bits).
4194 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4195 return true;
4196 ByteValues[DestNo] = I->getOperand(0);
4197 return false;
4198 }
4199
4200 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4201 // don't have this.
4202 Value *Shift = 0, *ShiftLHS = 0;
4203 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4204 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4205 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4206 return true;
4207 Instruction *SI = cast<Instruction>(Shift);
4208
4209 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4210 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4211 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4212 return true;
4213
4214 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4215 unsigned DestByte;
4216 if (AndAmt->getValue().getActiveBits() > 64)
4217 return true;
4218 uint64_t AndAmtVal = AndAmt->getZExtValue();
4219 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4220 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4221 break;
4222 // Unknown mask for bswap.
4223 if (DestByte == ByteValues.size()) return true;
4224
4225 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4226 unsigned SrcByte;
4227 if (SI->getOpcode() == Instruction::Shl)
4228 SrcByte = DestByte - ShiftBytes;
4229 else
4230 SrcByte = DestByte + ShiftBytes;
4231
4232 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4233 if (SrcByte != ByteValues.size()-DestByte-1)
4234 return true;
4235
4236 // If the destination byte value is already defined, the values are or'd
4237 // together, which isn't a bswap (unless it's an or of the same bits).
4238 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4239 return true;
4240 ByteValues[DestByte] = SI->getOperand(0);
4241 return false;
4242}
4243
4244/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4245/// If so, insert the new bswap intrinsic and return it.
4246Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4247 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4248 if (!ITy || ITy->getBitWidth() % 16)
4249 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4250
4251 /// ByteValues - For each byte of the result, we keep track of which value
4252 /// defines each byte.
4253 SmallVector<Value*, 8> ByteValues;
4254 ByteValues.resize(ITy->getBitWidth()/8);
4255
4256 // Try to find all the pieces corresponding to the bswap.
4257 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4258 CollectBSwapParts(I.getOperand(1), ByteValues))
4259 return 0;
4260
4261 // Check to see if all of the bytes come from the same value.
4262 Value *V = ByteValues[0];
4263 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4264
4265 // Check to make sure that all of the bytes come from the same value.
4266 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4267 if (ByteValues[i] != V)
4268 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004269 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004270 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004271 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004272 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273}
4274
4275
4276Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4277 bool Changed = SimplifyCommutative(I);
4278 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4279
4280 if (isa<UndefValue>(Op1)) // X | undef -> -1
4281 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4282
4283 // or X, X = X
4284 if (Op0 == Op1)
4285 return ReplaceInstUsesWith(I, Op0);
4286
4287 // See if we can simplify any instructions used by the instruction whose sole
4288 // purpose is to compute bits we don't care about.
4289 if (!isa<VectorType>(I.getType())) {
4290 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4291 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4292 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4293 KnownZero, KnownOne))
4294 return &I;
4295 } else if (isa<ConstantAggregateZero>(Op1)) {
4296 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4297 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4298 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4299 return ReplaceInstUsesWith(I, I.getOperand(1));
4300 }
4301
4302
4303
4304 // or X, -1 == -1
4305 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4306 ConstantInt *C1 = 0; Value *X = 0;
4307 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4308 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004309 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 InsertNewInstBefore(Or, I);
4311 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004312 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 ConstantInt::get(RHS->getValue() | C1->getValue()));
4314 }
4315
4316 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4317 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004318 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004319 InsertNewInstBefore(Or, I);
4320 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004321 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4323 }
4324
4325 // Try to fold constant and into select arguments.
4326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4327 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4328 return R;
4329 if (isa<PHINode>(Op0))
4330 if (Instruction *NV = FoldOpIntoPhi(I))
4331 return NV;
4332 }
4333
4334 Value *A = 0, *B = 0;
4335 ConstantInt *C1 = 0, *C2 = 0;
4336
4337 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4338 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4339 return ReplaceInstUsesWith(I, Op1);
4340 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4341 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4342 return ReplaceInstUsesWith(I, Op0);
4343
4344 // (A | B) | C and A | (B | C) -> bswap if possible.
4345 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4346 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4347 match(Op1, m_Or(m_Value(), m_Value())) ||
4348 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4349 match(Op1, m_Shift(m_Value(), m_Value())))) {
4350 if (Instruction *BSwap = MatchBSwap(I))
4351 return BSwap;
4352 }
4353
4354 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4355 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4356 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004357 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358 InsertNewInstBefore(NOr, I);
4359 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004360 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004361 }
4362
4363 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4364 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4365 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004366 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004367 InsertNewInstBefore(NOr, I);
4368 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004369 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004370 }
4371
4372 // (A & C)|(B & D)
4373 Value *C = 0, *D = 0;
4374 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4375 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4376 Value *V1 = 0, *V2 = 0, *V3 = 0;
4377 C1 = dyn_cast<ConstantInt>(C);
4378 C2 = dyn_cast<ConstantInt>(D);
4379 if (C1 && C2) { // (A & C1)|(B & C2)
4380 // If we have: ((V + N) & C1) | (V & C2)
4381 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4382 // replace with V+N.
4383 if (C1->getValue() == ~C2->getValue()) {
4384 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4385 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4386 // Add commutes, try both ways.
4387 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4388 return ReplaceInstUsesWith(I, A);
4389 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4390 return ReplaceInstUsesWith(I, A);
4391 }
4392 // Or commutes, try both ways.
4393 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4394 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4395 // Add commutes, try both ways.
4396 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4397 return ReplaceInstUsesWith(I, B);
4398 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4399 return ReplaceInstUsesWith(I, B);
4400 }
4401 }
4402 V1 = 0; V2 = 0; V3 = 0;
4403 }
4404
4405 // Check to see if we have any common things being and'ed. If so, find the
4406 // terms for V1 & (V2|V3).
4407 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4408 if (A == B) // (A & C)|(A & D) == A & (C|D)
4409 V1 = A, V2 = C, V3 = D;
4410 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4411 V1 = A, V2 = B, V3 = C;
4412 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4413 V1 = C, V2 = A, V3 = D;
4414 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4415 V1 = C, V2 = A, V3 = B;
4416
4417 if (V1) {
4418 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004419 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4420 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 }
4423 }
4424
4425 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4426 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4427 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4428 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4429 SI0->getOperand(1) == SI1->getOperand(1) &&
4430 (SI0->hasOneUse() || SI1->hasOneUse())) {
4431 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004432 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433 SI1->getOperand(0),
4434 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004435 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 SI1->getOperand(1));
4437 }
4438 }
4439
4440 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4441 if (A == Op1) // ~A | A == -1
4442 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4443 } else {
4444 A = 0;
4445 }
4446 // Note, A is still live here!
4447 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4448 if (Op0 == B)
4449 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4450
4451 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4452 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004453 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004455 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004456 }
4457 }
4458
4459 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4460 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4461 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4462 return R;
4463
4464 Value *LHSVal, *RHSVal;
4465 ConstantInt *LHSCst, *RHSCst;
4466 ICmpInst::Predicate LHSCC, RHSCC;
4467 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4468 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4469 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4470 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4471 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4472 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4473 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4474 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4475 // We can't fold (ugt x, C) | (sgt x, C2).
4476 PredicatesFoldable(LHSCC, RHSCC)) {
4477 // Ensure that the larger constant is on the RHS.
4478 ICmpInst *LHS = cast<ICmpInst>(Op0);
4479 bool NeedsSwap;
4480 if (ICmpInst::isSignedPredicate(LHSCC))
4481 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4482 else
4483 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4484
4485 if (NeedsSwap) {
4486 std::swap(LHS, RHS);
4487 std::swap(LHSCst, RHSCst);
4488 std::swap(LHSCC, RHSCC);
4489 }
4490
4491 // At this point, we know we have have two icmp instructions
4492 // comparing a value against two constants and or'ing the result
4493 // together. Because of the above check, we know that we only have
4494 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4495 // FoldICmpLogical check above), that the two constants are not
4496 // equal.
4497 assert(LHSCst != RHSCst && "Compares not folded above?");
4498
4499 switch (LHSCC) {
4500 default: assert(0 && "Unknown integer condition code!");
4501 case ICmpInst::ICMP_EQ:
4502 switch (RHSCC) {
4503 default: assert(0 && "Unknown integer condition code!");
4504 case ICmpInst::ICMP_EQ:
4505 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4506 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004507 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004508 LHSVal->getName()+".off");
4509 InsertNewInstBefore(Add, I);
4510 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4511 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4512 }
4513 break; // (X == 13 | X == 15) -> no change
4514 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4515 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4516 break;
4517 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4518 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4519 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4520 return ReplaceInstUsesWith(I, RHS);
4521 }
4522 break;
4523 case ICmpInst::ICMP_NE:
4524 switch (RHSCC) {
4525 default: assert(0 && "Unknown integer condition code!");
4526 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4527 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4528 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4529 return ReplaceInstUsesWith(I, LHS);
4530 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4531 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4532 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4534 }
4535 break;
4536 case ICmpInst::ICMP_ULT:
4537 switch (RHSCC) {
4538 default: assert(0 && "Unknown integer condition code!");
4539 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4540 break;
4541 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004542 // If RHSCst is [us]MAXINT, it is always false. Not handling
4543 // this can cause overflow.
4544 if (RHSCst->isMaxValue(false))
4545 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004546 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4547 false, I);
4548 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4549 break;
4550 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4551 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4552 return ReplaceInstUsesWith(I, RHS);
4553 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4554 break;
4555 }
4556 break;
4557 case ICmpInst::ICMP_SLT:
4558 switch (RHSCC) {
4559 default: assert(0 && "Unknown integer condition code!");
4560 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004563 // If RHSCst is [us]MAXINT, it is always false. Not handling
4564 // this can cause overflow.
4565 if (RHSCst->isMaxValue(true))
4566 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004567 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4568 false, I);
4569 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4570 break;
4571 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4572 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4573 return ReplaceInstUsesWith(I, RHS);
4574 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4575 break;
4576 }
4577 break;
4578 case ICmpInst::ICMP_UGT:
4579 switch (RHSCC) {
4580 default: assert(0 && "Unknown integer condition code!");
4581 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4582 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4583 return ReplaceInstUsesWith(I, LHS);
4584 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4585 break;
4586 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4587 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4588 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4589 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4590 break;
4591 }
4592 break;
4593 case ICmpInst::ICMP_SGT:
4594 switch (RHSCC) {
4595 default: assert(0 && "Unknown integer condition code!");
4596 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4597 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4598 return ReplaceInstUsesWith(I, LHS);
4599 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4602 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4603 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4604 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4605 break;
4606 }
4607 break;
4608 }
4609 }
4610 }
4611
4612 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004613 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4615 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004616 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4617 !isa<ICmpInst>(Op1C->getOperand(0))) {
4618 const Type *SrcTy = Op0C->getOperand(0)->getType();
4619 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4620 // Only do this if the casts both really cause code to be
4621 // generated.
4622 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4623 I.getType(), TD) &&
4624 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4625 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004626 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004627 Op1C->getOperand(0),
4628 I.getName());
4629 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004630 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004632 }
4633 }
Chris Lattner91882432007-10-24 05:38:08 +00004634 }
4635
4636
4637 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4638 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4639 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4640 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004641 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4642 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004643 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4644 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4645 // If either of the constants are nans, then the whole thing returns
4646 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004647 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4649
4650 // Otherwise, no need to compare the two constants, compare the
4651 // rest.
4652 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4653 RHS->getOperand(0));
4654 }
4655 }
4656 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004657
4658 return Changed ? &I : 0;
4659}
4660
Dan Gohman089efff2008-05-13 00:00:25 +00004661namespace {
4662
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004663// XorSelf - Implements: X ^ X --> 0
4664struct XorSelf {
4665 Value *RHS;
4666 XorSelf(Value *rhs) : RHS(rhs) {}
4667 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4668 Instruction *apply(BinaryOperator &Xor) const {
4669 return &Xor;
4670 }
4671};
4672
Dan Gohman089efff2008-05-13 00:00:25 +00004673}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004674
4675Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4676 bool Changed = SimplifyCommutative(I);
4677 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4678
Evan Chenge5cd8032008-03-25 20:07:13 +00004679 if (isa<UndefValue>(Op1)) {
4680 if (isa<UndefValue>(Op0))
4681 // Handle undef ^ undef -> 0 special case. This is a common
4682 // idiom (misuse).
4683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004684 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004685 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004686
4687 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4688 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004689 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4691 }
4692
4693 // See if we can simplify any instructions used by the instruction whose sole
4694 // purpose is to compute bits we don't care about.
4695 if (!isa<VectorType>(I.getType())) {
4696 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4697 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4698 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4699 KnownZero, KnownOne))
4700 return &I;
4701 } else if (isa<ConstantAggregateZero>(Op1)) {
4702 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4703 }
4704
4705 // Is this a ~ operation?
4706 if (Value *NotOp = dyn_castNotVal(&I)) {
4707 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4708 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4709 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4710 if (Op0I->getOpcode() == Instruction::And ||
4711 Op0I->getOpcode() == Instruction::Or) {
4712 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4713 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4714 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004715 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004716 Op0I->getOperand(1)->getName()+".not");
4717 InsertNewInstBefore(NotY, I);
4718 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004720 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004721 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004722 }
4723 }
4724 }
4725 }
4726
4727
4728 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004729 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4730 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004732 return new ICmpInst(ICI->getInversePredicate(),
4733 ICI->getOperand(0), ICI->getOperand(1));
4734
Nick Lewycky1405e922007-08-06 20:04:16 +00004735 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4736 return new FCmpInst(FCI->getInversePredicate(),
4737 FCI->getOperand(0), FCI->getOperand(1));
4738 }
4739
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004740 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4741 // ~(c-X) == X-c-1 == X+(-c-1)
4742 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4743 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4744 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4745 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4746 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004748 }
4749
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004750 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 if (Op0I->getOpcode() == Instruction::Add) {
4752 // ~(X-c) --> (-c-1)-X
4753 if (RHS->isAllOnesValue()) {
4754 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004756 ConstantExpr::getSub(NegOp0CI,
4757 ConstantInt::get(I.getType(), 1)),
4758 Op0I->getOperand(0));
4759 } else if (RHS->getValue().isSignBit()) {
4760 // (X + C) ^ signbit -> (X + C + signbit)
4761 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004762 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004763
4764 }
4765 } else if (Op0I->getOpcode() == Instruction::Or) {
4766 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4767 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4768 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4769 // Anything in both C1 and C2 is known to be zero, remove it from
4770 // NewRHS.
4771 Constant *CommonBits = And(Op0CI, RHS);
4772 NewRHS = ConstantExpr::getAnd(NewRHS,
4773 ConstantExpr::getNot(CommonBits));
4774 AddToWorkList(Op0I);
4775 I.setOperand(0, Op0I->getOperand(0));
4776 I.setOperand(1, NewRHS);
4777 return &I;
4778 }
4779 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 }
4782
4783 // Try to fold constant and into select arguments.
4784 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4785 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4786 return R;
4787 if (isa<PHINode>(Op0))
4788 if (Instruction *NV = FoldOpIntoPhi(I))
4789 return NV;
4790 }
4791
4792 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4793 if (X == Op1)
4794 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4795
4796 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4797 if (X == Op0)
4798 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4799
4800
4801 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4802 if (Op1I) {
4803 Value *A, *B;
4804 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4805 if (A == Op0) { // B^(B|A) == (A|B)^B
4806 Op1I->swapOperands();
4807 I.swapOperands();
4808 std::swap(Op0, Op1);
4809 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4810 I.swapOperands(); // Simplified below.
4811 std::swap(Op0, Op1);
4812 }
4813 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4814 if (Op0 == A) // A^(A^B) == B
4815 return ReplaceInstUsesWith(I, B);
4816 else if (Op0 == B) // A^(B^A) == B
4817 return ReplaceInstUsesWith(I, A);
4818 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4819 if (A == Op0) { // A^(A&B) -> A^(B&A)
4820 Op1I->swapOperands();
4821 std::swap(A, B);
4822 }
4823 if (B == Op0) { // A^(B&A) -> (B&A)^A
4824 I.swapOperands(); // Simplified below.
4825 std::swap(Op0, Op1);
4826 }
4827 }
4828 }
4829
4830 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4831 if (Op0I) {
4832 Value *A, *B;
4833 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4834 if (A == Op1) // (B|A)^B == (A|B)^B
4835 std::swap(A, B);
4836 if (B == Op1) { // (A|B)^B == A & ~B
4837 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004838 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4839 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004840 }
4841 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4842 if (Op1 == A) // (A^B)^A == B
4843 return ReplaceInstUsesWith(I, B);
4844 else if (Op1 == B) // (B^A)^A == B
4845 return ReplaceInstUsesWith(I, A);
4846 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4847 if (A == Op1) // (A&B)^A -> (B&A)^A
4848 std::swap(A, B);
4849 if (B == Op1 && // (B&A)^A == ~B & A
4850 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4851 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004852 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4853 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004854 }
4855 }
4856 }
4857
4858 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4859 if (Op0I && Op1I && Op0I->isShift() &&
4860 Op0I->getOpcode() == Op1I->getOpcode() &&
4861 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4862 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4863 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004864 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004865 Op1I->getOperand(0),
4866 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004867 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004868 Op1I->getOperand(1));
4869 }
4870
4871 if (Op0I && Op1I) {
4872 Value *A, *B, *C, *D;
4873 // (A & B)^(A | B) -> A ^ B
4874 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4875 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4876 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004877 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004878 }
4879 // (A | B)^(A & B) -> A ^ B
4880 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4881 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4882 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004883 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004884 }
4885
4886 // (A & B)^(C & D)
4887 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4888 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4889 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4890 // (X & Y)^(X & Y) -> (Y^Z) & X
4891 Value *X = 0, *Y = 0, *Z = 0;
4892 if (A == C)
4893 X = A, Y = B, Z = D;
4894 else if (A == D)
4895 X = A, Y = B, Z = C;
4896 else if (B == C)
4897 X = B, Y = A, Z = D;
4898 else if (B == D)
4899 X = B, Y = A, Z = C;
4900
4901 if (X) {
4902 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004903 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4904 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004905 }
4906 }
4907 }
4908
4909 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4910 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4911 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4912 return R;
4913
4914 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004915 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004916 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4917 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4918 const Type *SrcTy = Op0C->getOperand(0)->getType();
4919 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4920 // Only do this if the casts both really cause code to be generated.
4921 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4922 I.getType(), TD) &&
4923 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4924 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004925 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926 Op1C->getOperand(0),
4927 I.getName());
4928 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004930 }
4931 }
Chris Lattner91882432007-10-24 05:38:08 +00004932 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004933 return Changed ? &I : 0;
4934}
4935
4936/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4937/// overflowed for this type.
4938static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4939 ConstantInt *In2, bool IsSigned = false) {
4940 Result = cast<ConstantInt>(Add(In1, In2));
4941
4942 if (IsSigned)
4943 if (In2->getValue().isNegative())
4944 return Result->getValue().sgt(In1->getValue());
4945 else
4946 return Result->getValue().slt(In1->getValue());
4947 else
4948 return Result->getValue().ult(In1->getValue());
4949}
4950
4951/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4952/// code necessary to compute the offset from the base pointer (without adding
4953/// in the base pointer). Return the result as a signed integer of intptr size.
4954static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4955 TargetData &TD = IC.getTargetData();
4956 gep_type_iterator GTI = gep_type_begin(GEP);
4957 const Type *IntPtrTy = TD.getIntPtrType();
4958 Value *Result = Constant::getNullValue(IntPtrTy);
4959
4960 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004961 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4963
4964 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4965 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004966 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4968 if (OpC->isZero()) continue;
4969
4970 // Handle a struct index, which adds its field offset to the pointer.
4971 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4972 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4973
4974 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4975 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4976 else
4977 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004978 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004979 ConstantInt::get(IntPtrTy, Size),
4980 GEP->getName()+".offs"), I);
4981 continue;
4982 }
4983
4984 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4985 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4986 Scale = ConstantExpr::getMul(OC, Scale);
4987 if (Constant *RC = dyn_cast<Constant>(Result))
4988 Result = ConstantExpr::getAdd(RC, Scale);
4989 else {
4990 // Emit an add instruction.
4991 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004992 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004993 GEP->getName()+".offs"), I);
4994 }
4995 continue;
4996 }
4997 // Convert to correct type.
4998 if (Op->getType() != IntPtrTy) {
4999 if (Constant *OpC = dyn_cast<Constant>(Op))
5000 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5001 else
5002 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5003 Op->getName()+".c"), I);
5004 }
5005 if (Size != 1) {
5006 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5007 if (Constant *OpC = dyn_cast<Constant>(Op))
5008 Op = ConstantExpr::getMul(OpC, Scale);
5009 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005010 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005011 GEP->getName()+".idx"), I);
5012 }
5013
5014 // Emit an add instruction.
5015 if (isa<Constant>(Op) && isa<Constant>(Result))
5016 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5017 cast<Constant>(Result));
5018 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005019 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005020 GEP->getName()+".offs"), I);
5021 }
5022 return Result;
5023}
5024
Chris Lattnereba75862008-04-22 02:53:33 +00005025
5026/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5027/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5028/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5029/// complex, and scales are involved. The above expression would also be legal
5030/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5031/// later form is less amenable to optimization though, and we are allowed to
5032/// generate the first by knowing that pointer arithmetic doesn't overflow.
5033///
5034/// If we can't emit an optimized form for this expression, this returns null.
5035///
5036static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5037 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005038 TargetData &TD = IC.getTargetData();
5039 gep_type_iterator GTI = gep_type_begin(GEP);
5040
5041 // Check to see if this gep only has a single variable index. If so, and if
5042 // any constant indices are a multiple of its scale, then we can compute this
5043 // in terms of the scale of the variable index. For example, if the GEP
5044 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5045 // because the expression will cross zero at the same point.
5046 unsigned i, e = GEP->getNumOperands();
5047 int64_t Offset = 0;
5048 for (i = 1; i != e; ++i, ++GTI) {
5049 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5050 // Compute the aggregate offset of constant indices.
5051 if (CI->isZero()) continue;
5052
5053 // Handle a struct index, which adds its field offset to the pointer.
5054 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5055 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5056 } else {
5057 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5058 Offset += Size*CI->getSExtValue();
5059 }
5060 } else {
5061 // Found our variable index.
5062 break;
5063 }
5064 }
5065
5066 // If there are no variable indices, we must have a constant offset, just
5067 // evaluate it the general way.
5068 if (i == e) return 0;
5069
5070 Value *VariableIdx = GEP->getOperand(i);
5071 // Determine the scale factor of the variable element. For example, this is
5072 // 4 if the variable index is into an array of i32.
5073 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5074
5075 // Verify that there are no other variable indices. If so, emit the hard way.
5076 for (++i, ++GTI; i != e; ++i, ++GTI) {
5077 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5078 if (!CI) return 0;
5079
5080 // Compute the aggregate offset of constant indices.
5081 if (CI->isZero()) continue;
5082
5083 // Handle a struct index, which adds its field offset to the pointer.
5084 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5085 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5086 } else {
5087 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5088 Offset += Size*CI->getSExtValue();
5089 }
5090 }
5091
5092 // Okay, we know we have a single variable index, which must be a
5093 // pointer/array/vector index. If there is no offset, life is simple, return
5094 // the index.
5095 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5096 if (Offset == 0) {
5097 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5098 // we don't need to bother extending: the extension won't affect where the
5099 // computation crosses zero.
5100 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5101 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5102 VariableIdx->getNameStart(), &I);
5103 return VariableIdx;
5104 }
5105
5106 // Otherwise, there is an index. The computation we will do will be modulo
5107 // the pointer size, so get it.
5108 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5109
5110 Offset &= PtrSizeMask;
5111 VariableScale &= PtrSizeMask;
5112
5113 // To do this transformation, any constant index must be a multiple of the
5114 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5115 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5116 // multiple of the variable scale.
5117 int64_t NewOffs = Offset / (int64_t)VariableScale;
5118 if (Offset != NewOffs*(int64_t)VariableScale)
5119 return 0;
5120
5121 // Okay, we can do this evaluation. Start by converting the index to intptr.
5122 const Type *IntPtrTy = TD.getIntPtrType();
5123 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005124 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005125 true /*SExt*/,
5126 VariableIdx->getNameStart(), &I);
5127 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005129}
5130
5131
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005132/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5133/// else. At this point we know that the GEP is on the LHS of the comparison.
5134Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5135 ICmpInst::Predicate Cond,
5136 Instruction &I) {
5137 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5138
Chris Lattnereba75862008-04-22 02:53:33 +00005139 // Look through bitcasts.
5140 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5141 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005142
5143 Value *PtrBase = GEPLHS->getOperand(0);
5144 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005145 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005146 // This transformation (ignoring the base and scales) is valid because we
5147 // know pointers can't overflow. See if we can output an optimized form.
5148 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5149
5150 // If not, synthesize the offset the hard way.
5151 if (Offset == 0)
5152 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005153 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5154 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005155 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5156 // If the base pointers are different, but the indices are the same, just
5157 // compare the base pointer.
5158 if (PtrBase != GEPRHS->getOperand(0)) {
5159 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5160 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5161 GEPRHS->getOperand(0)->getType();
5162 if (IndicesTheSame)
5163 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5164 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5165 IndicesTheSame = false;
5166 break;
5167 }
5168
5169 // If all indices are the same, just compare the base pointers.
5170 if (IndicesTheSame)
5171 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5172 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5173
5174 // Otherwise, the base pointers are different and the indices are
5175 // different, bail out.
5176 return 0;
5177 }
5178
5179 // If one of the GEPs has all zero indices, recurse.
5180 bool AllZeros = true;
5181 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5182 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5183 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5184 AllZeros = false;
5185 break;
5186 }
5187 if (AllZeros)
5188 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5189 ICmpInst::getSwappedPredicate(Cond), I);
5190
5191 // If the other GEP has all zero indices, recurse.
5192 AllZeros = true;
5193 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5194 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5195 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5196 AllZeros = false;
5197 break;
5198 }
5199 if (AllZeros)
5200 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5201
5202 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5203 // If the GEPs only differ by one index, compare it.
5204 unsigned NumDifferences = 0; // Keep track of # differences.
5205 unsigned DiffOperand = 0; // The operand that differs.
5206 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5207 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5208 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5209 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5210 // Irreconcilable differences.
5211 NumDifferences = 2;
5212 break;
5213 } else {
5214 if (NumDifferences++) break;
5215 DiffOperand = i;
5216 }
5217 }
5218
5219 if (NumDifferences == 0) // SAME GEP?
5220 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005221 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005222 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005223
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005224 else if (NumDifferences == 1) {
5225 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5226 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5227 // Make sure we do a signed comparison here.
5228 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5229 }
5230 }
5231
5232 // Only lower this if the icmp is the only user of the GEP or if we expect
5233 // the result to fold to a constant!
5234 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5235 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5236 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5237 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5238 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5239 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5240 }
5241 }
5242 return 0;
5243}
5244
Chris Lattnere6b62d92008-05-19 20:18:56 +00005245/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5246///
5247Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5248 Instruction *LHSI,
5249 Constant *RHSC) {
5250 if (!isa<ConstantFP>(RHSC)) return 0;
5251 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5252
5253 // Get the width of the mantissa. We don't want to hack on conversions that
5254 // might lose information from the integer, e.g. "i64 -> float"
5255 int MantissaWidth = GetFPMantissaWidth(LHSI->getType());
5256 if (MantissaWidth == -1) return 0; // Unknown.
5257
5258 // Check to see that the input is converted from an integer type that is small
5259 // enough that preserves all bits. TODO: check here for "known" sign bits.
5260 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5261 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5262
5263 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5264 if (isa<UIToFPInst>(LHSI))
5265 ++InputSize;
5266
5267 // If the conversion would lose info, don't hack on this.
5268 if ((int)InputSize > MantissaWidth)
5269 return 0;
5270
5271 // Otherwise, we can potentially simplify the comparison. We know that it
5272 // will always come through as an integer value and we know the constant is
5273 // not a NAN (it would have been previously simplified).
5274 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5275
5276 ICmpInst::Predicate Pred;
5277 switch (I.getPredicate()) {
5278 default: assert(0 && "Unexpected predicate!");
5279 case FCmpInst::FCMP_UEQ:
5280 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5281 case FCmpInst::FCMP_UGT:
5282 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5283 case FCmpInst::FCMP_UGE:
5284 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5285 case FCmpInst::FCMP_ULT:
5286 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5287 case FCmpInst::FCMP_ULE:
5288 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5289 case FCmpInst::FCMP_UNE:
5290 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5291 case FCmpInst::FCMP_ORD:
5292 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5293 case FCmpInst::FCMP_UNO:
5294 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5295 }
5296
5297 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5298
5299 // Now we know that the APFloat is a normal number, zero or inf.
5300
5301 // See if the FP constant is top large for the integer. For example,
5302 // comparing an i8 to 300.0.
5303 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5304
5305 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5306 // and large values.
5307 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5308 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5309 APFloat::rmNearestTiesToEven);
5310 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5311 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5312 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5313 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5314 }
5315
5316 // See if the RHS value is < SignedMin.
5317 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5318 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5319 APFloat::rmNearestTiesToEven);
5320 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5321 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5322 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5323 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5324 }
5325
5326 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5327 // it may still be fractional. See if it is fractional by casting the FP
5328 // value to the integer value and back, checking for equality. Don't do this
5329 // for zero, because -0.0 is not fractional.
5330 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5331 if (!RHS.isZero() &&
5332 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5333 // If we had a comparison against a fractional value, we have to adjust
5334 // the compare predicate and sometimes the value. RHSC is rounded towards
5335 // zero at this point.
5336 switch (Pred) {
5337 default: assert(0 && "Unexpected integer comparison!");
5338 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5339 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5340 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5341 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5342 case ICmpInst::ICMP_SLE:
5343 // (float)int <= 4.4 --> int <= 4
5344 // (float)int <= -4.4 --> int < -4
5345 if (RHS.isNegative())
5346 Pred = ICmpInst::ICMP_SLT;
5347 break;
5348 case ICmpInst::ICMP_SLT:
5349 // (float)int < -4.4 --> int < -4
5350 // (float)int < 4.4 --> int <= 4
5351 if (!RHS.isNegative())
5352 Pred = ICmpInst::ICMP_SLE;
5353 break;
5354 case ICmpInst::ICMP_SGT:
5355 // (float)int > 4.4 --> int > 4
5356 // (float)int > -4.4 --> int >= -4
5357 if (RHS.isNegative())
5358 Pred = ICmpInst::ICMP_SGE;
5359 break;
5360 case ICmpInst::ICMP_SGE:
5361 // (float)int >= -4.4 --> int >= -4
5362 // (float)int >= 4.4 --> int > 4
5363 if (!RHS.isNegative())
5364 Pred = ICmpInst::ICMP_SGT;
5365 break;
5366 }
5367 }
5368
5369 // Lower this FP comparison into an appropriate integer version of the
5370 // comparison.
5371 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5372}
5373
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005374Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5375 bool Changed = SimplifyCompare(I);
5376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5377
5378 // Fold trivial predicates.
5379 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5380 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5381 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5382 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5383
5384 // Simplify 'fcmp pred X, X'
5385 if (Op0 == Op1) {
5386 switch (I.getPredicate()) {
5387 default: assert(0 && "Unknown predicate!");
5388 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5389 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5390 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5391 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5392 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5393 case FCmpInst::FCMP_OLT: // True if ordered and less than
5394 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5395 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5396
5397 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5398 case FCmpInst::FCMP_ULT: // True if unordered or less than
5399 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5400 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5401 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5402 I.setPredicate(FCmpInst::FCMP_UNO);
5403 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5404 return &I;
5405
5406 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5407 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5408 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5409 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5410 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5411 I.setPredicate(FCmpInst::FCMP_ORD);
5412 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5413 return &I;
5414 }
5415 }
5416
5417 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5418 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5419
5420 // Handle fcmp with constant RHS
5421 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005422 // If the constant is a nan, see if we can fold the comparison based on it.
5423 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5424 if (CFP->getValueAPF().isNaN()) {
5425 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5426 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5427 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5428 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5429 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5430 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5431 }
5432 }
5433
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005434 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5435 switch (LHSI->getOpcode()) {
5436 case Instruction::PHI:
5437 if (Instruction *NV = FoldOpIntoPhi(I))
5438 return NV;
5439 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005440 case Instruction::SIToFP:
5441 case Instruction::UIToFP:
5442 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5443 return NV;
5444 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005445 case Instruction::Select:
5446 // If either operand of the select is a constant, we can fold the
5447 // comparison into the select arms, which will cause one to be
5448 // constant folded and the select turned into a bitwise or.
5449 Value *Op1 = 0, *Op2 = 0;
5450 if (LHSI->hasOneUse()) {
5451 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5452 // Fold the known value into the constant operand.
5453 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5454 // Insert a new FCmp of the other select operand.
5455 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5456 LHSI->getOperand(2), RHSC,
5457 I.getName()), I);
5458 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5459 // Fold the known value into the constant operand.
5460 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5461 // Insert a new FCmp of the other select operand.
5462 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5463 LHSI->getOperand(1), RHSC,
5464 I.getName()), I);
5465 }
5466 }
5467
5468 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005469 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005470 break;
5471 }
5472 }
5473
5474 return Changed ? &I : 0;
5475}
5476
5477Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5478 bool Changed = SimplifyCompare(I);
5479 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5480 const Type *Ty = Op0->getType();
5481
5482 // icmp X, X
5483 if (Op0 == Op1)
5484 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005485 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005486
5487 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5488 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005489
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005490 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5491 // addresses never equal each other! We already know that Op0 != Op1.
5492 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5493 isa<ConstantPointerNull>(Op0)) &&
5494 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5495 isa<ConstantPointerNull>(Op1)))
5496 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005497 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005498
5499 // icmp's with boolean values can always be turned into bitwise operations
5500 if (Ty == Type::Int1Ty) {
5501 switch (I.getPredicate()) {
5502 default: assert(0 && "Invalid icmp instruction!");
5503 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005504 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005505 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005506 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005507 }
5508 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005509 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005510
5511 case ICmpInst::ICMP_UGT:
5512 case ICmpInst::ICMP_SGT:
5513 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5514 // FALL THROUGH
5515 case ICmpInst::ICMP_ULT:
5516 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005517 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005518 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005519 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005520 }
5521 case ICmpInst::ICMP_UGE:
5522 case ICmpInst::ICMP_SGE:
5523 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5524 // FALL THROUGH
5525 case ICmpInst::ICMP_ULE:
5526 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005527 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005528 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005529 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005530 }
5531 }
5532 }
5533
5534 // See if we are doing a comparison between a constant and an instruction that
5535 // can be folded into the comparison.
5536 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005537 Value *A, *B;
5538
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005539 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5540 if (I.isEquality() && CI->isNullValue() &&
5541 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5542 // (icmp cond A B) if cond is equality
5543 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005544 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005545
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005546 switch (I.getPredicate()) {
5547 default: break;
5548 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5549 if (CI->isMinValue(false))
5550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5552 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5553 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5554 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5555 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5556 if (CI->isMinValue(true))
5557 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5558 ConstantInt::getAllOnesValue(Op0->getType()));
5559
5560 break;
5561
5562 case ICmpInst::ICMP_SLT:
5563 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5564 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5565 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5566 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5567 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5568 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5569 break;
5570
5571 case ICmpInst::ICMP_UGT:
5572 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5573 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5574 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5575 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5576 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5577 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5578
5579 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5580 if (CI->isMaxValue(true))
5581 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5582 ConstantInt::getNullValue(Op0->getType()));
5583 break;
5584
5585 case ICmpInst::ICMP_SGT:
5586 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5587 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5588 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5589 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5590 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5591 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5592 break;
5593
5594 case ICmpInst::ICMP_ULE:
5595 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5597 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5598 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5599 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5600 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5601 break;
5602
5603 case ICmpInst::ICMP_SLE:
5604 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5605 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5606 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5607 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5608 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5609 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5610 break;
5611
5612 case ICmpInst::ICMP_UGE:
5613 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5614 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5615 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5616 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5617 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5618 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5619 break;
5620
5621 case ICmpInst::ICMP_SGE:
5622 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5623 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5624 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5625 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5626 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5627 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5628 break;
5629 }
5630
5631 // If we still have a icmp le or icmp ge instruction, turn it into the
5632 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5633 // already been handled above, this requires little checking.
5634 //
5635 switch (I.getPredicate()) {
5636 default: break;
5637 case ICmpInst::ICMP_ULE:
5638 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5639 case ICmpInst::ICMP_SLE:
5640 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5641 case ICmpInst::ICMP_UGE:
5642 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5643 case ICmpInst::ICMP_SGE:
5644 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5645 }
5646
5647 // See if we can fold the comparison based on bits known to be zero or one
5648 // in the input. If this comparison is a normal comparison, it demands all
5649 // bits, if it is a sign bit comparison, it only demands the sign bit.
5650
5651 bool UnusedBit;
5652 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5653
5654 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5655 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5656 if (SimplifyDemandedBits(Op0,
5657 isSignBit ? APInt::getSignBit(BitWidth)
5658 : APInt::getAllOnesValue(BitWidth),
5659 KnownZero, KnownOne, 0))
5660 return &I;
5661
5662 // Given the known and unknown bits, compute a range that the LHS could be
5663 // in.
5664 if ((KnownOne | KnownZero) != 0) {
5665 // Compute the Min, Max and RHS values based on the known bits. For the
5666 // EQ and NE we use unsigned values.
5667 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5668 const APInt& RHSVal = CI->getValue();
5669 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5670 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5671 Max);
5672 } else {
5673 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5674 Max);
5675 }
5676 switch (I.getPredicate()) { // LE/GE have been folded already.
5677 default: assert(0 && "Unknown icmp opcode!");
5678 case ICmpInst::ICMP_EQ:
5679 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5680 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5681 break;
5682 case ICmpInst::ICMP_NE:
5683 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5684 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5685 break;
5686 case ICmpInst::ICMP_ULT:
5687 if (Max.ult(RHSVal))
5688 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5689 if (Min.uge(RHSVal))
5690 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5691 break;
5692 case ICmpInst::ICMP_UGT:
5693 if (Min.ugt(RHSVal))
5694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695 if (Max.ule(RHSVal))
5696 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5697 break;
5698 case ICmpInst::ICMP_SLT:
5699 if (Max.slt(RHSVal))
5700 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5701 if (Min.sgt(RHSVal))
5702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5703 break;
5704 case ICmpInst::ICMP_SGT:
5705 if (Min.sgt(RHSVal))
5706 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5707 if (Max.sle(RHSVal))
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5709 break;
5710 }
5711 }
5712
5713 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5714 // instruction, see if that instruction also has constants so that the
5715 // instruction can be folded into the icmp
5716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5717 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5718 return Res;
5719 }
5720
5721 // Handle icmp with constant (but not simple integer constant) RHS
5722 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5723 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5724 switch (LHSI->getOpcode()) {
5725 case Instruction::GetElementPtr:
5726 if (RHSC->isNullValue()) {
5727 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5728 bool isAllZeros = true;
5729 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5730 if (!isa<Constant>(LHSI->getOperand(i)) ||
5731 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5732 isAllZeros = false;
5733 break;
5734 }
5735 if (isAllZeros)
5736 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5737 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5738 }
5739 break;
5740
5741 case Instruction::PHI:
5742 if (Instruction *NV = FoldOpIntoPhi(I))
5743 return NV;
5744 break;
5745 case Instruction::Select: {
5746 // If either operand of the select is a constant, we can fold the
5747 // comparison into the select arms, which will cause one to be
5748 // constant folded and the select turned into a bitwise or.
5749 Value *Op1 = 0, *Op2 = 0;
5750 if (LHSI->hasOneUse()) {
5751 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5752 // Fold the known value into the constant operand.
5753 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5754 // Insert a new ICmp of the other select operand.
5755 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5756 LHSI->getOperand(2), RHSC,
5757 I.getName()), I);
5758 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5759 // Fold the known value into the constant operand.
5760 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5761 // Insert a new ICmp of the other select operand.
5762 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5763 LHSI->getOperand(1), RHSC,
5764 I.getName()), I);
5765 }
5766 }
5767
5768 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005769 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005770 break;
5771 }
5772 case Instruction::Malloc:
5773 // If we have (malloc != null), and if the malloc has a single use, we
5774 // can assume it is successful and remove the malloc.
5775 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5776 AddToWorkList(LHSI);
5777 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005778 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005779 }
5780 break;
5781 }
5782 }
5783
5784 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5785 if (User *GEP = dyn_castGetElementPtr(Op0))
5786 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5787 return NI;
5788 if (User *GEP = dyn_castGetElementPtr(Op1))
5789 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5790 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5791 return NI;
5792
5793 // Test to see if the operands of the icmp are casted versions of other
5794 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5795 // now.
5796 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5797 if (isa<PointerType>(Op0->getType()) &&
5798 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5799 // We keep moving the cast from the left operand over to the right
5800 // operand, where it can often be eliminated completely.
5801 Op0 = CI->getOperand(0);
5802
5803 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5804 // so eliminate it as well.
5805 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5806 Op1 = CI2->getOperand(0);
5807
5808 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005809 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5811 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5812 } else {
5813 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005814 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005815 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005816 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005817 return new ICmpInst(I.getPredicate(), Op0, Op1);
5818 }
5819 }
5820
5821 if (isa<CastInst>(Op0)) {
5822 // Handle the special case of: icmp (cast bool to X), <cst>
5823 // This comes up when you have code like
5824 // int X = A < B;
5825 // if (X) ...
5826 // For generality, we handle any zero-extension of any operand comparison
5827 // with a constant or another cast from the same type.
5828 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5829 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5830 return R;
5831 }
5832
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005833 // ~x < ~y --> y < x
5834 { Value *A, *B;
5835 if (match(Op0, m_Not(m_Value(A))) &&
5836 match(Op1, m_Not(m_Value(B))))
5837 return new ICmpInst(I.getPredicate(), B, A);
5838 }
5839
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005840 if (I.isEquality()) {
5841 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005842
5843 // -x == -y --> x == y
5844 if (match(Op0, m_Neg(m_Value(A))) &&
5845 match(Op1, m_Neg(m_Value(B))))
5846 return new ICmpInst(I.getPredicate(), A, B);
5847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005848 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5849 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5850 Value *OtherVal = A == Op1 ? B : A;
5851 return new ICmpInst(I.getPredicate(), OtherVal,
5852 Constant::getNullValue(A->getType()));
5853 }
5854
5855 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5856 // A^c1 == C^c2 --> A == C^(c1^c2)
5857 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5858 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5859 if (Op1->hasOneUse()) {
5860 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005861 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005862 return new ICmpInst(I.getPredicate(), A,
5863 InsertNewInstBefore(Xor, I));
5864 }
5865
5866 // A^B == A^D -> B == D
5867 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5868 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5869 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5870 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5871 }
5872 }
5873
5874 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5875 (A == Op0 || B == Op0)) {
5876 // A == (A^B) -> B == 0
5877 Value *OtherVal = A == Op0 ? B : A;
5878 return new ICmpInst(I.getPredicate(), OtherVal,
5879 Constant::getNullValue(A->getType()));
5880 }
5881 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5882 // (A-B) == A -> B == 0
5883 return new ICmpInst(I.getPredicate(), B,
5884 Constant::getNullValue(B->getType()));
5885 }
5886 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5887 // A == (A-B) -> B == 0
5888 return new ICmpInst(I.getPredicate(), B,
5889 Constant::getNullValue(B->getType()));
5890 }
5891
5892 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5893 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5894 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5895 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5896 Value *X = 0, *Y = 0, *Z = 0;
5897
5898 if (A == C) {
5899 X = B; Y = D; Z = A;
5900 } else if (A == D) {
5901 X = B; Y = C; Z = A;
5902 } else if (B == C) {
5903 X = A; Y = D; Z = B;
5904 } else if (B == D) {
5905 X = A; Y = C; Z = B;
5906 }
5907
5908 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005909 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5910 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005911 I.setOperand(0, Op1);
5912 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5913 return &I;
5914 }
5915 }
5916 }
5917 return Changed ? &I : 0;
5918}
5919
5920
5921/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5922/// and CmpRHS are both known to be integer constants.
5923Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5924 ConstantInt *DivRHS) {
5925 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5926 const APInt &CmpRHSV = CmpRHS->getValue();
5927
5928 // FIXME: If the operand types don't match the type of the divide
5929 // then don't attempt this transform. The code below doesn't have the
5930 // logic to deal with a signed divide and an unsigned compare (and
5931 // vice versa). This is because (x /s C1) <s C2 produces different
5932 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5933 // (x /u C1) <u C2. Simply casting the operands and result won't
5934 // work. :( The if statement below tests that condition and bails
5935 // if it finds it.
5936 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5937 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5938 return 0;
5939 if (DivRHS->isZero())
5940 return 0; // The ProdOV computation fails on divide by zero.
5941
5942 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5943 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5944 // C2 (CI). By solving for X we can turn this into a range check
5945 // instead of computing a divide.
5946 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5947
5948 // Determine if the product overflows by seeing if the product is
5949 // not equal to the divide. Make sure we do the same kind of divide
5950 // as in the LHS instruction that we're folding.
5951 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5952 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5953
5954 // Get the ICmp opcode
5955 ICmpInst::Predicate Pred = ICI.getPredicate();
5956
5957 // Figure out the interval that is being checked. For example, a comparison
5958 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5959 // Compute this interval based on the constants involved and the signedness of
5960 // the compare/divide. This computes a half-open interval, keeping track of
5961 // whether either value in the interval overflows. After analysis each
5962 // overflow variable is set to 0 if it's corresponding bound variable is valid
5963 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5964 int LoOverflow = 0, HiOverflow = 0;
5965 ConstantInt *LoBound = 0, *HiBound = 0;
5966
5967
5968 if (!DivIsSigned) { // udiv
5969 // e.g. X/5 op 3 --> [15, 20)
5970 LoBound = Prod;
5971 HiOverflow = LoOverflow = ProdOV;
5972 if (!HiOverflow)
5973 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005974 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005975 if (CmpRHSV == 0) { // (X / pos) op 0
5976 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5977 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5978 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005979 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005980 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5981 HiOverflow = LoOverflow = ProdOV;
5982 if (!HiOverflow)
5983 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5984 } else { // (X / pos) op neg
5985 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5986 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5987 LoOverflow = AddWithOverflow(LoBound, Prod,
5988 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5989 HiBound = AddOne(Prod);
5990 HiOverflow = ProdOV ? -1 : 0;
5991 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005992 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005993 if (CmpRHSV == 0) { // (X / neg) op 0
5994 // e.g. X/-5 op 0 --> [-4, 5)
5995 LoBound = AddOne(DivRHS);
5996 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5997 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5998 HiOverflow = 1; // [INTMIN+1, overflow)
5999 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6000 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006001 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002 // e.g. X/-5 op 3 --> [-19, -14)
6003 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6004 if (!LoOverflow)
6005 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6006 HiBound = AddOne(Prod);
6007 } else { // (X / neg) op neg
6008 // e.g. X/-5 op -3 --> [15, 20)
6009 LoBound = Prod;
6010 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6011 HiBound = Subtract(Prod, DivRHS);
6012 }
6013
6014 // Dividing by a negative swaps the condition. LT <-> GT
6015 Pred = ICmpInst::getSwappedPredicate(Pred);
6016 }
6017
6018 Value *X = DivI->getOperand(0);
6019 switch (Pred) {
6020 default: assert(0 && "Unhandled icmp opcode!");
6021 case ICmpInst::ICMP_EQ:
6022 if (LoOverflow && HiOverflow)
6023 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6024 else if (HiOverflow)
6025 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6026 ICmpInst::ICMP_UGE, X, LoBound);
6027 else if (LoOverflow)
6028 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6029 ICmpInst::ICMP_ULT, X, HiBound);
6030 else
6031 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6032 case ICmpInst::ICMP_NE:
6033 if (LoOverflow && HiOverflow)
6034 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6035 else if (HiOverflow)
6036 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6037 ICmpInst::ICMP_ULT, X, LoBound);
6038 else if (LoOverflow)
6039 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6040 ICmpInst::ICMP_UGE, X, HiBound);
6041 else
6042 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6043 case ICmpInst::ICMP_ULT:
6044 case ICmpInst::ICMP_SLT:
6045 if (LoOverflow == +1) // Low bound is greater than input range.
6046 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6047 if (LoOverflow == -1) // Low bound is less than input range.
6048 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6049 return new ICmpInst(Pred, X, LoBound);
6050 case ICmpInst::ICMP_UGT:
6051 case ICmpInst::ICMP_SGT:
6052 if (HiOverflow == +1) // High bound greater than input range.
6053 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6054 else if (HiOverflow == -1) // High bound less than input range.
6055 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6056 if (Pred == ICmpInst::ICMP_UGT)
6057 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6058 else
6059 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6060 }
6061}
6062
6063
6064/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6065///
6066Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6067 Instruction *LHSI,
6068 ConstantInt *RHS) {
6069 const APInt &RHSV = RHS->getValue();
6070
6071 switch (LHSI->getOpcode()) {
6072 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6073 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6074 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6075 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006076 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6077 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006078 Value *CompareVal = LHSI->getOperand(0);
6079
6080 // If the sign bit of the XorCST is not set, there is no change to
6081 // the operation, just stop using the Xor.
6082 if (!XorCST->getValue().isNegative()) {
6083 ICI.setOperand(0, CompareVal);
6084 AddToWorkList(LHSI);
6085 return &ICI;
6086 }
6087
6088 // Was the old condition true if the operand is positive?
6089 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6090
6091 // If so, the new one isn't.
6092 isTrueIfPositive ^= true;
6093
6094 if (isTrueIfPositive)
6095 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6096 else
6097 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6098 }
6099 }
6100 break;
6101 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6102 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6103 LHSI->getOperand(0)->hasOneUse()) {
6104 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6105
6106 // If the LHS is an AND of a truncating cast, we can widen the
6107 // and/compare to be the input width without changing the value
6108 // produced, eliminating a cast.
6109 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6110 // We can do this transformation if either the AND constant does not
6111 // have its sign bit set or if it is an equality comparison.
6112 // Extending a relational comparison when we're checking the sign
6113 // bit would not work.
6114 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006115 (ICI.isEquality() ||
6116 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 uint32_t BitWidth =
6118 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6119 APInt NewCST = AndCST->getValue();
6120 NewCST.zext(BitWidth);
6121 APInt NewCI = RHSV;
6122 NewCI.zext(BitWidth);
6123 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006124 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006125 ConstantInt::get(NewCST),LHSI->getName());
6126 InsertNewInstBefore(NewAnd, ICI);
6127 return new ICmpInst(ICI.getPredicate(), NewAnd,
6128 ConstantInt::get(NewCI));
6129 }
6130 }
6131
6132 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6133 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6134 // happens a LOT in code produced by the C front-end, for bitfield
6135 // access.
6136 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6137 if (Shift && !Shift->isShift())
6138 Shift = 0;
6139
6140 ConstantInt *ShAmt;
6141 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6142 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6143 const Type *AndTy = AndCST->getType(); // Type of the and.
6144
6145 // We can fold this as long as we can't shift unknown bits
6146 // into the mask. This can only happen with signed shift
6147 // rights, as they sign-extend.
6148 if (ShAmt) {
6149 bool CanFold = Shift->isLogicalShift();
6150 if (!CanFold) {
6151 // To test for the bad case of the signed shr, see if any
6152 // of the bits shifted in could be tested after the mask.
6153 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6154 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6155
6156 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6157 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6158 AndCST->getValue()) == 0)
6159 CanFold = true;
6160 }
6161
6162 if (CanFold) {
6163 Constant *NewCst;
6164 if (Shift->getOpcode() == Instruction::Shl)
6165 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6166 else
6167 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6168
6169 // Check to see if we are shifting out any of the bits being
6170 // compared.
6171 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6172 // If we shifted bits out, the fold is not going to work out.
6173 // As a special case, check to see if this means that the
6174 // result is always true or false now.
6175 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6176 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6177 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6178 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6179 } else {
6180 ICI.setOperand(1, NewCst);
6181 Constant *NewAndCST;
6182 if (Shift->getOpcode() == Instruction::Shl)
6183 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6184 else
6185 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6186 LHSI->setOperand(1, NewAndCST);
6187 LHSI->setOperand(0, Shift->getOperand(0));
6188 AddToWorkList(Shift); // Shift is dead.
6189 AddUsesToWorkList(ICI);
6190 return &ICI;
6191 }
6192 }
6193 }
6194
6195 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6196 // preferable because it allows the C<<Y expression to be hoisted out
6197 // of a loop if Y is invariant and X is not.
6198 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6199 ICI.isEquality() && !Shift->isArithmeticShift() &&
6200 isa<Instruction>(Shift->getOperand(0))) {
6201 // Compute C << Y.
6202 Value *NS;
6203 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006204 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006205 Shift->getOperand(1), "tmp");
6206 } else {
6207 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006208 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006209 Shift->getOperand(1), "tmp");
6210 }
6211 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6212
6213 // Compute X & (C << Y).
6214 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006215 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 InsertNewInstBefore(NewAnd, ICI);
6217
6218 ICI.setOperand(0, NewAnd);
6219 return &ICI;
6220 }
6221 }
6222 break;
6223
6224 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6225 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6226 if (!ShAmt) break;
6227
6228 uint32_t TypeBits = RHSV.getBitWidth();
6229
6230 // Check that the shift amount is in range. If not, don't perform
6231 // undefined shifts. When the shift is visited it will be
6232 // simplified.
6233 if (ShAmt->uge(TypeBits))
6234 break;
6235
6236 if (ICI.isEquality()) {
6237 // If we are comparing against bits always shifted out, the
6238 // comparison cannot succeed.
6239 Constant *Comp =
6240 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6241 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6242 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6243 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6244 return ReplaceInstUsesWith(ICI, Cst);
6245 }
6246
6247 if (LHSI->hasOneUse()) {
6248 // Otherwise strength reduce the shift into an and.
6249 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6250 Constant *Mask =
6251 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6252
6253 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006254 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006255 Mask, LHSI->getName()+".mask");
6256 Value *And = InsertNewInstBefore(AndI, ICI);
6257 return new ICmpInst(ICI.getPredicate(), And,
6258 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6259 }
6260 }
6261
6262 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6263 bool TrueIfSigned = false;
6264 if (LHSI->hasOneUse() &&
6265 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6266 // (X << 31) <s 0 --> (X&1) != 0
6267 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6268 (TypeBits-ShAmt->getZExtValue()-1));
6269 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006270 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006271 Mask, LHSI->getName()+".mask");
6272 Value *And = InsertNewInstBefore(AndI, ICI);
6273
6274 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6275 And, Constant::getNullValue(And->getType()));
6276 }
6277 break;
6278 }
6279
6280 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6281 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006282 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006283 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006284 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006285
Chris Lattner5ee84f82008-03-21 05:19:58 +00006286 // Check that the shift amount is in range. If not, don't perform
6287 // undefined shifts. When the shift is visited it will be
6288 // simplified.
6289 uint32_t TypeBits = RHSV.getBitWidth();
6290 if (ShAmt->uge(TypeBits))
6291 break;
6292
6293 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006294
Chris Lattner5ee84f82008-03-21 05:19:58 +00006295 // If we are comparing against bits always shifted out, the
6296 // comparison cannot succeed.
6297 APInt Comp = RHSV << ShAmtVal;
6298 if (LHSI->getOpcode() == Instruction::LShr)
6299 Comp = Comp.lshr(ShAmtVal);
6300 else
6301 Comp = Comp.ashr(ShAmtVal);
6302
6303 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6304 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6305 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6306 return ReplaceInstUsesWith(ICI, Cst);
6307 }
6308
6309 // Otherwise, check to see if the bits shifted out are known to be zero.
6310 // If so, we can compare against the unshifted value:
6311 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006312 if (LHSI->hasOneUse() &&
6313 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006314 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6315 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6316 ConstantExpr::getShl(RHS, ShAmt));
6317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006318
Evan Chengfb9292a2008-04-23 00:38:06 +00006319 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006320 // Otherwise strength reduce the shift into an and.
6321 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6322 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323
Chris Lattner5ee84f82008-03-21 05:19:58 +00006324 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006325 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006326 Mask, LHSI->getName()+".mask");
6327 Value *And = InsertNewInstBefore(AndI, ICI);
6328 return new ICmpInst(ICI.getPredicate(), And,
6329 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006330 }
6331 break;
6332 }
6333
6334 case Instruction::SDiv:
6335 case Instruction::UDiv:
6336 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6337 // Fold this div into the comparison, producing a range check.
6338 // Determine, based on the divide type, what the range is being
6339 // checked. If there is an overflow on the low or high side, remember
6340 // it, otherwise compute the range [low, hi) bounding the new value.
6341 // See: InsertRangeTest above for the kinds of replacements possible.
6342 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6343 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6344 DivRHS))
6345 return R;
6346 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006347
6348 case Instruction::Add:
6349 // Fold: icmp pred (add, X, C1), C2
6350
6351 if (!ICI.isEquality()) {
6352 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6353 if (!LHSC) break;
6354 const APInt &LHSV = LHSC->getValue();
6355
6356 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6357 .subtract(LHSV);
6358
6359 if (ICI.isSignedPredicate()) {
6360 if (CR.getLower().isSignBit()) {
6361 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6362 ConstantInt::get(CR.getUpper()));
6363 } else if (CR.getUpper().isSignBit()) {
6364 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6365 ConstantInt::get(CR.getLower()));
6366 }
6367 } else {
6368 if (CR.getLower().isMinValue()) {
6369 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6370 ConstantInt::get(CR.getUpper()));
6371 } else if (CR.getUpper().isMinValue()) {
6372 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6373 ConstantInt::get(CR.getLower()));
6374 }
6375 }
6376 }
6377 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006378 }
6379
6380 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6381 if (ICI.isEquality()) {
6382 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6383
6384 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6385 // the second operand is a constant, simplify a bit.
6386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6387 switch (BO->getOpcode()) {
6388 case Instruction::SRem:
6389 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6390 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6391 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6392 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6393 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006394 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006395 BO->getName());
6396 InsertNewInstBefore(NewRem, ICI);
6397 return new ICmpInst(ICI.getPredicate(), NewRem,
6398 Constant::getNullValue(BO->getType()));
6399 }
6400 }
6401 break;
6402 case Instruction::Add:
6403 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6404 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6405 if (BO->hasOneUse())
6406 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6407 Subtract(RHS, BOp1C));
6408 } else if (RHSV == 0) {
6409 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6410 // efficiently invertible, or if the add has just this one use.
6411 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6412
6413 if (Value *NegVal = dyn_castNegVal(BOp1))
6414 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6415 else if (Value *NegVal = dyn_castNegVal(BOp0))
6416 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6417 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006418 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006419 InsertNewInstBefore(Neg, ICI);
6420 Neg->takeName(BO);
6421 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6422 }
6423 }
6424 break;
6425 case Instruction::Xor:
6426 // For the xor case, we can xor two constants together, eliminating
6427 // the explicit xor.
6428 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6429 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6430 ConstantExpr::getXor(RHS, BOC));
6431
6432 // FALLTHROUGH
6433 case Instruction::Sub:
6434 // Replace (([sub|xor] A, B) != 0) with (A != B)
6435 if (RHSV == 0)
6436 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6437 BO->getOperand(1));
6438 break;
6439
6440 case Instruction::Or:
6441 // If bits are being or'd in that are not present in the constant we
6442 // are comparing against, then the comparison could never succeed!
6443 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6444 Constant *NotCI = ConstantExpr::getNot(RHS);
6445 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6446 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6447 isICMP_NE));
6448 }
6449 break;
6450
6451 case Instruction::And:
6452 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6453 // If bits are being compared against that are and'd out, then the
6454 // comparison can never succeed!
6455 if ((RHSV & ~BOC->getValue()) != 0)
6456 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6457 isICMP_NE));
6458
6459 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6460 if (RHS == BOC && RHSV.isPowerOf2())
6461 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6462 ICmpInst::ICMP_NE, LHSI,
6463 Constant::getNullValue(RHS->getType()));
6464
6465 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6466 if (isSignBit(BOC)) {
6467 Value *X = BO->getOperand(0);
6468 Constant *Zero = Constant::getNullValue(X->getType());
6469 ICmpInst::Predicate pred = isICMP_NE ?
6470 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6471 return new ICmpInst(pred, X, Zero);
6472 }
6473
6474 // ((X & ~7) == 0) --> X < 8
6475 if (RHSV == 0 && isHighOnes(BOC)) {
6476 Value *X = BO->getOperand(0);
6477 Constant *NegX = ConstantExpr::getNeg(BOC);
6478 ICmpInst::Predicate pred = isICMP_NE ?
6479 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6480 return new ICmpInst(pred, X, NegX);
6481 }
6482 }
6483 default: break;
6484 }
6485 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6486 // Handle icmp {eq|ne} <intrinsic>, intcst.
6487 if (II->getIntrinsicID() == Intrinsic::bswap) {
6488 AddToWorkList(II);
6489 ICI.setOperand(0, II->getOperand(1));
6490 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6491 return &ICI;
6492 }
6493 }
6494 } else { // Not a ICMP_EQ/ICMP_NE
6495 // If the LHS is a cast from an integral value of the same size,
6496 // then since we know the RHS is a constant, try to simlify.
6497 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6498 Value *CastOp = Cast->getOperand(0);
6499 const Type *SrcTy = CastOp->getType();
6500 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6501 if (SrcTy->isInteger() &&
6502 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6503 // If this is an unsigned comparison, try to make the comparison use
6504 // smaller constant values.
6505 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6506 // X u< 128 => X s> -1
6507 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6508 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6509 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6510 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6511 // X u> 127 => X s< 0
6512 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6513 Constant::getNullValue(SrcTy));
6514 }
6515 }
6516 }
6517 }
6518 return 0;
6519}
6520
6521/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6522/// We only handle extending casts so far.
6523///
6524Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6525 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6526 Value *LHSCIOp = LHSCI->getOperand(0);
6527 const Type *SrcTy = LHSCIOp->getType();
6528 const Type *DestTy = LHSCI->getType();
6529 Value *RHSCIOp;
6530
6531 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6532 // integer type is the same size as the pointer type.
6533 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6534 getTargetData().getPointerSizeInBits() ==
6535 cast<IntegerType>(DestTy)->getBitWidth()) {
6536 Value *RHSOp = 0;
6537 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6538 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6539 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6540 RHSOp = RHSC->getOperand(0);
6541 // If the pointer types don't match, insert a bitcast.
6542 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006543 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006544 }
6545
6546 if (RHSOp)
6547 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6548 }
6549
6550 // The code below only handles extension cast instructions, so far.
6551 // Enforce this.
6552 if (LHSCI->getOpcode() != Instruction::ZExt &&
6553 LHSCI->getOpcode() != Instruction::SExt)
6554 return 0;
6555
6556 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6557 bool isSignedCmp = ICI.isSignedPredicate();
6558
6559 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6560 // Not an extension from the same type?
6561 RHSCIOp = CI->getOperand(0);
6562 if (RHSCIOp->getType() != LHSCIOp->getType())
6563 return 0;
6564
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006565 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566 // and the other is a zext), then we can't handle this.
6567 if (CI->getOpcode() != LHSCI->getOpcode())
6568 return 0;
6569
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006570 // Deal with equality cases early.
6571 if (ICI.isEquality())
6572 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6573
6574 // A signed comparison of sign extended values simplifies into a
6575 // signed comparison.
6576 if (isSignedCmp && isSignedExt)
6577 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6578
6579 // The other three cases all fold into an unsigned comparison.
6580 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006581 }
6582
6583 // If we aren't dealing with a constant on the RHS, exit early
6584 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6585 if (!CI)
6586 return 0;
6587
6588 // Compute the constant that would happen if we truncated to SrcTy then
6589 // reextended to DestTy.
6590 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6591 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6592
6593 // If the re-extended constant didn't change...
6594 if (Res2 == CI) {
6595 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6596 // For example, we might have:
6597 // %A = sext short %X to uint
6598 // %B = icmp ugt uint %A, 1330
6599 // It is incorrect to transform this into
6600 // %B = icmp ugt short %X, 1330
6601 // because %A may have negative value.
6602 //
6603 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6604 // OR operation is EQ/NE.
6605 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6606 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6607 else
6608 return 0;
6609 }
6610
6611 // The re-extended constant changed so the constant cannot be represented
6612 // in the shorter type. Consequently, we cannot emit a simple comparison.
6613
6614 // First, handle some easy cases. We know the result cannot be equal at this
6615 // point so handle the ICI.isEquality() cases
6616 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6617 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6618 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6619 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6620
6621 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6622 // should have been folded away previously and not enter in here.
6623 Value *Result;
6624 if (isSignedCmp) {
6625 // We're performing a signed comparison.
6626 if (cast<ConstantInt>(CI)->getValue().isNegative())
6627 Result = ConstantInt::getFalse(); // X < (small) --> false
6628 else
6629 Result = ConstantInt::getTrue(); // X < (large) --> true
6630 } else {
6631 // We're performing an unsigned comparison.
6632 if (isSignedExt) {
6633 // We're performing an unsigned comp with a sign extended value.
6634 // This is true if the input is >= 0. [aka >s -1]
6635 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6636 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6637 NegOne, ICI.getName()), ICI);
6638 } else {
6639 // Unsigned extend & unsigned compare -> always true.
6640 Result = ConstantInt::getTrue();
6641 }
6642 }
6643
6644 // Finally, return the value computed.
6645 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6646 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6647 return ReplaceInstUsesWith(ICI, Result);
6648 } else {
6649 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6650 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6651 "ICmp should be folded!");
6652 if (Constant *CI = dyn_cast<Constant>(Result))
6653 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6654 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006655 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 }
6657}
6658
6659Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6660 return commonShiftTransforms(I);
6661}
6662
6663Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6664 return commonShiftTransforms(I);
6665}
6666
6667Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006668 if (Instruction *R = commonShiftTransforms(I))
6669 return R;
6670
6671 Value *Op0 = I.getOperand(0);
6672
6673 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6674 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6675 if (CSI->isAllOnesValue())
6676 return ReplaceInstUsesWith(I, CSI);
6677
6678 // See if we can turn a signed shr into an unsigned shr.
6679 if (MaskedValueIsZero(Op0,
6680 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006681 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006682
6683 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006684}
6685
6686Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6687 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6689
6690 // shl X, 0 == X and shr X, 0 == X
6691 // shl 0, X == 0 and shr 0, X == 0
6692 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6693 Op0 == Constant::getNullValue(Op0->getType()))
6694 return ReplaceInstUsesWith(I, Op0);
6695
6696 if (isa<UndefValue>(Op0)) {
6697 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6698 return ReplaceInstUsesWith(I, Op0);
6699 else // undef << X -> 0, undef >>u X -> 0
6700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6701 }
6702 if (isa<UndefValue>(Op1)) {
6703 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6704 return ReplaceInstUsesWith(I, Op0);
6705 else // X << undef, X >>u undef -> 0
6706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6707 }
6708
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006709 // Try to fold constant and into select arguments.
6710 if (isa<Constant>(Op0))
6711 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6712 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6713 return R;
6714
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006715 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6716 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6717 return Res;
6718 return 0;
6719}
6720
6721Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6722 BinaryOperator &I) {
6723 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6724
6725 // See if we can simplify any instructions used by the instruction whose sole
6726 // purpose is to compute bits we don't care about.
6727 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6728 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6729 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6730 KnownZero, KnownOne))
6731 return &I;
6732
6733 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6734 // of a signed value.
6735 //
6736 if (Op1->uge(TypeBits)) {
6737 if (I.getOpcode() != Instruction::AShr)
6738 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6739 else {
6740 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6741 return &I;
6742 }
6743 }
6744
6745 // ((X*C1) << C2) == (X * (C1 << C2))
6746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6747 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6748 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006749 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006750 ConstantExpr::getShl(BOOp, Op1));
6751
6752 // Try to fold constant and into select arguments.
6753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6754 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6755 return R;
6756 if (isa<PHINode>(Op0))
6757 if (Instruction *NV = FoldOpIntoPhi(I))
6758 return NV;
6759
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006760 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6761 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6762 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6763 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6764 // place. Don't try to do this transformation in this case. Also, we
6765 // require that the input operand is a shift-by-constant so that we have
6766 // confidence that the shifts will get folded together. We could do this
6767 // xform in more cases, but it is unlikely to be profitable.
6768 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6769 isa<ConstantInt>(TrOp->getOperand(1))) {
6770 // Okay, we'll do this xform. Make the shift of shift.
6771 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006772 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006773 I.getName());
6774 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6775
6776 // For logical shifts, the truncation has the effect of making the high
6777 // part of the register be zeros. Emulate this by inserting an AND to
6778 // clear the top bits as needed. This 'and' will usually be zapped by
6779 // other xforms later if dead.
6780 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6781 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6782 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6783
6784 // The mask we constructed says what the trunc would do if occurring
6785 // between the shifts. We want to know the effect *after* the second
6786 // shift. We know that it is a logical shift by a constant, so adjust the
6787 // mask as appropriate.
6788 if (I.getOpcode() == Instruction::Shl)
6789 MaskV <<= Op1->getZExtValue();
6790 else {
6791 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6792 MaskV = MaskV.lshr(Op1->getZExtValue());
6793 }
6794
Gabor Greifa645dd32008-05-16 19:29:10 +00006795 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006796 TI->getName());
6797 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6798
6799 // Return the value truncated to the interesting size.
6800 return new TruncInst(And, I.getType());
6801 }
6802 }
6803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804 if (Op0->hasOneUse()) {
6805 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6806 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6807 Value *V1, *V2;
6808 ConstantInt *CC;
6809 switch (Op0BO->getOpcode()) {
6810 default: break;
6811 case Instruction::Add:
6812 case Instruction::And:
6813 case Instruction::Or:
6814 case Instruction::Xor: {
6815 // These operators commute.
6816 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6817 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6818 match(Op0BO->getOperand(1),
6819 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006820 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006821 Op0BO->getOperand(0), Op1,
6822 Op0BO->getName());
6823 InsertNewInstBefore(YS, I); // (Y << C)
6824 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006825 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006826 Op0BO->getOperand(1)->getName());
6827 InsertNewInstBefore(X, I); // (X + (Y << C))
6828 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006829 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006830 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6831 }
6832
6833 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6834 Value *Op0BOOp1 = Op0BO->getOperand(1);
6835 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6836 match(Op0BOOp1,
6837 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6838 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6839 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006840 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006841 Op0BO->getOperand(0), Op1,
6842 Op0BO->getName());
6843 InsertNewInstBefore(YS, I); // (Y << C)
6844 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006845 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006846 V1->getName()+".mask");
6847 InsertNewInstBefore(XM, I); // X & (CC << C)
6848
Gabor Greifa645dd32008-05-16 19:29:10 +00006849 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006850 }
6851 }
6852
6853 // FALL THROUGH.
6854 case Instruction::Sub: {
6855 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6856 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6857 match(Op0BO->getOperand(0),
6858 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006859 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 Op0BO->getOperand(1), Op1,
6861 Op0BO->getName());
6862 InsertNewInstBefore(YS, I); // (Y << C)
6863 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006864 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006865 Op0BO->getOperand(0)->getName());
6866 InsertNewInstBefore(X, I); // (X + (Y << C))
6867 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006868 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006869 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6870 }
6871
6872 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6873 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6874 match(Op0BO->getOperand(0),
6875 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6876 m_ConstantInt(CC))) && V2 == Op1 &&
6877 cast<BinaryOperator>(Op0BO->getOperand(0))
6878 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006879 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006880 Op0BO->getOperand(1), Op1,
6881 Op0BO->getName());
6882 InsertNewInstBefore(YS, I); // (Y << C)
6883 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006884 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 V1->getName()+".mask");
6886 InsertNewInstBefore(XM, I); // X & (CC << C)
6887
Gabor Greifa645dd32008-05-16 19:29:10 +00006888 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006889 }
6890
6891 break;
6892 }
6893 }
6894
6895
6896 // If the operand is an bitwise operator with a constant RHS, and the
6897 // shift is the only use, we can pull it out of the shift.
6898 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6899 bool isValid = true; // Valid only for And, Or, Xor
6900 bool highBitSet = false; // Transform if high bit of constant set?
6901
6902 switch (Op0BO->getOpcode()) {
6903 default: isValid = false; break; // Do not perform transform!
6904 case Instruction::Add:
6905 isValid = isLeftShift;
6906 break;
6907 case Instruction::Or:
6908 case Instruction::Xor:
6909 highBitSet = false;
6910 break;
6911 case Instruction::And:
6912 highBitSet = true;
6913 break;
6914 }
6915
6916 // If this is a signed shift right, and the high bit is modified
6917 // by the logical operation, do not perform the transformation.
6918 // The highBitSet boolean indicates the value of the high bit of
6919 // the constant which would cause it to be modified for this
6920 // operation.
6921 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006922 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006923 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006924
6925 if (isValid) {
6926 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6927
6928 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006929 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006930 InsertNewInstBefore(NewShift, I);
6931 NewShift->takeName(Op0BO);
6932
Gabor Greifa645dd32008-05-16 19:29:10 +00006933 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006934 NewRHS);
6935 }
6936 }
6937 }
6938 }
6939
6940 // Find out if this is a shift of a shift by a constant.
6941 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6942 if (ShiftOp && !ShiftOp->isShift())
6943 ShiftOp = 0;
6944
6945 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6946 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6947 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6948 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6949 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6950 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6951 Value *X = ShiftOp->getOperand(0);
6952
6953 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6954 if (AmtSum > TypeBits)
6955 AmtSum = TypeBits;
6956
6957 const IntegerType *Ty = cast<IntegerType>(I.getType());
6958
6959 // Check for (X << c1) << c2 and (X >> c1) >> c2
6960 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006961 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006962 ConstantInt::get(Ty, AmtSum));
6963 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6964 I.getOpcode() == Instruction::AShr) {
6965 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006966 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006967 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6968 I.getOpcode() == Instruction::LShr) {
6969 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6970 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006971 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006972 InsertNewInstBefore(Shift, I);
6973
6974 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006975 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006976 }
6977
6978 // Okay, if we get here, one shift must be left, and the other shift must be
6979 // right. See if the amounts are equal.
6980 if (ShiftAmt1 == ShiftAmt2) {
6981 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6982 if (I.getOpcode() == Instruction::Shl) {
6983 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006984 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006985 }
6986 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6987 if (I.getOpcode() == Instruction::LShr) {
6988 APInt Mask(APInt::getLowBitsSet(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 // We can simplify ((X << C) >>s C) into a trunc + sext.
6992 // NOTE: we could do this for any C, but that would make 'unusual' integer
6993 // types. For now, just stick to ones well-supported by the code
6994 // generators.
6995 const Type *SExtType = 0;
6996 switch (Ty->getBitWidth() - ShiftAmt1) {
6997 case 1 :
6998 case 8 :
6999 case 16 :
7000 case 32 :
7001 case 64 :
7002 case 128:
7003 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7004 break;
7005 default: break;
7006 }
7007 if (SExtType) {
7008 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7009 InsertNewInstBefore(NewTrunc, I);
7010 return new SExtInst(NewTrunc, Ty);
7011 }
7012 // Otherwise, we can't handle it yet.
7013 } else if (ShiftAmt1 < ShiftAmt2) {
7014 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7015
7016 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7017 if (I.getOpcode() == Instruction::Shl) {
7018 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7019 ShiftOp->getOpcode() == Instruction::AShr);
7020 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007021 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007022 InsertNewInstBefore(Shift, I);
7023
7024 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007025 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007026 }
7027
7028 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7029 if (I.getOpcode() == Instruction::LShr) {
7030 assert(ShiftOp->getOpcode() == Instruction::Shl);
7031 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007032 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007033 InsertNewInstBefore(Shift, I);
7034
7035 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007036 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007037 }
7038
7039 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7040 } else {
7041 assert(ShiftAmt2 < ShiftAmt1);
7042 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7043
7044 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7045 if (I.getOpcode() == Instruction::Shl) {
7046 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7047 ShiftOp->getOpcode() == Instruction::AShr);
7048 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007049 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007050 ConstantInt::get(Ty, ShiftDiff));
7051 InsertNewInstBefore(Shift, I);
7052
7053 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007054 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007055 }
7056
7057 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7058 if (I.getOpcode() == Instruction::LShr) {
7059 assert(ShiftOp->getOpcode() == Instruction::Shl);
7060 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007061 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007062 InsertNewInstBefore(Shift, I);
7063
7064 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007065 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007066 }
7067
7068 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7069 }
7070 }
7071 return 0;
7072}
7073
7074
7075/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7076/// expression. If so, decompose it, returning some value X, such that Val is
7077/// X*Scale+Offset.
7078///
7079static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7080 int &Offset) {
7081 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7082 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7083 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007084 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007085 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007086 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7088 if (I->getOpcode() == Instruction::Shl) {
7089 // This is a value scaled by '1 << the shift amt'.
7090 Scale = 1U << RHS->getZExtValue();
7091 Offset = 0;
7092 return I->getOperand(0);
7093 } else if (I->getOpcode() == Instruction::Mul) {
7094 // This value is scaled by 'RHS'.
7095 Scale = RHS->getZExtValue();
7096 Offset = 0;
7097 return I->getOperand(0);
7098 } else if (I->getOpcode() == Instruction::Add) {
7099 // We have X+C. Check to see if we really have (X*C2)+C1,
7100 // where C1 is divisible by C2.
7101 unsigned SubScale;
7102 Value *SubVal =
7103 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7104 Offset += RHS->getZExtValue();
7105 Scale = SubScale;
7106 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007107 }
7108 }
7109 }
7110
7111 // Otherwise, we can't look past this.
7112 Scale = 1;
7113 Offset = 0;
7114 return Val;
7115}
7116
7117
7118/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7119/// try to eliminate the cast by moving the type information into the alloc.
7120Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7121 AllocationInst &AI) {
7122 const PointerType *PTy = cast<PointerType>(CI.getType());
7123
7124 // Remove any uses of AI that are dead.
7125 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7126
7127 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7128 Instruction *User = cast<Instruction>(*UI++);
7129 if (isInstructionTriviallyDead(User)) {
7130 while (UI != E && *UI == User)
7131 ++UI; // If this instruction uses AI more than once, don't break UI.
7132
7133 ++NumDeadInst;
7134 DOUT << "IC: DCE: " << *User;
7135 EraseInstFromFunction(*User);
7136 }
7137 }
7138
7139 // Get the type really allocated and the type casted to.
7140 const Type *AllocElTy = AI.getAllocatedType();
7141 const Type *CastElTy = PTy->getElementType();
7142 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7143
7144 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7145 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7146 if (CastElTyAlign < AllocElTyAlign) return 0;
7147
7148 // If the allocation has multiple uses, only promote it if we are strictly
7149 // increasing the alignment of the resultant allocation. If we keep it the
7150 // same, we open the door to infinite loops of various kinds.
7151 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7152
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007153 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7154 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7156
7157 // See if we can satisfy the modulus by pulling a scale out of the array
7158 // size argument.
7159 unsigned ArraySizeScale;
7160 int ArrayOffset;
7161 Value *NumElements = // See if the array size is a decomposable linear expr.
7162 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7163
7164 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7165 // do the xform.
7166 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7167 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7168
7169 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7170 Value *Amt = 0;
7171 if (Scale == 1) {
7172 Amt = NumElements;
7173 } else {
7174 // If the allocation size is constant, form a constant mul expression
7175 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7176 if (isa<ConstantInt>(NumElements))
7177 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7178 // otherwise multiply the amount and the number of elements
7179 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007180 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007181 Amt = InsertNewInstBefore(Tmp, AI);
7182 }
7183 }
7184
7185 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7186 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007187 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007188 Amt = InsertNewInstBefore(Tmp, AI);
7189 }
7190
7191 AllocationInst *New;
7192 if (isa<MallocInst>(AI))
7193 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7194 else
7195 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7196 InsertNewInstBefore(New, AI);
7197 New->takeName(&AI);
7198
7199 // If the allocation has multiple uses, insert a cast and change all things
7200 // that used it to use the new cast. This will also hack on CI, but it will
7201 // die soon.
7202 if (!AI.hasOneUse()) {
7203 AddUsesToWorkList(AI);
7204 // New is the allocation instruction, pointer typed. AI is the original
7205 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7206 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7207 InsertNewInstBefore(NewCast, AI);
7208 AI.replaceAllUsesWith(NewCast);
7209 }
7210 return ReplaceInstUsesWith(CI, New);
7211}
7212
7213/// CanEvaluateInDifferentType - Return true if we can take the specified value
7214/// and return it as type Ty without inserting any new casts and without
7215/// changing the computed value. This is used by code that tries to decide
7216/// whether promoting or shrinking integer operations to wider or smaller types
7217/// will allow us to eliminate a truncate or extend.
7218///
7219/// This is a truncation operation if Ty is smaller than V->getType(), or an
7220/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007221bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7222 unsigned CastOpc,
7223 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007224 // We can always evaluate constants in another type.
7225 if (isa<ConstantInt>(V))
7226 return true;
7227
7228 Instruction *I = dyn_cast<Instruction>(V);
7229 if (!I) return false;
7230
7231 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7232
Chris Lattneref70bb82007-08-02 06:11:14 +00007233 // If this is an extension or truncate, we can often eliminate it.
7234 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7235 // If this is a cast from the destination type, we can trivially eliminate
7236 // it, and this will remove a cast overall.
7237 if (I->getOperand(0)->getType() == Ty) {
7238 // If the first operand is itself a cast, and is eliminable, do not count
7239 // this as an eliminable cast. We would prefer to eliminate those two
7240 // casts first.
7241 if (!isa<CastInst>(I->getOperand(0)))
7242 ++NumCastsRemoved;
7243 return true;
7244 }
7245 }
7246
7247 // We can't extend or shrink something that has multiple uses: doing so would
7248 // require duplicating the instruction in general, which isn't profitable.
7249 if (!I->hasOneUse()) return false;
7250
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007251 switch (I->getOpcode()) {
7252 case Instruction::Add:
7253 case Instruction::Sub:
7254 case Instruction::And:
7255 case Instruction::Or:
7256 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007257 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007258 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7259 NumCastsRemoved) &&
7260 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7261 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007262
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007263 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007264 // A multiply can be truncated by truncating its operands.
7265 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7266 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7267 NumCastsRemoved) &&
7268 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7269 NumCastsRemoved);
7270
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007271 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007272 // If we are truncating the result of this SHL, and if it's a shift of a
7273 // constant amount, we can always perform a SHL in a smaller type.
7274 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7275 uint32_t BitWidth = Ty->getBitWidth();
7276 if (BitWidth < OrigTy->getBitWidth() &&
7277 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007278 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7279 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007280 }
7281 break;
7282 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007283 // If this is a truncate of a logical shr, we can truncate it to a smaller
7284 // lshr iff we know that the bits we would otherwise be shifting in are
7285 // already zeros.
7286 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7287 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7288 uint32_t BitWidth = Ty->getBitWidth();
7289 if (BitWidth < OrigBitWidth &&
7290 MaskedValueIsZero(I->getOperand(0),
7291 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7292 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007293 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7294 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007295 }
7296 }
7297 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 case Instruction::ZExt:
7299 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007300 case Instruction::Trunc:
7301 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007302 // can safely replace it. Note that replacing it does not reduce the number
7303 // of casts in the input.
7304 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00007306
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007307 break;
7308 default:
7309 // TODO: Can handle more cases here.
7310 break;
7311 }
7312
7313 return false;
7314}
7315
7316/// EvaluateInDifferentType - Given an expression that
7317/// CanEvaluateInDifferentType returns true for, actually insert the code to
7318/// evaluate the expression.
7319Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7320 bool isSigned) {
7321 if (Constant *C = dyn_cast<Constant>(V))
7322 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7323
7324 // Otherwise, it must be an instruction.
7325 Instruction *I = cast<Instruction>(V);
7326 Instruction *Res = 0;
7327 switch (I->getOpcode()) {
7328 case Instruction::Add:
7329 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007330 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007331 case Instruction::And:
7332 case Instruction::Or:
7333 case Instruction::Xor:
7334 case Instruction::AShr:
7335 case Instruction::LShr:
7336 case Instruction::Shl: {
7337 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7338 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007339 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007340 LHS, RHS, I->getName());
7341 break;
7342 }
7343 case Instruction::Trunc:
7344 case Instruction::ZExt:
7345 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007346 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007347 // just return the source. There's no need to insert it because it is not
7348 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007349 if (I->getOperand(0)->getType() == Ty)
7350 return I->getOperand(0);
7351
Chris Lattneref70bb82007-08-02 06:11:14 +00007352 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007353 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007354 Ty, I->getName());
7355 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007356 default:
7357 // TODO: Can handle more cases here.
7358 assert(0 && "Unreachable!");
7359 break;
7360 }
7361
7362 return InsertNewInstBefore(Res, *I);
7363}
7364
7365/// @brief Implement the transforms common to all CastInst visitors.
7366Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7367 Value *Src = CI.getOperand(0);
7368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7370 // eliminate it now.
7371 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7372 if (Instruction::CastOps opc =
7373 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7374 // The first cast (CSrc) is eliminable so we need to fix up or replace
7375 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007376 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377 }
7378 }
7379
7380 // If we are casting a select then fold the cast into the select
7381 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7382 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7383 return NV;
7384
7385 // If we are casting a PHI then fold the cast into the PHI
7386 if (isa<PHINode>(Src))
7387 if (Instruction *NV = FoldOpIntoPhi(CI))
7388 return NV;
7389
7390 return 0;
7391}
7392
7393/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7394Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7395 Value *Src = CI.getOperand(0);
7396
7397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7398 // If casting the result of a getelementptr instruction with no offset, turn
7399 // this into a cast of the original pointer!
7400 if (GEP->hasAllZeroIndices()) {
7401 // Changing the cast operand is usually not a good idea but it is safe
7402 // here because the pointer operand is being replaced with another
7403 // pointer operand so the opcode doesn't need to change.
7404 AddToWorkList(GEP);
7405 CI.setOperand(0, GEP->getOperand(0));
7406 return &CI;
7407 }
7408
7409 // If the GEP has a single use, and the base pointer is a bitcast, and the
7410 // GEP computes a constant offset, see if we can convert these three
7411 // instructions into fewer. This typically happens with unions and other
7412 // non-type-safe code.
7413 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7414 if (GEP->hasAllConstantIndices()) {
7415 // We are guaranteed to get a constant from EmitGEPOffset.
7416 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7417 int64_t Offset = OffsetV->getSExtValue();
7418
7419 // Get the base pointer input of the bitcast, and the type it points to.
7420 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7421 const Type *GEPIdxTy =
7422 cast<PointerType>(OrigBase->getType())->getElementType();
7423 if (GEPIdxTy->isSized()) {
7424 SmallVector<Value*, 8> NewIndices;
7425
7426 // Start with the index over the outer type. Note that the type size
7427 // might be zero (even if the offset isn't zero) if the indexed type
7428 // is something like [0 x {int, int}]
7429 const Type *IntPtrTy = TD->getIntPtrType();
7430 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007431 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007432 FirstIdx = Offset/TySize;
7433 Offset %= TySize;
7434
7435 // Handle silly modulus not returning values values [0..TySize).
7436 if (Offset < 0) {
7437 --FirstIdx;
7438 Offset += TySize;
7439 assert(Offset >= 0);
7440 }
7441 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7442 }
7443
7444 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7445
7446 // Index into the types. If we fail, set OrigBase to null.
7447 while (Offset) {
7448 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7449 const StructLayout *SL = TD->getStructLayout(STy);
7450 if (Offset < (int64_t)SL->getSizeInBytes()) {
7451 unsigned Elt = SL->getElementContainingOffset(Offset);
7452 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7453
7454 Offset -= SL->getElementOffset(Elt);
7455 GEPIdxTy = STy->getElementType(Elt);
7456 } else {
7457 // Otherwise, we can't index into this, bail out.
7458 Offset = 0;
7459 OrigBase = 0;
7460 }
7461 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7462 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007463 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007464 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7465 Offset %= EltSize;
7466 } else {
7467 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7468 }
7469 GEPIdxTy = STy->getElementType();
7470 } else {
7471 // Otherwise, we can't index into this, bail out.
7472 Offset = 0;
7473 OrigBase = 0;
7474 }
7475 }
7476 if (OrigBase) {
7477 // If we were able to index down into an element, create the GEP
7478 // and bitcast the result. This eliminates one bitcast, potentially
7479 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007480 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7481 NewIndices.begin(),
7482 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007483 InsertNewInstBefore(NGEP, CI);
7484 NGEP->takeName(GEP);
7485
7486 if (isa<BitCastInst>(CI))
7487 return new BitCastInst(NGEP, CI.getType());
7488 assert(isa<PtrToIntInst>(CI));
7489 return new PtrToIntInst(NGEP, CI.getType());
7490 }
7491 }
7492 }
7493 }
7494 }
7495
7496 return commonCastTransforms(CI);
7497}
7498
7499
7500
7501/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7502/// integer types. This function implements the common transforms for all those
7503/// cases.
7504/// @brief Implement the transforms common to CastInst with integer operands
7505Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7506 if (Instruction *Result = commonCastTransforms(CI))
7507 return Result;
7508
7509 Value *Src = CI.getOperand(0);
7510 const Type *SrcTy = Src->getType();
7511 const Type *DestTy = CI.getType();
7512 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7513 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7514
7515 // See if we can simplify any instructions used by the LHS whose sole
7516 // purpose is to compute bits we don't care about.
7517 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7518 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7519 KnownZero, KnownOne))
7520 return &CI;
7521
7522 // If the source isn't an instruction or has more than one use then we
7523 // can't do anything more.
7524 Instruction *SrcI = dyn_cast<Instruction>(Src);
7525 if (!SrcI || !Src->hasOneUse())
7526 return 0;
7527
7528 // Attempt to propagate the cast into the instruction for int->int casts.
7529 int NumCastsRemoved = 0;
7530 if (!isa<BitCastInst>(CI) &&
7531 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007532 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007533 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007534 // eliminates the cast, so it is always a win. If this is a zero-extension,
7535 // we need to do an AND to maintain the clear top-part of the computation,
7536 // so we require that the input have eliminated at least one cast. If this
7537 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538 // require that two casts have been eliminated.
7539 bool DoXForm;
7540 switch (CI.getOpcode()) {
7541 default:
7542 // All the others use floating point so we shouldn't actually
7543 // get here because of the check above.
7544 assert(0 && "Unknown cast type");
7545 case Instruction::Trunc:
7546 DoXForm = true;
7547 break;
7548 case Instruction::ZExt:
7549 DoXForm = NumCastsRemoved >= 1;
7550 break;
7551 case Instruction::SExt:
7552 DoXForm = NumCastsRemoved >= 2;
7553 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007554 }
7555
7556 if (DoXForm) {
7557 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7558 CI.getOpcode() == Instruction::SExt);
7559 assert(Res->getType() == DestTy);
7560 switch (CI.getOpcode()) {
7561 default: assert(0 && "Unknown cast type!");
7562 case Instruction::Trunc:
7563 case Instruction::BitCast:
7564 // Just replace this cast with the result.
7565 return ReplaceInstUsesWith(CI, Res);
7566 case Instruction::ZExt: {
7567 // We need to emit an AND to clear the high bits.
7568 assert(SrcBitSize < DestBitSize && "Not a zext?");
7569 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7570 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007571 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007572 }
7573 case Instruction::SExt:
7574 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007575 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007576 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7577 CI), DestTy);
7578 }
7579 }
7580 }
7581
7582 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7583 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7584
7585 switch (SrcI->getOpcode()) {
7586 case Instruction::Add:
7587 case Instruction::Mul:
7588 case Instruction::And:
7589 case Instruction::Or:
7590 case Instruction::Xor:
7591 // If we are discarding information, rewrite.
7592 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7593 // Don't insert two casts if they cannot be eliminated. We allow
7594 // two casts to be inserted if the sizes are the same. This could
7595 // only be converting signedness, which is a noop.
7596 if (DestBitSize == SrcBitSize ||
7597 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7598 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7599 Instruction::CastOps opcode = CI.getOpcode();
7600 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7601 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007602 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7604 }
7605 }
7606
7607 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7608 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7609 SrcI->getOpcode() == Instruction::Xor &&
7610 Op1 == ConstantInt::getTrue() &&
7611 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7612 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007613 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007614 }
7615 break;
7616 case Instruction::SDiv:
7617 case Instruction::UDiv:
7618 case Instruction::SRem:
7619 case Instruction::URem:
7620 // If we are just changing the sign, rewrite.
7621 if (DestBitSize == SrcBitSize) {
7622 // Don't insert two casts if they cannot be eliminated. We allow
7623 // two casts to be inserted if the sizes are the same. This could
7624 // only be converting signedness, which is a noop.
7625 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7626 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7627 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7628 Op0, DestTy, SrcI);
7629 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7630 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007631 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007632 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7633 }
7634 }
7635 break;
7636
7637 case Instruction::Shl:
7638 // Allow changing the sign of the source operand. Do not allow
7639 // changing the size of the shift, UNLESS the shift amount is a
7640 // constant. We must not change variable sized shifts to a smaller
7641 // size, because it is undefined to shift more bits out than exist
7642 // in the value.
7643 if (DestBitSize == SrcBitSize ||
7644 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7645 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7646 Instruction::BitCast : Instruction::Trunc);
7647 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7648 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007649 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007650 }
7651 break;
7652 case Instruction::AShr:
7653 // If this is a signed shr, and if all bits shifted in are about to be
7654 // truncated off, turn it into an unsigned shr to allow greater
7655 // simplifications.
7656 if (DestBitSize < SrcBitSize &&
7657 isa<ConstantInt>(Op1)) {
7658 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7659 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7660 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007661 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 }
7663 }
7664 break;
7665 }
7666 return 0;
7667}
7668
7669Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7670 if (Instruction *Result = commonIntCastTransforms(CI))
7671 return Result;
7672
7673 Value *Src = CI.getOperand(0);
7674 const Type *Ty = CI.getType();
7675 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7676 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7677
7678 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7679 switch (SrcI->getOpcode()) {
7680 default: break;
7681 case Instruction::LShr:
7682 // We can shrink lshr to something smaller if we know the bits shifted in
7683 // are already zeros.
7684 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7685 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7686
7687 // Get a mask for the bits shifting in.
7688 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7689 Value* SrcIOp0 = SrcI->getOperand(0);
7690 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7691 if (ShAmt >= DestBitWidth) // All zeros.
7692 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7693
7694 // Okay, we can shrink this. Truncate the input, then return a new
7695 // shift.
7696 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7697 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7698 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007699 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007700 }
7701 } else { // This is a variable shr.
7702
7703 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7704 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7705 // loop-invariant and CSE'd.
7706 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7707 Value *One = ConstantInt::get(SrcI->getType(), 1);
7708
7709 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007710 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007711 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007712 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007713 SrcI->getOperand(0),
7714 "tmp"), CI);
7715 Value *Zero = Constant::getNullValue(V->getType());
7716 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7717 }
7718 }
7719 break;
7720 }
7721 }
7722
7723 return 0;
7724}
7725
Evan Chenge3779cf2008-03-24 00:21:34 +00007726/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7727/// in order to eliminate the icmp.
7728Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7729 bool DoXform) {
7730 // If we are just checking for a icmp eq of a single bit and zext'ing it
7731 // to an integer, then shift the bit to the appropriate place and then
7732 // cast to integer to avoid the comparison.
7733 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7734 const APInt &Op1CV = Op1C->getValue();
7735
7736 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7737 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7738 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7739 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7740 if (!DoXform) return ICI;
7741
7742 Value *In = ICI->getOperand(0);
7743 Value *Sh = ConstantInt::get(In->getType(),
7744 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007745 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007746 In->getName()+".lobit"),
7747 CI);
7748 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007749 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007750 false/*ZExt*/, "tmp", &CI);
7751
7752 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7753 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007754 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007755 In->getName()+".not"),
7756 CI);
7757 }
7758
7759 return ReplaceInstUsesWith(CI, In);
7760 }
7761
7762
7763
7764 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7765 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7766 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7767 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7768 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7769 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7770 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7771 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7772 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7773 // This only works for EQ and NE
7774 ICI->isEquality()) {
7775 // If Op1C some other power of two, convert:
7776 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7777 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7778 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7779 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7780
7781 APInt KnownZeroMask(~KnownZero);
7782 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7783 if (!DoXform) return ICI;
7784
7785 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7786 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7787 // (X&4) == 2 --> false
7788 // (X&4) != 2 --> true
7789 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7790 Res = ConstantExpr::getZExt(Res, CI.getType());
7791 return ReplaceInstUsesWith(CI, Res);
7792 }
7793
7794 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7795 Value *In = ICI->getOperand(0);
7796 if (ShiftAmt) {
7797 // Perform a logical shr by shiftamt.
7798 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007799 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007800 ConstantInt::get(In->getType(), ShiftAmt),
7801 In->getName()+".lobit"), CI);
7802 }
7803
7804 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7805 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007806 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007807 InsertNewInstBefore(cast<Instruction>(In), CI);
7808 }
7809
7810 if (CI.getType() == In->getType())
7811 return ReplaceInstUsesWith(CI, In);
7812 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007813 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007814 }
7815 }
7816 }
7817
7818 return 0;
7819}
7820
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007821Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7822 // If one of the common conversion will work ..
7823 if (Instruction *Result = commonIntCastTransforms(CI))
7824 return Result;
7825
7826 Value *Src = CI.getOperand(0);
7827
7828 // If this is a cast of a cast
7829 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7830 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7831 // types and if the sizes are just right we can convert this into a logical
7832 // 'and' which will be much cheaper than the pair of casts.
7833 if (isa<TruncInst>(CSrc)) {
7834 // Get the sizes of the types involved
7835 Value *A = CSrc->getOperand(0);
7836 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7837 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7838 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7839 // If we're actually extending zero bits and the trunc is a no-op
7840 if (MidSize < DstSize && SrcSize == DstSize) {
7841 // Replace both of the casts with an And of the type mask.
7842 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7843 Constant *AndConst = ConstantInt::get(AndValue);
7844 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007845 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007846 // Unfortunately, if the type changed, we need to cast it back.
7847 if (And->getType() != CI.getType()) {
7848 And->setName(CSrc->getName()+".mask");
7849 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007850 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007851 }
7852 return And;
7853 }
7854 }
7855 }
7856
Evan Chenge3779cf2008-03-24 00:21:34 +00007857 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7858 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007859
Evan Chenge3779cf2008-03-24 00:21:34 +00007860 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7861 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7862 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7863 // of the (zext icmp) will be transformed.
7864 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7865 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7866 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7867 (transformZExtICmp(LHS, CI, false) ||
7868 transformZExtICmp(RHS, CI, false))) {
7869 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7870 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007871 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007872 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007873 }
7874
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007875 return 0;
7876}
7877
7878Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7879 if (Instruction *I = commonIntCastTransforms(CI))
7880 return I;
7881
7882 Value *Src = CI.getOperand(0);
7883
7884 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7885 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7886 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7887 // If we are just checking for a icmp eq of a single bit and zext'ing it
7888 // to an integer, then shift the bit to the appropriate place and then
7889 // cast to integer to avoid the comparison.
7890 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7891 const APInt &Op1CV = Op1C->getValue();
7892
7893 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7894 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7895 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7896 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7897 Value *In = ICI->getOperand(0);
7898 Value *Sh = ConstantInt::get(In->getType(),
7899 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007900 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007901 In->getName()+".lobit"),
7902 CI);
7903 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007904 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007905 true/*SExt*/, "tmp", &CI);
7906
7907 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007908 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007909 In->getName()+".not"), CI);
7910
7911 return ReplaceInstUsesWith(CI, In);
7912 }
7913 }
7914 }
7915
7916 return 0;
7917}
7918
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007919/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7920/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007921static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007922 APFloat F = CFP->getValueAPF();
7923 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007924 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007925 return 0;
7926}
7927
7928/// LookThroughFPExtensions - If this is an fp extension instruction, look
7929/// through it until we get the source value.
7930static Value *LookThroughFPExtensions(Value *V) {
7931 if (Instruction *I = dyn_cast<Instruction>(V))
7932 if (I->getOpcode() == Instruction::FPExt)
7933 return LookThroughFPExtensions(I->getOperand(0));
7934
7935 // If this value is a constant, return the constant in the smallest FP type
7936 // that can accurately represent it. This allows us to turn
7937 // (float)((double)X+2.0) into x+2.0f.
7938 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7939 if (CFP->getType() == Type::PPC_FP128Ty)
7940 return V; // No constant folding of this.
7941 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007942 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007943 return V;
7944 if (CFP->getType() == Type::DoubleTy)
7945 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007946 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007947 return V;
7948 // Don't try to shrink to various long double types.
7949 }
7950
7951 return V;
7952}
7953
7954Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7955 if (Instruction *I = commonCastTransforms(CI))
7956 return I;
7957
7958 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7959 // smaller than the destination type, we can eliminate the truncate by doing
7960 // the add as the smaller type. This applies to add/sub/mul/div as well as
7961 // many builtins (sqrt, etc).
7962 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7963 if (OpI && OpI->hasOneUse()) {
7964 switch (OpI->getOpcode()) {
7965 default: break;
7966 case Instruction::Add:
7967 case Instruction::Sub:
7968 case Instruction::Mul:
7969 case Instruction::FDiv:
7970 case Instruction::FRem:
7971 const Type *SrcTy = OpI->getType();
7972 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7973 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7974 if (LHSTrunc->getType() != SrcTy &&
7975 RHSTrunc->getType() != SrcTy) {
7976 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7977 // If the source types were both smaller than the destination type of
7978 // the cast, do this xform.
7979 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7980 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7981 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7982 CI.getType(), CI);
7983 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7984 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007985 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007986 }
7987 }
7988 break;
7989 }
7990 }
7991 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992}
7993
7994Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7995 return commonCastTransforms(CI);
7996}
7997
7998Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7999 return commonCastTransforms(CI);
8000}
8001
8002Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
8003 return commonCastTransforms(CI);
8004}
8005
8006Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8007 return commonCastTransforms(CI);
8008}
8009
8010Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8011 return commonCastTransforms(CI);
8012}
8013
8014Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8015 return commonPointerCastTransforms(CI);
8016}
8017
Chris Lattner7c1626482008-01-08 07:23:51 +00008018Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8019 if (Instruction *I = commonCastTransforms(CI))
8020 return I;
8021
8022 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8023 if (!DestPointee->isSized()) return 0;
8024
8025 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8026 ConstantInt *Cst;
8027 Value *X;
8028 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8029 m_ConstantInt(Cst)))) {
8030 // If the source and destination operands have the same type, see if this
8031 // is a single-index GEP.
8032 if (X->getType() == CI.getType()) {
8033 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00008034 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008035
8036 // Convert the constant to intptr type.
8037 APInt Offset = Cst->getValue();
8038 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8039
8040 // If Offset is evenly divisible by Size, we can do this xform.
8041 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8042 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008043 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008044 }
8045 }
8046 // TODO: Could handle other cases, e.g. where add is indexing into field of
8047 // struct etc.
8048 } else if (CI.getOperand(0)->hasOneUse() &&
8049 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8050 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8051 // "inttoptr+GEP" instead of "add+intptr".
8052
8053 // Get the size of the pointee type.
8054 uint64_t Size = TD->getABITypeSize(DestPointee);
8055
8056 // Convert the constant to intptr type.
8057 APInt Offset = Cst->getValue();
8058 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8059
8060 // If Offset is evenly divisible by Size, we can do this xform.
8061 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8062 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8063
8064 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8065 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008066 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008067 }
8068 }
8069 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008070}
8071
8072Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8073 // If the operands are integer typed then apply the integer transforms,
8074 // otherwise just apply the common ones.
8075 Value *Src = CI.getOperand(0);
8076 const Type *SrcTy = Src->getType();
8077 const Type *DestTy = CI.getType();
8078
8079 if (SrcTy->isInteger() && DestTy->isInteger()) {
8080 if (Instruction *Result = commonIntCastTransforms(CI))
8081 return Result;
8082 } else if (isa<PointerType>(SrcTy)) {
8083 if (Instruction *I = commonPointerCastTransforms(CI))
8084 return I;
8085 } else {
8086 if (Instruction *Result = commonCastTransforms(CI))
8087 return Result;
8088 }
8089
8090
8091 // Get rid of casts from one type to the same type. These are useless and can
8092 // be replaced by the operand.
8093 if (DestTy == Src->getType())
8094 return ReplaceInstUsesWith(CI, Src);
8095
8096 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8097 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8098 const Type *DstElTy = DstPTy->getElementType();
8099 const Type *SrcElTy = SrcPTy->getElementType();
8100
Nate Begemandf5b3612008-03-31 00:22:16 +00008101 // If the address spaces don't match, don't eliminate the bitcast, which is
8102 // required for changing types.
8103 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8104 return 0;
8105
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008106 // If we are casting a malloc or alloca to a pointer to a type of the same
8107 // size, rewrite the allocation instruction to allocate the "right" type.
8108 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8109 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8110 return V;
8111
8112 // If the source and destination are pointers, and this cast is equivalent
8113 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8114 // This can enhance SROA and other transforms that want type-safe pointers.
8115 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8116 unsigned NumZeros = 0;
8117 while (SrcElTy != DstElTy &&
8118 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8119 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8120 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8121 ++NumZeros;
8122 }
8123
8124 // If we found a path from the src to dest, create the getelementptr now.
8125 if (SrcElTy == DstElTy) {
8126 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008127 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8128 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 }
8130 }
8131
8132 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8133 if (SVI->hasOneUse()) {
8134 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8135 // a bitconvert to a vector with the same # elts.
8136 if (isa<VectorType>(DestTy) &&
8137 cast<VectorType>(DestTy)->getNumElements() ==
8138 SVI->getType()->getNumElements()) {
8139 CastInst *Tmp;
8140 // If either of the operands is a cast from CI.getType(), then
8141 // evaluating the shuffle in the casted destination's type will allow
8142 // us to eliminate at least one cast.
8143 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8144 Tmp->getOperand(0)->getType() == DestTy) ||
8145 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8146 Tmp->getOperand(0)->getType() == DestTy)) {
8147 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8148 SVI->getOperand(0), DestTy, &CI);
8149 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8150 SVI->getOperand(1), DestTy, &CI);
8151 // Return a new shuffle vector. Use the same element ID's, as we
8152 // know the vector types match #elts.
8153 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8154 }
8155 }
8156 }
8157 }
8158 return 0;
8159}
8160
8161/// GetSelectFoldableOperands - We want to turn code that looks like this:
8162/// %C = or %A, %B
8163/// %D = select %cond, %C, %A
8164/// into:
8165/// %C = select %cond, %B, 0
8166/// %D = or %A, %C
8167///
8168/// Assuming that the specified instruction is an operand to the select, return
8169/// a bitmask indicating which operands of this instruction are foldable if they
8170/// equal the other incoming value of the select.
8171///
8172static unsigned GetSelectFoldableOperands(Instruction *I) {
8173 switch (I->getOpcode()) {
8174 case Instruction::Add:
8175 case Instruction::Mul:
8176 case Instruction::And:
8177 case Instruction::Or:
8178 case Instruction::Xor:
8179 return 3; // Can fold through either operand.
8180 case Instruction::Sub: // Can only fold on the amount subtracted.
8181 case Instruction::Shl: // Can only fold on the shift amount.
8182 case Instruction::LShr:
8183 case Instruction::AShr:
8184 return 1;
8185 default:
8186 return 0; // Cannot fold
8187 }
8188}
8189
8190/// GetSelectFoldableConstant - For the same transformation as the previous
8191/// function, return the identity constant that goes into the select.
8192static Constant *GetSelectFoldableConstant(Instruction *I) {
8193 switch (I->getOpcode()) {
8194 default: assert(0 && "This cannot happen!"); abort();
8195 case Instruction::Add:
8196 case Instruction::Sub:
8197 case Instruction::Or:
8198 case Instruction::Xor:
8199 case Instruction::Shl:
8200 case Instruction::LShr:
8201 case Instruction::AShr:
8202 return Constant::getNullValue(I->getType());
8203 case Instruction::And:
8204 return Constant::getAllOnesValue(I->getType());
8205 case Instruction::Mul:
8206 return ConstantInt::get(I->getType(), 1);
8207 }
8208}
8209
8210/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8211/// have the same opcode and only one use each. Try to simplify this.
8212Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8213 Instruction *FI) {
8214 if (TI->getNumOperands() == 1) {
8215 // If this is a non-volatile load or a cast from the same type,
8216 // merge.
8217 if (TI->isCast()) {
8218 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8219 return 0;
8220 } else {
8221 return 0; // unknown unary op.
8222 }
8223
8224 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008225 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8226 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008227 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008228 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008229 TI->getType());
8230 }
8231
8232 // Only handle binary operators here.
8233 if (!isa<BinaryOperator>(TI))
8234 return 0;
8235
8236 // Figure out if the operations have any operands in common.
8237 Value *MatchOp, *OtherOpT, *OtherOpF;
8238 bool MatchIsOpZero;
8239 if (TI->getOperand(0) == FI->getOperand(0)) {
8240 MatchOp = TI->getOperand(0);
8241 OtherOpT = TI->getOperand(1);
8242 OtherOpF = FI->getOperand(1);
8243 MatchIsOpZero = true;
8244 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8245 MatchOp = TI->getOperand(1);
8246 OtherOpT = TI->getOperand(0);
8247 OtherOpF = FI->getOperand(0);
8248 MatchIsOpZero = false;
8249 } else if (!TI->isCommutative()) {
8250 return 0;
8251 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8252 MatchOp = TI->getOperand(0);
8253 OtherOpT = TI->getOperand(1);
8254 OtherOpF = FI->getOperand(0);
8255 MatchIsOpZero = true;
8256 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8257 MatchOp = TI->getOperand(1);
8258 OtherOpT = TI->getOperand(0);
8259 OtherOpF = FI->getOperand(1);
8260 MatchIsOpZero = true;
8261 } else {
8262 return 0;
8263 }
8264
8265 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008266 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8267 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008268 InsertNewInstBefore(NewSI, SI);
8269
8270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8271 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008272 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008273 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008274 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008275 }
8276 assert(0 && "Shouldn't get here");
8277 return 0;
8278}
8279
8280Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8281 Value *CondVal = SI.getCondition();
8282 Value *TrueVal = SI.getTrueValue();
8283 Value *FalseVal = SI.getFalseValue();
8284
8285 // select true, X, Y -> X
8286 // select false, X, Y -> Y
8287 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8288 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8289
8290 // select C, X, X -> X
8291 if (TrueVal == FalseVal)
8292 return ReplaceInstUsesWith(SI, TrueVal);
8293
8294 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8295 return ReplaceInstUsesWith(SI, FalseVal);
8296 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8297 return ReplaceInstUsesWith(SI, TrueVal);
8298 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8299 if (isa<Constant>(TrueVal))
8300 return ReplaceInstUsesWith(SI, TrueVal);
8301 else
8302 return ReplaceInstUsesWith(SI, FalseVal);
8303 }
8304
8305 if (SI.getType() == Type::Int1Ty) {
8306 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8307 if (C->getZExtValue()) {
8308 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008309 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008310 } else {
8311 // Change: A = select B, false, C --> A = and !B, C
8312 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008313 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008314 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008315 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008316 }
8317 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8318 if (C->getZExtValue() == false) {
8319 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008320 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008321 } else {
8322 // Change: A = select B, C, true --> A = or !B, C
8323 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008326 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327 }
8328 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008329
8330 // select a, b, a -> a&b
8331 // select a, a, b -> a|b
8332 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008333 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008334 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008335 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008336 }
8337
8338 // Selecting between two integer constants?
8339 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8340 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8341 // select C, 1, 0 -> zext C to int
8342 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008343 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008344 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8345 // select C, 0, 1 -> zext !C to int
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 CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 }
8351
8352 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8353
8354 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8355
8356 // (x <s 0) ? -1 : 0 -> ashr x, 31
8357 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8358 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8359 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8360 // The comparison constant and the result are not neccessarily the
8361 // same width. Make an all-ones value by inserting a AShr.
8362 Value *X = IC->getOperand(0);
8363 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8364 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008365 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366 ShAmt, "ones");
8367 InsertNewInstBefore(SRA, SI);
8368
8369 // Finally, convert to the type of the select RHS. We figure out
8370 // if this requires a SExt, Trunc or BitCast based on the sizes.
8371 Instruction::CastOps opc = Instruction::BitCast;
8372 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8373 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8374 if (SRASize < SISize)
8375 opc = Instruction::SExt;
8376 else if (SRASize > SISize)
8377 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008378 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008379 }
8380 }
8381
8382
8383 // If one of the constants is zero (we know they can't both be) and we
8384 // have an icmp instruction with zero, and we have an 'and' with the
8385 // non-constant value, eliminate this whole mess. This corresponds to
8386 // cases like this: ((X & 27) ? 27 : 0)
8387 if (TrueValC->isZero() || FalseValC->isZero())
8388 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8389 cast<Constant>(IC->getOperand(1))->isNullValue())
8390 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8391 if (ICA->getOpcode() == Instruction::And &&
8392 isa<ConstantInt>(ICA->getOperand(1)) &&
8393 (ICA->getOperand(1) == TrueValC ||
8394 ICA->getOperand(1) == FalseValC) &&
8395 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8396 // Okay, now we know that everything is set up, we just don't
8397 // know whether we have a icmp_ne or icmp_eq and whether the
8398 // true or false val is the zero.
8399 bool ShouldNotVal = !TrueValC->isZero();
8400 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8401 Value *V = ICA;
8402 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008403 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008404 Instruction::Xor, V, ICA->getOperand(1)), SI);
8405 return ReplaceInstUsesWith(SI, V);
8406 }
8407 }
8408 }
8409
8410 // See if we are selecting two values based on a comparison of the two values.
8411 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8412 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8413 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008414 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8415 // This is not safe in general for floating point:
8416 // consider X== -0, Y== +0.
8417 // It becomes safe if either operand is a nonzero constant.
8418 ConstantFP *CFPt, *CFPf;
8419 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8420 !CFPt->getValueAPF().isZero()) ||
8421 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8422 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008423 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008424 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008425 // Transform (X != Y) ? X : Y -> X
8426 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8427 return ReplaceInstUsesWith(SI, TrueVal);
8428 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8429
8430 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8431 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008432 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8433 // This is not safe in general for floating point:
8434 // consider X== -0, Y== +0.
8435 // It becomes safe if either operand is a nonzero constant.
8436 ConstantFP *CFPt, *CFPf;
8437 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8438 !CFPt->getValueAPF().isZero()) ||
8439 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8440 !CFPf->getValueAPF().isZero()))
8441 return ReplaceInstUsesWith(SI, FalseVal);
8442 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008443 // Transform (X != Y) ? Y : X -> Y
8444 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8445 return ReplaceInstUsesWith(SI, TrueVal);
8446 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8447 }
8448 }
8449
8450 // See if we are selecting two values based on a comparison of the two values.
8451 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8452 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8453 // Transform (X == Y) ? X : Y -> Y
8454 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8455 return ReplaceInstUsesWith(SI, FalseVal);
8456 // Transform (X != Y) ? X : Y -> X
8457 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8458 return ReplaceInstUsesWith(SI, TrueVal);
8459 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8460
8461 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8462 // Transform (X == Y) ? Y : X -> X
8463 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8464 return ReplaceInstUsesWith(SI, FalseVal);
8465 // Transform (X != Y) ? Y : X -> Y
8466 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8467 return ReplaceInstUsesWith(SI, TrueVal);
8468 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8469 }
8470 }
8471
8472 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8473 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8474 if (TI->hasOneUse() && FI->hasOneUse()) {
8475 Instruction *AddOp = 0, *SubOp = 0;
8476
8477 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8478 if (TI->getOpcode() == FI->getOpcode())
8479 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8480 return IV;
8481
8482 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8483 // even legal for FP.
8484 if (TI->getOpcode() == Instruction::Sub &&
8485 FI->getOpcode() == Instruction::Add) {
8486 AddOp = FI; SubOp = TI;
8487 } else if (FI->getOpcode() == Instruction::Sub &&
8488 TI->getOpcode() == Instruction::Add) {
8489 AddOp = TI; SubOp = FI;
8490 }
8491
8492 if (AddOp) {
8493 Value *OtherAddOp = 0;
8494 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8495 OtherAddOp = AddOp->getOperand(1);
8496 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8497 OtherAddOp = AddOp->getOperand(0);
8498 }
8499
8500 if (OtherAddOp) {
8501 // So at this point we know we have (Y -> OtherAddOp):
8502 // select C, (add X, Y), (sub X, Z)
8503 Value *NegVal; // Compute -Z
8504 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8505 NegVal = ConstantExpr::getNeg(C);
8506 } else {
8507 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008508 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008509 }
8510
8511 Value *NewTrueOp = OtherAddOp;
8512 Value *NewFalseOp = NegVal;
8513 if (AddOp != TI)
8514 std::swap(NewTrueOp, NewFalseOp);
8515 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008516 SelectInst::Create(CondVal, NewTrueOp,
8517 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008518
8519 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008520 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008521 }
8522 }
8523 }
8524
8525 // See if we can fold the select into one of our operands.
8526 if (SI.getType()->isInteger()) {
8527 // See the comment above GetSelectFoldableOperands for a description of the
8528 // transformation we are doing here.
8529 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8530 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8531 !isa<Constant>(FalseVal))
8532 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8533 unsigned OpToFold = 0;
8534 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8535 OpToFold = 1;
8536 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8537 OpToFold = 2;
8538 }
8539
8540 if (OpToFold) {
8541 Constant *C = GetSelectFoldableConstant(TVI);
8542 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008543 SelectInst::Create(SI.getCondition(),
8544 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008545 InsertNewInstBefore(NewSel, SI);
8546 NewSel->takeName(TVI);
8547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008548 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008549 else {
8550 assert(0 && "Unknown instruction!!");
8551 }
8552 }
8553 }
8554
8555 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8556 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8557 !isa<Constant>(TrueVal))
8558 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8559 unsigned OpToFold = 0;
8560 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8561 OpToFold = 1;
8562 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8563 OpToFold = 2;
8564 }
8565
8566 if (OpToFold) {
8567 Constant *C = GetSelectFoldableConstant(FVI);
8568 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008569 SelectInst::Create(SI.getCondition(), C,
8570 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008571 InsertNewInstBefore(NewSel, SI);
8572 NewSel->takeName(FVI);
8573 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008574 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008575 else
8576 assert(0 && "Unknown instruction!!");
8577 }
8578 }
8579 }
8580
8581 if (BinaryOperator::isNot(CondVal)) {
8582 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8583 SI.setOperand(1, FalseVal);
8584 SI.setOperand(2, TrueVal);
8585 return &SI;
8586 }
8587
8588 return 0;
8589}
8590
Dan Gohman2d648bb2008-04-10 18:43:06 +00008591/// EnforceKnownAlignment - If the specified pointer points to an object that
8592/// we control, modify the object's alignment to PrefAlign. This isn't
8593/// often possible though. If alignment is important, a more reliable approach
8594/// is to simply align all global variables and allocation instructions to
8595/// their preferred alignment from the beginning.
8596///
8597static unsigned EnforceKnownAlignment(Value *V,
8598 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008599
Dan Gohman2d648bb2008-04-10 18:43:06 +00008600 User *U = dyn_cast<User>(V);
8601 if (!U) return Align;
8602
8603 switch (getOpcode(U)) {
8604 default: break;
8605 case Instruction::BitCast:
8606 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8607 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008608 // If all indexes are zero, it is just the alignment of the base pointer.
8609 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008610 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8611 if (!isa<Constant>(U->getOperand(i)) ||
8612 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008613 AllZeroOperands = false;
8614 break;
8615 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008616
8617 if (AllZeroOperands) {
8618 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008619 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008620 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008621 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008622 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008623 }
8624
8625 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8626 // If there is a large requested alignment and we can, bump up the alignment
8627 // of the global.
8628 if (!GV->isDeclaration()) {
8629 GV->setAlignment(PrefAlign);
8630 Align = PrefAlign;
8631 }
8632 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8633 // If there is a requested alignment and if this is an alloca, round up. We
8634 // don't do this for malloc, because some systems can't respect the request.
8635 if (isa<AllocaInst>(AI)) {
8636 AI->setAlignment(PrefAlign);
8637 Align = PrefAlign;
8638 }
8639 }
8640
8641 return Align;
8642}
8643
8644/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8645/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8646/// and it is more than the alignment of the ultimate object, see if we can
8647/// increase the alignment of the ultimate object, making this check succeed.
8648unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8649 unsigned PrefAlign) {
8650 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8651 sizeof(PrefAlign) * CHAR_BIT;
8652 APInt Mask = APInt::getAllOnesValue(BitWidth);
8653 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8654 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8655 unsigned TrailZ = KnownZero.countTrailingOnes();
8656 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8657
8658 if (PrefAlign > Align)
8659 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8660
8661 // We don't need to make any adjustment.
8662 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008663}
8664
Chris Lattner00ae5132008-01-13 23:50:23 +00008665Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008666 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8667 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008668 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8669 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8670
8671 if (CopyAlign < MinAlign) {
8672 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8673 return MI;
8674 }
8675
8676 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8677 // load/store.
8678 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8679 if (MemOpLength == 0) return 0;
8680
Chris Lattnerc669fb62008-01-14 00:28:35 +00008681 // Source and destination pointer types are always "i8*" for intrinsic. See
8682 // if the size is something we can handle with a single primitive load/store.
8683 // A single load+store correctly handles overlapping memory in the memmove
8684 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008685 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008686 if (Size == 0) return MI; // Delete this mem transfer.
8687
8688 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008689 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008690
Chris Lattnerc669fb62008-01-14 00:28:35 +00008691 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008692 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008693
8694 // Memcpy forces the use of i8* for the source and destination. That means
8695 // that if you're using memcpy to move one double around, you'll get a cast
8696 // from double* to i8*. We'd much rather use a double load+store rather than
8697 // an i64 load+store, here because this improves the odds that the source or
8698 // dest address will be promotable. See if we can find a better type than the
8699 // integer datatype.
8700 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8701 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8702 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8703 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8704 // down through these levels if so.
8705 while (!SrcETy->isFirstClassType()) {
8706 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8707 if (STy->getNumElements() == 1)
8708 SrcETy = STy->getElementType(0);
8709 else
8710 break;
8711 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8712 if (ATy->getNumElements() == 1)
8713 SrcETy = ATy->getElementType();
8714 else
8715 break;
8716 } else
8717 break;
8718 }
8719
8720 if (SrcETy->isFirstClassType())
8721 NewPtrTy = PointerType::getUnqual(SrcETy);
8722 }
8723 }
8724
8725
Chris Lattner00ae5132008-01-13 23:50:23 +00008726 // If the memcpy/memmove provides better alignment info than we can
8727 // infer, use it.
8728 SrcAlign = std::max(SrcAlign, CopyAlign);
8729 DstAlign = std::max(DstAlign, CopyAlign);
8730
8731 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8732 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008733 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8734 InsertNewInstBefore(L, *MI);
8735 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8736
8737 // Set the size of the copy to 0, it will be deleted on the next iteration.
8738 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8739 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008740}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008741
Chris Lattner5af8a912008-04-30 06:39:11 +00008742Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8743 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8744 if (MI->getAlignment()->getZExtValue() < Alignment) {
8745 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8746 return MI;
8747 }
8748
8749 // Extract the length and alignment and fill if they are constant.
8750 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8751 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8752 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8753 return 0;
8754 uint64_t Len = LenC->getZExtValue();
8755 Alignment = MI->getAlignment()->getZExtValue();
8756
8757 // If the length is zero, this is a no-op
8758 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8759
8760 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8761 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8762 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8763
8764 Value *Dest = MI->getDest();
8765 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8766
8767 // Alignment 0 is identity for alignment 1 for memset, but not store.
8768 if (Alignment == 0) Alignment = 1;
8769
8770 // Extract the fill value and store.
8771 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8772 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8773 Alignment), *MI);
8774
8775 // Set the size of the copy to 0, it will be deleted on the next iteration.
8776 MI->setLength(Constant::getNullValue(LenC->getType()));
8777 return MI;
8778 }
8779
8780 return 0;
8781}
8782
8783
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008784/// visitCallInst - CallInst simplification. This mostly only handles folding
8785/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8786/// the heavy lifting.
8787///
8788Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8789 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8790 if (!II) return visitCallSite(&CI);
8791
8792 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8793 // visitCallSite.
8794 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8795 bool Changed = false;
8796
8797 // memmove/cpy/set of zero bytes is a noop.
8798 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8799 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8800
8801 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8802 if (CI->getZExtValue() == 1) {
8803 // Replace the instruction with just byte operations. We would
8804 // transform other cases to loads/stores, but we don't know if
8805 // alignment is sufficient.
8806 }
8807 }
8808
8809 // If we have a memmove and the source operation is a constant global,
8810 // then the source and dest pointers can't alias, so we can change this
8811 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008812 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008813 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8814 if (GVSrc->isConstant()) {
8815 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008816 Intrinsic::ID MemCpyID;
8817 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8818 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008819 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008820 MemCpyID = Intrinsic::memcpy_i64;
8821 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008822 Changed = true;
8823 }
8824 }
8825
8826 // If we can determine a pointer alignment that is bigger than currently
8827 // set, update the alignment.
8828 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008829 if (Instruction *I = SimplifyMemTransfer(MI))
8830 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008831 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8832 if (Instruction *I = SimplifyMemSet(MSI))
8833 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008834 }
8835
8836 if (Changed) return II;
8837 } else {
8838 switch (II->getIntrinsicID()) {
8839 default: break;
8840 case Intrinsic::ppc_altivec_lvx:
8841 case Intrinsic::ppc_altivec_lvxl:
8842 case Intrinsic::x86_sse_loadu_ps:
8843 case Intrinsic::x86_sse2_loadu_pd:
8844 case Intrinsic::x86_sse2_loadu_dq:
8845 // Turn PPC lvx -> load if the pointer is known aligned.
8846 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008847 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008848 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8849 PointerType::getUnqual(II->getType()),
8850 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008851 return new LoadInst(Ptr);
8852 }
8853 break;
8854 case Intrinsic::ppc_altivec_stvx:
8855 case Intrinsic::ppc_altivec_stvxl:
8856 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008857 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008858 const Type *OpPtrTy =
8859 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008860 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008861 return new StoreInst(II->getOperand(1), Ptr);
8862 }
8863 break;
8864 case Intrinsic::x86_sse_storeu_ps:
8865 case Intrinsic::x86_sse2_storeu_pd:
8866 case Intrinsic::x86_sse2_storeu_dq:
8867 case Intrinsic::x86_sse2_storel_dq:
8868 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008869 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008870 const Type *OpPtrTy =
8871 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008872 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008873 return new StoreInst(II->getOperand(2), Ptr);
8874 }
8875 break;
8876
8877 case Intrinsic::x86_sse_cvttss2si: {
8878 // These intrinsics only demands the 0th element of its input vector. If
8879 // we can simplify the input based on that, do so now.
8880 uint64_t UndefElts;
8881 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8882 UndefElts)) {
8883 II->setOperand(1, V);
8884 return II;
8885 }
8886 break;
8887 }
8888
8889 case Intrinsic::ppc_altivec_vperm:
8890 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8891 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8892 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8893
8894 // Check that all of the elements are integer constants or undefs.
8895 bool AllEltsOk = true;
8896 for (unsigned i = 0; i != 16; ++i) {
8897 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8898 !isa<UndefValue>(Mask->getOperand(i))) {
8899 AllEltsOk = false;
8900 break;
8901 }
8902 }
8903
8904 if (AllEltsOk) {
8905 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008906 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8907 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008908 Value *Result = UndefValue::get(Op0->getType());
8909
8910 // Only extract each element once.
8911 Value *ExtractedElts[32];
8912 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8913
8914 for (unsigned i = 0; i != 16; ++i) {
8915 if (isa<UndefValue>(Mask->getOperand(i)))
8916 continue;
8917 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8918 Idx &= 31; // Match the hardware behavior.
8919
8920 if (ExtractedElts[Idx] == 0) {
8921 Instruction *Elt =
8922 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8923 InsertNewInstBefore(Elt, CI);
8924 ExtractedElts[Idx] = Elt;
8925 }
8926
8927 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008928 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8929 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008930 InsertNewInstBefore(cast<Instruction>(Result), CI);
8931 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008932 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008933 }
8934 }
8935 break;
8936
8937 case Intrinsic::stackrestore: {
8938 // If the save is right next to the restore, remove the restore. This can
8939 // happen when variable allocas are DCE'd.
8940 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8941 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8942 BasicBlock::iterator BI = SS;
8943 if (&*++BI == II)
8944 return EraseInstFromFunction(CI);
8945 }
8946 }
8947
Chris Lattner416d91c2008-02-18 06:12:38 +00008948 // Scan down this block to see if there is another stack restore in the
8949 // same block without an intervening call/alloca.
8950 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008951 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008952 bool CannotRemove = false;
8953 for (++BI; &*BI != TI; ++BI) {
8954 if (isa<AllocaInst>(BI)) {
8955 CannotRemove = true;
8956 break;
8957 }
8958 if (isa<CallInst>(BI)) {
8959 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008960 CannotRemove = true;
8961 break;
8962 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008963 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008964 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008965 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008966 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008967
8968 // If the stack restore is in a return/unwind block and if there are no
8969 // allocas or calls between the restore and the return, nuke the restore.
8970 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8971 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008972 break;
8973 }
8974 }
8975 }
8976
8977 return visitCallSite(II);
8978}
8979
8980// InvokeInst simplification
8981//
8982Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8983 return visitCallSite(&II);
8984}
8985
Dale Johannesen96021832008-04-25 21:16:07 +00008986/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8987/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008988static bool isSafeToEliminateVarargsCast(const CallSite CS,
8989 const CastInst * const CI,
8990 const TargetData * const TD,
8991 const int ix) {
8992 if (!CI->isLosslessCast())
8993 return false;
8994
8995 // The size of ByVal arguments is derived from the type, so we
8996 // can't change to a type with a different size. If the size were
8997 // passed explicitly we could avoid this check.
8998 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8999 return true;
9000
9001 const Type* SrcTy =
9002 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9003 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9004 if (!SrcTy->isSized() || !DstTy->isSized())
9005 return false;
9006 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9007 return false;
9008 return true;
9009}
9010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009011// visitCallSite - Improvements for call and invoke instructions.
9012//
9013Instruction *InstCombiner::visitCallSite(CallSite CS) {
9014 bool Changed = false;
9015
9016 // If the callee is a constexpr cast of a function, attempt to move the cast
9017 // to the arguments of the call/invoke.
9018 if (transformConstExprCastCall(CS)) return 0;
9019
9020 Value *Callee = CS.getCalledValue();
9021
9022 if (Function *CalleeF = dyn_cast<Function>(Callee))
9023 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9024 Instruction *OldCall = CS.getInstruction();
9025 // If the call and callee calling conventions don't match, this call must
9026 // be unreachable, as the call is undefined.
9027 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009028 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9029 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009030 if (!OldCall->use_empty())
9031 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9032 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9033 return EraseInstFromFunction(*OldCall);
9034 return 0;
9035 }
9036
9037 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9038 // This instruction is not reachable, just remove it. We insert a store to
9039 // undef so that we know that this code is not reachable, despite the fact
9040 // that we can't modify the CFG here.
9041 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009042 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009043 CS.getInstruction());
9044
9045 if (!CS.getInstruction()->use_empty())
9046 CS.getInstruction()->
9047 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9048
9049 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9050 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009051 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9052 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009053 }
9054 return EraseInstFromFunction(*CS.getInstruction());
9055 }
9056
Duncan Sands74833f22007-09-17 10:26:40 +00009057 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9058 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9059 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9060 return transformCallThroughTrampoline(CS);
9061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009062 const PointerType *PTy = cast<PointerType>(Callee->getType());
9063 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9064 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009065 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009066 // See if we can optimize any arguments passed through the varargs area of
9067 // the call.
9068 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009069 E = CS.arg_end(); I != E; ++I, ++ix) {
9070 CastInst *CI = dyn_cast<CastInst>(*I);
9071 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9072 *I = CI->getOperand(0);
9073 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009074 }
Dale Johannesen35615462008-04-23 18:34:37 +00009075 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 }
9077
Duncan Sands2937e352007-12-19 21:13:37 +00009078 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009079 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009080 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009081 Changed = true;
9082 }
9083
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009084 return Changed ? CS.getInstruction() : 0;
9085}
9086
9087// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9088// attempt to move the cast to the arguments of the call/invoke.
9089//
9090bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9091 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9092 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9093 if (CE->getOpcode() != Instruction::BitCast ||
9094 !isa<Function>(CE->getOperand(0)))
9095 return false;
9096 Function *Callee = cast<Function>(CE->getOperand(0));
9097 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009098 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009099
9100 // Okay, this is a cast from a function to a different type. Unless doing so
9101 // would cause a type conversion of one of our arguments, change this call to
9102 // be a direct call with arguments casted to the appropriate types.
9103 //
9104 const FunctionType *FT = Callee->getFunctionType();
9105 const Type *OldRetTy = Caller->getType();
9106
Devang Pateld091d322008-03-11 18:04:06 +00009107 if (isa<StructType>(FT->getReturnType()))
9108 return false; // TODO: Handle multiple return values.
9109
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009110 // Check to see if we are changing the return type...
9111 if (OldRetTy != FT->getReturnType()) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009112 if (Callee->isDeclaration() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009113 // Conversion is ok if changing from pointer to int of same size.
9114 !(isa<PointerType>(FT->getReturnType()) &&
9115 TD->getIntPtrType() == OldRetTy))
9116 return false; // Cannot transform this return value.
9117
Duncan Sands5c489582008-01-06 10:12:28 +00009118 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009119 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00009120 FT->getReturnType() != Type::VoidTy &&
9121 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009122 return false; // Cannot transform this return value.
9123
Chris Lattner1c8733e2008-03-12 17:45:29 +00009124 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9125 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009126 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9127 return false; // Attribute not compatible with transformed value.
9128 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009130 // If the callsite is an invoke instruction, and the return value is used by
9131 // a PHI node in a successor, we cannot change the return type of the call
9132 // because there is no place to put the cast instruction (without breaking
9133 // the critical edge). Bail out in this case.
9134 if (!Caller->use_empty())
9135 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9136 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9137 UI != E; ++UI)
9138 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9139 if (PN->getParent() == II->getNormalDest() ||
9140 PN->getParent() == II->getUnwindDest())
9141 return false;
9142 }
9143
9144 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9145 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9146
9147 CallSite::arg_iterator AI = CS.arg_begin();
9148 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9149 const Type *ParamTy = FT->getParamType(i);
9150 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009151
9152 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009153 return false; // Cannot transform this parameter value.
9154
Chris Lattner1c8733e2008-03-12 17:45:29 +00009155 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9156 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00009159 // Some conversions are safe even if we do not have a body.
9160 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009161 bool isConvertible = ActTy == ParamTy ||
9162 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9163 (ParamTy->isInteger() && ActTy->isInteger() &&
9164 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9165 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9166 && c->getValue().isStrictlyPositive());
9167 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009168 }
9169
9170 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9171 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009172 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009173
Chris Lattner1c8733e2008-03-12 17:45:29 +00009174 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9175 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009176 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009177 // won't be dropping them. Check that these extra arguments have attributes
9178 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009179 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9180 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009181 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009182 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009183 if (PAttrs & ParamAttr::VarArgsIncompatible)
9184 return false;
9185 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009186
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009187 // Okay, we decided that this is a safe thing to do: go ahead and start
9188 // inserting cast instructions as necessary...
9189 std::vector<Value*> Args;
9190 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009191 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009192 attrVec.reserve(NumCommonArgs);
9193
9194 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009195 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009196
9197 // If the return value is not being used, the type may not be compatible
9198 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009199 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00009200
9201 // Add the new return attributes.
9202 if (RAttrs)
9203 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009204
9205 AI = CS.arg_begin();
9206 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9207 const Type *ParamTy = FT->getParamType(i);
9208 if ((*AI)->getType() == ParamTy) {
9209 Args.push_back(*AI);
9210 } else {
9211 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9212 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009213 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009214 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9215 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009216
9217 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009218 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009219 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009220 }
9221
9222 // If the function takes more arguments than the call was taking, add them
9223 // now...
9224 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9225 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9226
9227 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009228 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009229 if (!FT->isVarArg()) {
9230 cerr << "WARNING: While resolving call to function '"
9231 << Callee->getName() << "' arguments were dropped!\n";
9232 } else {
9233 // Add all of the arguments in their promoted form to the arg list...
9234 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9235 const Type *PTy = getPromotedType((*AI)->getType());
9236 if (PTy != (*AI)->getType()) {
9237 // Must promote to pass through va_arg area!
9238 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9239 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009240 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009241 InsertNewInstBefore(Cast, *Caller);
9242 Args.push_back(Cast);
9243 } else {
9244 Args.push_back(*AI);
9245 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009246
Duncan Sands4ced1f82008-01-13 08:02:44 +00009247 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009248 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009249 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9250 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009251 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009252 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009253
9254 if (FT->getReturnType() == Type::VoidTy)
9255 Caller->setName(""); // Void type should not have a name.
9256
Chris Lattner1c8733e2008-03-12 17:45:29 +00009257 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009258
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009259 Instruction *NC;
9260 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009261 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009262 Args.begin(), Args.end(),
9263 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009264 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009265 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009266 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009267 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9268 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009269 CallInst *CI = cast<CallInst>(Caller);
9270 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009271 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009272 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009273 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009274 }
9275
9276 // Insert a cast of the return type as necessary.
9277 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009278 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009279 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009280 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009281 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009282 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009283
9284 // If this is an invoke instruction, we should insert it after the first
9285 // non-phi, instruction in the normal successor block.
9286 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9287 BasicBlock::iterator I = II->getNormalDest()->begin();
9288 while (isa<PHINode>(I)) ++I;
9289 InsertNewInstBefore(NC, *I);
9290 } else {
9291 // Otherwise, it's a call, just insert cast right after the call instr
9292 InsertNewInstBefore(NC, *Caller);
9293 }
9294 AddUsersToWorkList(*Caller);
9295 } else {
9296 NV = UndefValue::get(Caller->getType());
9297 }
9298 }
9299
9300 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9301 Caller->replaceAllUsesWith(NV);
9302 Caller->eraseFromParent();
9303 RemoveFromWorkList(Caller);
9304 return true;
9305}
9306
Duncan Sands74833f22007-09-17 10:26:40 +00009307// transformCallThroughTrampoline - Turn a call to a function created by the
9308// init_trampoline intrinsic into a direct call to the underlying function.
9309//
9310Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9311 Value *Callee = CS.getCalledValue();
9312 const PointerType *PTy = cast<PointerType>(Callee->getType());
9313 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009314 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009315
9316 // If the call already has the 'nest' attribute somewhere then give up -
9317 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009318 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009319 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009320
9321 IntrinsicInst *Tramp =
9322 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9323
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009324 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009325 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9326 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9327
Chris Lattner1c8733e2008-03-12 17:45:29 +00009328 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9329 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009330 unsigned NestIdx = 1;
9331 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009332 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009333
9334 // Look for a parameter marked with the 'nest' attribute.
9335 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9336 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009337 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009338 // Record the parameter type and any other attributes.
9339 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009340 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009341 break;
9342 }
9343
9344 if (NestTy) {
9345 Instruction *Caller = CS.getInstruction();
9346 std::vector<Value*> NewArgs;
9347 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9348
Chris Lattner1c8733e2008-03-12 17:45:29 +00009349 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9350 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009351
Duncan Sands74833f22007-09-17 10:26:40 +00009352 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009353 // mean appending it. Likewise for attributes.
9354
9355 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009356 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9357 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009358
Duncan Sands74833f22007-09-17 10:26:40 +00009359 {
9360 unsigned Idx = 1;
9361 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9362 do {
9363 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009364 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009365 Value *NestVal = Tramp->getOperand(3);
9366 if (NestVal->getType() != NestTy)
9367 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9368 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009369 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009370 }
9371
9372 if (I == E)
9373 break;
9374
Duncan Sands48b81112008-01-14 19:52:09 +00009375 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009376 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009377 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009378 NewAttrs.push_back
9379 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009380
9381 ++Idx, ++I;
9382 } while (1);
9383 }
9384
9385 // The trampoline may have been bitcast to a bogus type (FTy).
9386 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009387 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009388
Duncan Sands74833f22007-09-17 10:26:40 +00009389 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009390 NewTypes.reserve(FTy->getNumParams()+1);
9391
Duncan Sands74833f22007-09-17 10:26:40 +00009392 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009393 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009394 {
9395 unsigned Idx = 1;
9396 FunctionType::param_iterator I = FTy->param_begin(),
9397 E = FTy->param_end();
9398
9399 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009400 if (Idx == NestIdx)
9401 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009402 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009403
9404 if (I == E)
9405 break;
9406
Duncan Sands48b81112008-01-14 19:52:09 +00009407 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009408 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009409
9410 ++Idx, ++I;
9411 } while (1);
9412 }
9413
9414 // Replace the trampoline call with a direct call. Let the generic
9415 // code sort out any function type mismatches.
9416 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009417 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009418 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9419 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009420 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009421
9422 Instruction *NewCaller;
9423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009424 NewCaller = InvokeInst::Create(NewCallee,
9425 II->getNormalDest(), II->getUnwindDest(),
9426 NewArgs.begin(), NewArgs.end(),
9427 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009428 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009429 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009430 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009431 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9432 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009433 if (cast<CallInst>(Caller)->isTailCall())
9434 cast<CallInst>(NewCaller)->setTailCall();
9435 cast<CallInst>(NewCaller)->
9436 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009437 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009438 }
9439 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9440 Caller->replaceAllUsesWith(NewCaller);
9441 Caller->eraseFromParent();
9442 RemoveFromWorkList(Caller);
9443 return 0;
9444 }
9445 }
9446
9447 // Replace the trampoline call with a direct call. Since there is no 'nest'
9448 // parameter, there is no need to adjust the argument list. Let the generic
9449 // code sort out any function type mismatches.
9450 Constant *NewCallee =
9451 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9452 CS.setCalledFunction(NewCallee);
9453 return CS.getInstruction();
9454}
9455
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009456/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9457/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9458/// and a single binop.
9459Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9460 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9461 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9462 isa<CmpInst>(FirstInst));
9463 unsigned Opc = FirstInst->getOpcode();
9464 Value *LHSVal = FirstInst->getOperand(0);
9465 Value *RHSVal = FirstInst->getOperand(1);
9466
9467 const Type *LHSType = LHSVal->getType();
9468 const Type *RHSType = RHSVal->getType();
9469
9470 // Scan to see if all operands are the same opcode, all have one use, and all
9471 // kill their operands (i.e. the operands have one use).
9472 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9473 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9474 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9475 // Verify type of the LHS matches so we don't fold cmp's of different
9476 // types or GEP's with different index types.
9477 I->getOperand(0)->getType() != LHSType ||
9478 I->getOperand(1)->getType() != RHSType)
9479 return 0;
9480
9481 // If they are CmpInst instructions, check their predicates
9482 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9483 if (cast<CmpInst>(I)->getPredicate() !=
9484 cast<CmpInst>(FirstInst)->getPredicate())
9485 return 0;
9486
9487 // Keep track of which operand needs a phi node.
9488 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9489 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9490 }
9491
9492 // Otherwise, this is safe to transform, determine if it is profitable.
9493
9494 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9495 // Indexes are often folded into load/store instructions, so we don't want to
9496 // hide them behind a phi.
9497 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9498 return 0;
9499
9500 Value *InLHS = FirstInst->getOperand(0);
9501 Value *InRHS = FirstInst->getOperand(1);
9502 PHINode *NewLHS = 0, *NewRHS = 0;
9503 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009504 NewLHS = PHINode::Create(LHSType,
9505 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009506 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9507 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9508 InsertNewInstBefore(NewLHS, PN);
9509 LHSVal = NewLHS;
9510 }
9511
9512 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009513 NewRHS = PHINode::Create(RHSType,
9514 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009515 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9516 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9517 InsertNewInstBefore(NewRHS, PN);
9518 RHSVal = NewRHS;
9519 }
9520
9521 // Add all operands to the new PHIs.
9522 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9523 if (NewLHS) {
9524 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9525 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9526 }
9527 if (NewRHS) {
9528 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9529 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9530 }
9531 }
9532
9533 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009534 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009535 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009536 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537 RHSVal);
9538 else {
9539 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009540 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009541 }
9542}
9543
9544/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9545/// of the block that defines it. This means that it must be obvious the value
9546/// of the load is not changed from the point of the load to the end of the
9547/// block it is in.
9548///
9549/// Finally, it is safe, but not profitable, to sink a load targetting a
9550/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9551/// to a register.
9552static bool isSafeToSinkLoad(LoadInst *L) {
9553 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9554
9555 for (++BBI; BBI != E; ++BBI)
9556 if (BBI->mayWriteToMemory())
9557 return false;
9558
9559 // Check for non-address taken alloca. If not address-taken already, it isn't
9560 // profitable to do this xform.
9561 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9562 bool isAddressTaken = false;
9563 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9564 UI != E; ++UI) {
9565 if (isa<LoadInst>(UI)) continue;
9566 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9567 // If storing TO the alloca, then the address isn't taken.
9568 if (SI->getOperand(1) == AI) continue;
9569 }
9570 isAddressTaken = true;
9571 break;
9572 }
9573
9574 if (!isAddressTaken)
9575 return false;
9576 }
9577
9578 return true;
9579}
9580
9581
9582// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9583// operator and they all are only used by the PHI, PHI together their
9584// inputs, and do the operation once, to the result of the PHI.
9585Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9586 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9587
9588 // Scan the instruction, looking for input operations that can be folded away.
9589 // If all input operands to the phi are the same instruction (e.g. a cast from
9590 // the same type or "+42") we can pull the operation through the PHI, reducing
9591 // code size and simplifying code.
9592 Constant *ConstantOp = 0;
9593 const Type *CastSrcTy = 0;
9594 bool isVolatile = false;
9595 if (isa<CastInst>(FirstInst)) {
9596 CastSrcTy = FirstInst->getOperand(0)->getType();
9597 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9598 // Can fold binop, compare or shift here if the RHS is a constant,
9599 // otherwise call FoldPHIArgBinOpIntoPHI.
9600 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9601 if (ConstantOp == 0)
9602 return FoldPHIArgBinOpIntoPHI(PN);
9603 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9604 isVolatile = LI->isVolatile();
9605 // We can't sink the load if the loaded value could be modified between the
9606 // load and the PHI.
9607 if (LI->getParent() != PN.getIncomingBlock(0) ||
9608 !isSafeToSinkLoad(LI))
9609 return 0;
9610 } else if (isa<GetElementPtrInst>(FirstInst)) {
9611 if (FirstInst->getNumOperands() == 2)
9612 return FoldPHIArgBinOpIntoPHI(PN);
9613 // Can't handle general GEPs yet.
9614 return 0;
9615 } else {
9616 return 0; // Cannot fold this operation.
9617 }
9618
9619 // Check to see if all arguments are the same operation.
9620 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9621 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9622 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9623 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9624 return 0;
9625 if (CastSrcTy) {
9626 if (I->getOperand(0)->getType() != CastSrcTy)
9627 return 0; // Cast operation must match.
9628 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9629 // We can't sink the load if the loaded value could be modified between
9630 // the load and the PHI.
9631 if (LI->isVolatile() != isVolatile ||
9632 LI->getParent() != PN.getIncomingBlock(i) ||
9633 !isSafeToSinkLoad(LI))
9634 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009635
9636 // If the PHI is volatile and its block has multiple successors, sinking
9637 // it would remove a load of the volatile value from the path through the
9638 // other successor.
9639 if (isVolatile &&
9640 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9641 return 0;
9642
9643
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009644 } else if (I->getOperand(1) != ConstantOp) {
9645 return 0;
9646 }
9647 }
9648
9649 // Okay, they are all the same operation. Create a new PHI node of the
9650 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009651 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9652 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009653 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9654
9655 Value *InVal = FirstInst->getOperand(0);
9656 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9657
9658 // Add all operands to the new PHI.
9659 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9660 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9661 if (NewInVal != InVal)
9662 InVal = 0;
9663 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9664 }
9665
9666 Value *PhiVal;
9667 if (InVal) {
9668 // The new PHI unions all of the same values together. This is really
9669 // common, so we handle it intelligently here for compile-time speed.
9670 PhiVal = InVal;
9671 delete NewPN;
9672 } else {
9673 InsertNewInstBefore(NewPN, PN);
9674 PhiVal = NewPN;
9675 }
9676
9677 // Insert and return the new operation.
9678 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009679 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009680 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009681 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009682 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009683 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009684 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009685 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9686
9687 // If this was a volatile load that we are merging, make sure to loop through
9688 // and mark all the input loads as non-volatile. If we don't do this, we will
9689 // insert a new volatile load and the old ones will not be deletable.
9690 if (isVolatile)
9691 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9692 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9693
9694 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695}
9696
9697/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9698/// that is dead.
9699static bool DeadPHICycle(PHINode *PN,
9700 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9701 if (PN->use_empty()) return true;
9702 if (!PN->hasOneUse()) return false;
9703
9704 // Remember this node, and if we find the cycle, return.
9705 if (!PotentiallyDeadPHIs.insert(PN))
9706 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009707
9708 // Don't scan crazily complex things.
9709 if (PotentiallyDeadPHIs.size() == 16)
9710 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009711
9712 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9713 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9714
9715 return false;
9716}
9717
Chris Lattner27b695d2007-11-06 21:52:06 +00009718/// PHIsEqualValue - Return true if this phi node is always equal to
9719/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9720/// z = some value; x = phi (y, z); y = phi (x, z)
9721static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9722 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9723 // See if we already saw this PHI node.
9724 if (!ValueEqualPHIs.insert(PN))
9725 return true;
9726
9727 // Don't scan crazily complex things.
9728 if (ValueEqualPHIs.size() == 16)
9729 return false;
9730
9731 // Scan the operands to see if they are either phi nodes or are equal to
9732 // the value.
9733 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9734 Value *Op = PN->getIncomingValue(i);
9735 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9736 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9737 return false;
9738 } else if (Op != NonPhiInVal)
9739 return false;
9740 }
9741
9742 return true;
9743}
9744
9745
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009746// PHINode simplification
9747//
9748Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9749 // If LCSSA is around, don't mess with Phi nodes
9750 if (MustPreserveLCSSA) return 0;
9751
9752 if (Value *V = PN.hasConstantValue())
9753 return ReplaceInstUsesWith(PN, V);
9754
9755 // If all PHI operands are the same operation, pull them through the PHI,
9756 // reducing code size.
9757 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9758 PN.getIncomingValue(0)->hasOneUse())
9759 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9760 return Result;
9761
9762 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9763 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9764 // PHI)... break the cycle.
9765 if (PN.hasOneUse()) {
9766 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9767 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9768 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9769 PotentiallyDeadPHIs.insert(&PN);
9770 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9771 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9772 }
9773
9774 // If this phi has a single use, and if that use just computes a value for
9775 // the next iteration of a loop, delete the phi. This occurs with unused
9776 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9777 // common case here is good because the only other things that catch this
9778 // are induction variable analysis (sometimes) and ADCE, which is only run
9779 // late.
9780 if (PHIUser->hasOneUse() &&
9781 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9782 PHIUser->use_back() == &PN) {
9783 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9784 }
9785 }
9786
Chris Lattner27b695d2007-11-06 21:52:06 +00009787 // We sometimes end up with phi cycles that non-obviously end up being the
9788 // same value, for example:
9789 // z = some value; x = phi (y, z); y = phi (x, z)
9790 // where the phi nodes don't necessarily need to be in the same block. Do a
9791 // quick check to see if the PHI node only contains a single non-phi value, if
9792 // so, scan to see if the phi cycle is actually equal to that value.
9793 {
9794 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9795 // Scan for the first non-phi operand.
9796 while (InValNo != NumOperandVals &&
9797 isa<PHINode>(PN.getIncomingValue(InValNo)))
9798 ++InValNo;
9799
9800 if (InValNo != NumOperandVals) {
9801 Value *NonPhiInVal = PN.getOperand(InValNo);
9802
9803 // Scan the rest of the operands to see if there are any conflicts, if so
9804 // there is no need to recursively scan other phis.
9805 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9806 Value *OpVal = PN.getIncomingValue(InValNo);
9807 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9808 break;
9809 }
9810
9811 // If we scanned over all operands, then we have one unique value plus
9812 // phi values. Scan PHI nodes to see if they all merge in each other or
9813 // the value.
9814 if (InValNo == NumOperandVals) {
9815 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9816 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9817 return ReplaceInstUsesWith(PN, NonPhiInVal);
9818 }
9819 }
9820 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009821 return 0;
9822}
9823
9824static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9825 Instruction *InsertPoint,
9826 InstCombiner *IC) {
9827 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9828 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9829 // We must cast correctly to the pointer type. Ensure that we
9830 // sign extend the integer value if it is smaller as this is
9831 // used for address computation.
9832 Instruction::CastOps opcode =
9833 (VTySize < PtrSize ? Instruction::SExt :
9834 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9835 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9836}
9837
9838
9839Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9840 Value *PtrOp = GEP.getOperand(0);
9841 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9842 // If so, eliminate the noop.
9843 if (GEP.getNumOperands() == 1)
9844 return ReplaceInstUsesWith(GEP, PtrOp);
9845
9846 if (isa<UndefValue>(GEP.getOperand(0)))
9847 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9848
9849 bool HasZeroPointerIndex = false;
9850 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9851 HasZeroPointerIndex = C->isNullValue();
9852
9853 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9854 return ReplaceInstUsesWith(GEP, PtrOp);
9855
9856 // Eliminate unneeded casts for indices.
9857 bool MadeChange = false;
9858
9859 gep_type_iterator GTI = gep_type_begin(GEP);
9860 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9861 if (isa<SequentialType>(*GTI)) {
9862 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9863 if (CI->getOpcode() == Instruction::ZExt ||
9864 CI->getOpcode() == Instruction::SExt) {
9865 const Type *SrcTy = CI->getOperand(0)->getType();
9866 // We can eliminate a cast from i32 to i64 iff the target
9867 // is a 32-bit pointer target.
9868 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9869 MadeChange = true;
9870 GEP.setOperand(i, CI->getOperand(0));
9871 }
9872 }
9873 }
9874 // If we are using a wider index than needed for this platform, shrink it
9875 // to what we need. If the incoming value needs a cast instruction,
9876 // insert it. This explicit cast can make subsequent optimizations more
9877 // obvious.
9878 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009879 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009880 if (Constant *C = dyn_cast<Constant>(Op)) {
9881 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9882 MadeChange = true;
9883 } else {
9884 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9885 GEP);
9886 GEP.setOperand(i, Op);
9887 MadeChange = true;
9888 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009889 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009890 }
9891 }
9892 if (MadeChange) return &GEP;
9893
9894 // If this GEP instruction doesn't move the pointer, and if the input operand
9895 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9896 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009897 if (GEP.hasAllZeroIndices()) {
9898 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9899 // If the bitcast is of an allocation, and the allocation will be
9900 // converted to match the type of the cast, don't touch this.
9901 if (isa<AllocationInst>(BCI->getOperand(0))) {
9902 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009903 if (Instruction *I = visitBitCast(*BCI)) {
9904 if (I != BCI) {
9905 I->takeName(BCI);
9906 BCI->getParent()->getInstList().insert(BCI, I);
9907 ReplaceInstUsesWith(*BCI, I);
9908 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009909 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009910 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009911 }
9912 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9913 }
9914 }
9915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009916 // Combine Indices - If the source pointer to this getelementptr instruction
9917 // is a getelementptr instruction, combine the indices of the two
9918 // getelementptr instructions into a single instruction.
9919 //
9920 SmallVector<Value*, 8> SrcGEPOperands;
9921 if (User *Src = dyn_castGetElementPtr(PtrOp))
9922 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9923
9924 if (!SrcGEPOperands.empty()) {
9925 // Note that if our source is a gep chain itself that we wait for that
9926 // chain to be resolved before we perform this transformation. This
9927 // avoids us creating a TON of code in some cases.
9928 //
9929 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9930 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9931 return 0; // Wait until our source is folded to completion.
9932
9933 SmallVector<Value*, 8> Indices;
9934
9935 // Find out whether the last index in the source GEP is a sequential idx.
9936 bool EndsWithSequential = false;
9937 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9938 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9939 EndsWithSequential = !isa<StructType>(*I);
9940
9941 // Can we combine the two pointer arithmetics offsets?
9942 if (EndsWithSequential) {
9943 // Replace: gep (gep %P, long B), long A, ...
9944 // With: T = long A+B; gep %P, T, ...
9945 //
9946 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9947 if (SO1 == Constant::getNullValue(SO1->getType())) {
9948 Sum = GO1;
9949 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9950 Sum = SO1;
9951 } else {
9952 // If they aren't the same type, convert both to an integer of the
9953 // target's pointer size.
9954 if (SO1->getType() != GO1->getType()) {
9955 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9956 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9957 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9958 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9959 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009960 unsigned PS = TD->getPointerSizeInBits();
9961 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009962 // Convert GO1 to SO1's type.
9963 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9964
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009965 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009966 // Convert SO1 to GO1's type.
9967 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9968 } else {
9969 const Type *PT = TD->getIntPtrType();
9970 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9971 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9972 }
9973 }
9974 }
9975 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9976 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9977 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009978 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009979 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9980 }
9981 }
9982
9983 // Recycle the GEP we already have if possible.
9984 if (SrcGEPOperands.size() == 2) {
9985 GEP.setOperand(0, SrcGEPOperands[0]);
9986 GEP.setOperand(1, Sum);
9987 return &GEP;
9988 } else {
9989 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9990 SrcGEPOperands.end()-1);
9991 Indices.push_back(Sum);
9992 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9993 }
9994 } else if (isa<Constant>(*GEP.idx_begin()) &&
9995 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9996 SrcGEPOperands.size() != 1) {
9997 // Otherwise we can do the fold if the first index of the GEP is a zero
9998 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9999 SrcGEPOperands.end());
10000 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10001 }
10002
10003 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010004 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10005 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010006
10007 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10008 // GEP of global variable. If all of the indices for this GEP are
10009 // constants, we can promote this to a constexpr instead of an instruction.
10010
10011 // Scan for nonconstants...
10012 SmallVector<Constant*, 8> Indices;
10013 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10014 for (; I != E && isa<Constant>(*I); ++I)
10015 Indices.push_back(cast<Constant>(*I));
10016
10017 if (I == E) { // If they are all constants...
10018 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10019 &Indices[0],Indices.size());
10020
10021 // Replace all uses of the GEP with the new constexpr...
10022 return ReplaceInstUsesWith(GEP, CE);
10023 }
10024 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10025 if (!isa<PointerType>(X->getType())) {
10026 // Not interesting. Source pointer must be a cast from pointer.
10027 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010028 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10029 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010030 //
10031 // This occurs when the program declares an array extern like "int X[];"
10032 //
10033 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10034 const PointerType *XTy = cast<PointerType>(X->getType());
10035 if (const ArrayType *XATy =
10036 dyn_cast<ArrayType>(XTy->getElementType()))
10037 if (const ArrayType *CATy =
10038 dyn_cast<ArrayType>(CPTy->getElementType()))
10039 if (CATy->getElementType() == XATy->getElementType()) {
10040 // At this point, we know that the cast source type is a pointer
10041 // to an array of the same type as the destination pointer
10042 // array. Because the array type is never stepped over (there
10043 // is a leading zero) we can fold the cast into this GEP.
10044 GEP.setOperand(0, X);
10045 return &GEP;
10046 }
10047 } else if (GEP.getNumOperands() == 2) {
10048 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010049 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10050 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010051 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10052 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10053 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010054 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10055 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010056 Value *Idx[2];
10057 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10058 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010059 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010060 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010061 // V and GEP are both pointer types --> BitCast
10062 return new BitCastInst(V, GEP.getType());
10063 }
10064
10065 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010066 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010067 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010068 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010069
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010070 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010071 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010072 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010073
10074 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10075 // allow either a mul, shift, or constant here.
10076 Value *NewIdx = 0;
10077 ConstantInt *Scale = 0;
10078 if (ArrayEltSize == 1) {
10079 NewIdx = GEP.getOperand(1);
10080 Scale = ConstantInt::get(NewIdx->getType(), 1);
10081 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10082 NewIdx = ConstantInt::get(CI->getType(), 1);
10083 Scale = CI;
10084 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10085 if (Inst->getOpcode() == Instruction::Shl &&
10086 isa<ConstantInt>(Inst->getOperand(1))) {
10087 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10088 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10089 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10090 NewIdx = Inst->getOperand(0);
10091 } else if (Inst->getOpcode() == Instruction::Mul &&
10092 isa<ConstantInt>(Inst->getOperand(1))) {
10093 Scale = cast<ConstantInt>(Inst->getOperand(1));
10094 NewIdx = Inst->getOperand(0);
10095 }
10096 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010097
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010098 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010099 // out, perform the transformation. Note, we don't know whether Scale is
10100 // signed or not. We'll use unsigned version of division/modulo
10101 // operation after making sure Scale doesn't have the sign bit set.
10102 if (Scale && Scale->getSExtValue() >= 0LL &&
10103 Scale->getZExtValue() % ArrayEltSize == 0) {
10104 Scale = ConstantInt::get(Scale->getType(),
10105 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010106 if (Scale->getZExtValue() != 1) {
10107 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010108 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010109 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010110 NewIdx = InsertNewInstBefore(Sc, GEP);
10111 }
10112
10113 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010114 Value *Idx[2];
10115 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10116 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010117 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010118 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010119 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10120 // The NewGEP must be pointer typed, so must the old one -> BitCast
10121 return new BitCastInst(NewGEP, GEP.getType());
10122 }
10123 }
10124 }
10125 }
10126
10127 return 0;
10128}
10129
10130Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10131 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010132 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010133 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10134 const Type *NewTy =
10135 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10136 AllocationInst *New = 0;
10137
10138 // Create and insert the replacement instruction...
10139 if (isa<MallocInst>(AI))
10140 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10141 else {
10142 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10143 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10144 }
10145
10146 InsertNewInstBefore(New, AI);
10147
10148 // Scan to the end of the allocation instructions, to skip over a block of
10149 // allocas if possible...
10150 //
10151 BasicBlock::iterator It = New;
10152 while (isa<AllocationInst>(*It)) ++It;
10153
10154 // Now that I is pointing to the first non-allocation-inst in the block,
10155 // insert our getelementptr instruction...
10156 //
10157 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010158 Value *Idx[2];
10159 Idx[0] = NullIdx;
10160 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010161 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10162 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010163
10164 // Now make everything use the getelementptr instead of the original
10165 // allocation.
10166 return ReplaceInstUsesWith(AI, V);
10167 } else if (isa<UndefValue>(AI.getArraySize())) {
10168 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10169 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010171
10172 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10173 // Note that we only do this for alloca's, because malloc should allocate and
10174 // return a unique pointer, even for a zero byte allocation.
10175 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010176 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010177 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10178
10179 return 0;
10180}
10181
10182Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10183 Value *Op = FI.getOperand(0);
10184
10185 // free undef -> unreachable.
10186 if (isa<UndefValue>(Op)) {
10187 // Insert a new store to null because we cannot modify the CFG here.
10188 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010189 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010190 return EraseInstFromFunction(FI);
10191 }
10192
10193 // If we have 'free null' delete the instruction. This can happen in stl code
10194 // when lots of inlining happens.
10195 if (isa<ConstantPointerNull>(Op))
10196 return EraseInstFromFunction(FI);
10197
10198 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10199 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10200 FI.setOperand(0, CI->getOperand(0));
10201 return &FI;
10202 }
10203
10204 // Change free (gep X, 0,0,0,0) into free(X)
10205 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10206 if (GEPI->hasAllZeroIndices()) {
10207 AddToWorkList(GEPI);
10208 FI.setOperand(0, GEPI->getOperand(0));
10209 return &FI;
10210 }
10211 }
10212
10213 // Change free(malloc) into nothing, if the malloc has a single use.
10214 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10215 if (MI->hasOneUse()) {
10216 EraseInstFromFunction(FI);
10217 return EraseInstFromFunction(*MI);
10218 }
10219
10220 return 0;
10221}
10222
10223
10224/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010225static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010226 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010227 User *CI = cast<User>(LI.getOperand(0));
10228 Value *CastOp = CI->getOperand(0);
10229
Devang Patela0f8ea82007-10-18 19:52:32 +000010230 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10231 // Instead of loading constant c string, use corresponding integer value
10232 // directly if string length is small enough.
10233 const std::string &Str = CE->getOperand(0)->getStringValue();
10234 if (!Str.empty()) {
10235 unsigned len = Str.length();
10236 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10237 unsigned numBits = Ty->getPrimitiveSizeInBits();
10238 // Replace LI with immediate integer store.
10239 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010240 APInt StrVal(numBits, 0);
10241 APInt SingleChar(numBits, 0);
10242 if (TD->isLittleEndian()) {
10243 for (signed i = len-1; i >= 0; i--) {
10244 SingleChar = (uint64_t) Str[i];
10245 StrVal = (StrVal << 8) | SingleChar;
10246 }
10247 } else {
10248 for (unsigned i = 0; i < len; i++) {
10249 SingleChar = (uint64_t) Str[i];
10250 StrVal = (StrVal << 8) | SingleChar;
10251 }
10252 // Append NULL at the end.
10253 SingleChar = 0;
10254 StrVal = (StrVal << 8) | SingleChar;
10255 }
10256 Value *NL = ConstantInt::get(StrVal);
10257 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010258 }
10259 }
10260 }
10261
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010262 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10263 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10264 const Type *SrcPTy = SrcTy->getElementType();
10265
10266 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10267 isa<VectorType>(DestPTy)) {
10268 // If the source is an array, the code below will not succeed. Check to
10269 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10270 // constants.
10271 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10272 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10273 if (ASrcTy->getNumElements() != 0) {
10274 Value *Idxs[2];
10275 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10276 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10277 SrcTy = cast<PointerType>(CastOp->getType());
10278 SrcPTy = SrcTy->getElementType();
10279 }
10280
10281 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10282 isa<VectorType>(SrcPTy)) &&
10283 // Do not allow turning this into a load of an integer, which is then
10284 // casted to a pointer, this pessimizes pointer analysis a lot.
10285 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10286 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10287 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10288
10289 // Okay, we are casting from one integer or pointer type to another of
10290 // the same size. Instead of casting the pointer before the load, cast
10291 // the result of the loaded value.
10292 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10293 CI->getName(),
10294 LI.isVolatile()),LI);
10295 // Now cast the result of the load.
10296 return new BitCastInst(NewLoad, LI.getType());
10297 }
10298 }
10299 }
10300 return 0;
10301}
10302
10303/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10304/// from this value cannot trap. If it is not obviously safe to load from the
10305/// specified pointer, we do a quick local scan of the basic block containing
10306/// ScanFrom, to determine if the address is already accessed.
10307static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010308 // If it is an alloca it is always safe to load from.
10309 if (isa<AllocaInst>(V)) return true;
10310
Duncan Sandse40a94a2007-09-19 10:25:38 +000010311 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010312 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010313 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010314 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010315
10316 // Otherwise, be a little bit agressive by scanning the local block where we
10317 // want to check to see if the pointer is already being loaded or stored
10318 // from/to. If so, the previous load or store would have already trapped,
10319 // so there is no harm doing an extra load (also, CSE will later eliminate
10320 // the load entirely).
10321 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10322
10323 while (BBI != E) {
10324 --BBI;
10325
10326 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10327 if (LI->getOperand(0) == V) return true;
10328 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10329 if (SI->getOperand(1) == V) return true;
10330
10331 }
10332 return false;
10333}
10334
Chris Lattner0270a112007-08-11 18:48:48 +000010335/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10336/// until we find the underlying object a pointer is referring to or something
10337/// we don't understand. Note that the returned pointer may be offset from the
10338/// input, because we ignore GEP indices.
10339static Value *GetUnderlyingObject(Value *Ptr) {
10340 while (1) {
10341 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10342 if (CE->getOpcode() == Instruction::BitCast ||
10343 CE->getOpcode() == Instruction::GetElementPtr)
10344 Ptr = CE->getOperand(0);
10345 else
10346 return Ptr;
10347 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10348 Ptr = BCI->getOperand(0);
10349 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10350 Ptr = GEP->getOperand(0);
10351 } else {
10352 return Ptr;
10353 }
10354 }
10355}
10356
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010357Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10358 Value *Op = LI.getOperand(0);
10359
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010360 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010361 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10362 if (KnownAlign >
10363 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10364 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010365 LI.setAlignment(KnownAlign);
10366
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010367 // load (cast X) --> cast (load X) iff safe
10368 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010369 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010370 return Res;
10371
10372 // None of the following transforms are legal for volatile loads.
10373 if (LI.isVolatile()) return 0;
10374
10375 if (&LI.getParent()->front() != &LI) {
10376 BasicBlock::iterator BBI = &LI; --BBI;
10377 // If the instruction immediately before this is a store to the same
10378 // address, do a simple form of store->load forwarding.
10379 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10380 if (SI->getOperand(1) == LI.getOperand(0))
10381 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10382 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10383 if (LIB->getOperand(0) == LI.getOperand(0))
10384 return ReplaceInstUsesWith(LI, LIB);
10385 }
10386
Christopher Lamb2c175392007-12-29 07:56:53 +000010387 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10388 const Value *GEPI0 = GEPI->getOperand(0);
10389 // TODO: Consider a target hook for valid address spaces for this xform.
10390 if (isa<ConstantPointerNull>(GEPI0) &&
10391 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010392 // Insert a new store to null instruction before the load to indicate
10393 // that this code is not reachable. We do this instead of inserting
10394 // an unreachable instruction directly because we cannot modify the
10395 // CFG.
10396 new StoreInst(UndefValue::get(LI.getType()),
10397 Constant::getNullValue(Op->getType()), &LI);
10398 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10399 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010400 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010401
10402 if (Constant *C = dyn_cast<Constant>(Op)) {
10403 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010404 // TODO: Consider a target hook for valid address spaces for this xform.
10405 if (isa<UndefValue>(C) || (C->isNullValue() &&
10406 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010407 // Insert a new store to null instruction before the load to indicate that
10408 // this code is not reachable. We do this instead of inserting an
10409 // unreachable instruction directly because we cannot modify the CFG.
10410 new StoreInst(UndefValue::get(LI.getType()),
10411 Constant::getNullValue(Op->getType()), &LI);
10412 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10413 }
10414
10415 // Instcombine load (constant global) into the value loaded.
10416 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10417 if (GV->isConstant() && !GV->isDeclaration())
10418 return ReplaceInstUsesWith(LI, GV->getInitializer());
10419
10420 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010422 if (CE->getOpcode() == Instruction::GetElementPtr) {
10423 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10424 if (GV->isConstant() && !GV->isDeclaration())
10425 if (Constant *V =
10426 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10427 return ReplaceInstUsesWith(LI, V);
10428 if (CE->getOperand(0)->isNullValue()) {
10429 // Insert a new store to null instruction before the load to indicate
10430 // that this code is not reachable. We do this instead of inserting
10431 // an unreachable instruction directly because we cannot modify the
10432 // 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 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010439 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010440 return Res;
10441 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010442 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010443 }
Chris Lattner0270a112007-08-11 18:48:48 +000010444
10445 // If this load comes from anywhere in a constant global, and if the global
10446 // is all undef or zero, we know what it loads.
10447 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10448 if (GV->isConstant() && GV->hasInitializer()) {
10449 if (GV->getInitializer()->isNullValue())
10450 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10451 else if (isa<UndefValue>(GV->getInitializer()))
10452 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10453 }
10454 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010455
10456 if (Op->hasOneUse()) {
10457 // Change select and PHI nodes to select values instead of addresses: this
10458 // helps alias analysis out a lot, allows many others simplifications, and
10459 // exposes redundancy in the code.
10460 //
10461 // Note that we cannot do the transformation unless we know that the
10462 // introduced loads cannot trap! Something like this is valid as long as
10463 // the condition is always false: load (select bool %C, int* null, int* %G),
10464 // but it would not be valid if we transformed it to load from null
10465 // unconditionally.
10466 //
10467 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10468 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10469 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10470 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10471 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10472 SI->getOperand(1)->getName()+".val"), LI);
10473 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10474 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010475 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010476 }
10477
10478 // load (select (cond, null, P)) -> load P
10479 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10480 if (C->isNullValue()) {
10481 LI.setOperand(0, SI->getOperand(2));
10482 return &LI;
10483 }
10484
10485 // load (select (cond, P, null)) -> load P
10486 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10487 if (C->isNullValue()) {
10488 LI.setOperand(0, SI->getOperand(1));
10489 return &LI;
10490 }
10491 }
10492 }
10493 return 0;
10494}
10495
10496/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10497/// when possible.
10498static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10499 User *CI = cast<User>(SI.getOperand(1));
10500 Value *CastOp = CI->getOperand(0);
10501
10502 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10503 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10504 const Type *SrcPTy = SrcTy->getElementType();
10505
10506 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10507 // If the source is an array, the code below will not succeed. Check to
10508 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10509 // constants.
10510 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10511 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10512 if (ASrcTy->getNumElements() != 0) {
10513 Value* Idxs[2];
10514 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10515 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10516 SrcTy = cast<PointerType>(CastOp->getType());
10517 SrcPTy = SrcTy->getElementType();
10518 }
10519
10520 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10521 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10522 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10523
10524 // Okay, we are casting from one integer or pointer type to another of
10525 // the same size. Instead of casting the pointer before
10526 // the store, cast the value to be stored.
10527 Value *NewCast;
10528 Value *SIOp0 = SI.getOperand(0);
10529 Instruction::CastOps opcode = Instruction::BitCast;
10530 const Type* CastSrcTy = SIOp0->getType();
10531 const Type* CastDstTy = SrcPTy;
10532 if (isa<PointerType>(CastDstTy)) {
10533 if (CastSrcTy->isInteger())
10534 opcode = Instruction::IntToPtr;
10535 } else if (isa<IntegerType>(CastDstTy)) {
10536 if (isa<PointerType>(SIOp0->getType()))
10537 opcode = Instruction::PtrToInt;
10538 }
10539 if (Constant *C = dyn_cast<Constant>(SIOp0))
10540 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10541 else
10542 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010543 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010544 SI);
10545 return new StoreInst(NewCast, CastOp);
10546 }
10547 }
10548 }
10549 return 0;
10550}
10551
10552Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10553 Value *Val = SI.getOperand(0);
10554 Value *Ptr = SI.getOperand(1);
10555
10556 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10557 EraseInstFromFunction(SI);
10558 ++NumCombined;
10559 return 0;
10560 }
10561
10562 // If the RHS is an alloca with a single use, zapify the store, making the
10563 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010564 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010565 if (isa<AllocaInst>(Ptr)) {
10566 EraseInstFromFunction(SI);
10567 ++NumCombined;
10568 return 0;
10569 }
10570
10571 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10572 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10573 GEP->getOperand(0)->hasOneUse()) {
10574 EraseInstFromFunction(SI);
10575 ++NumCombined;
10576 return 0;
10577 }
10578 }
10579
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010580 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010581 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10582 if (KnownAlign >
10583 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10584 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010585 SI.setAlignment(KnownAlign);
10586
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010587 // Do really simple DSE, to catch cases where there are several consequtive
10588 // stores to the same location, separated by a few arithmetic operations. This
10589 // situation often occurs with bitfield accesses.
10590 BasicBlock::iterator BBI = &SI;
10591 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10592 --ScanInsts) {
10593 --BBI;
10594
10595 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10596 // Prev store isn't volatile, and stores to the same location?
10597 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10598 ++NumDeadStore;
10599 ++BBI;
10600 EraseInstFromFunction(*PrevSI);
10601 continue;
10602 }
10603 break;
10604 }
10605
10606 // If this is a load, we have to stop. However, if the loaded value is from
10607 // the pointer we're loading and is producing the pointer we're storing,
10608 // then *this* store is dead (X = load P; store X -> P).
10609 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010610 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010611 EraseInstFromFunction(SI);
10612 ++NumCombined;
10613 return 0;
10614 }
10615 // Otherwise, this is a load from some other location. Stores before it
10616 // may not be dead.
10617 break;
10618 }
10619
10620 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010621 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010622 break;
10623 }
10624
10625
10626 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10627
10628 // store X, null -> turns into 'unreachable' in SimplifyCFG
10629 if (isa<ConstantPointerNull>(Ptr)) {
10630 if (!isa<UndefValue>(Val)) {
10631 SI.setOperand(0, UndefValue::get(Val->getType()));
10632 if (Instruction *U = dyn_cast<Instruction>(Val))
10633 AddToWorkList(U); // Dropped a use.
10634 ++NumCombined;
10635 }
10636 return 0; // Do not modify these!
10637 }
10638
10639 // store undef, Ptr -> noop
10640 if (isa<UndefValue>(Val)) {
10641 EraseInstFromFunction(SI);
10642 ++NumCombined;
10643 return 0;
10644 }
10645
10646 // If the pointer destination is a cast, see if we can fold the cast into the
10647 // source instead.
10648 if (isa<CastInst>(Ptr))
10649 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10650 return Res;
10651 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10652 if (CE->isCast())
10653 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10654 return Res;
10655
10656
10657 // If this store is the last instruction in the basic block, and if the block
10658 // ends with an unconditional branch, try to move it to the successor block.
10659 BBI = &SI; ++BBI;
10660 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10661 if (BI->isUnconditional())
10662 if (SimplifyStoreAtEndOfBlock(SI))
10663 return 0; // xform done!
10664
10665 return 0;
10666}
10667
10668/// SimplifyStoreAtEndOfBlock - Turn things like:
10669/// if () { *P = v1; } else { *P = v2 }
10670/// into a phi node with a store in the successor.
10671///
10672/// Simplify things like:
10673/// *P = v1; if () { *P = v2; }
10674/// into a phi node with a store in the successor.
10675///
10676bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10677 BasicBlock *StoreBB = SI.getParent();
10678
10679 // Check to see if the successor block has exactly two incoming edges. If
10680 // so, see if the other predecessor contains a store to the same location.
10681 // if so, insert a PHI node (if needed) and move the stores down.
10682 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10683
10684 // Determine whether Dest has exactly two predecessors and, if so, compute
10685 // the other predecessor.
10686 pred_iterator PI = pred_begin(DestBB);
10687 BasicBlock *OtherBB = 0;
10688 if (*PI != StoreBB)
10689 OtherBB = *PI;
10690 ++PI;
10691 if (PI == pred_end(DestBB))
10692 return false;
10693
10694 if (*PI != StoreBB) {
10695 if (OtherBB)
10696 return false;
10697 OtherBB = *PI;
10698 }
10699 if (++PI != pred_end(DestBB))
10700 return false;
10701
10702
10703 // Verify that the other block ends in a branch and is not otherwise empty.
10704 BasicBlock::iterator BBI = OtherBB->getTerminator();
10705 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10706 if (!OtherBr || BBI == OtherBB->begin())
10707 return false;
10708
10709 // If the other block ends in an unconditional branch, check for the 'if then
10710 // else' case. there is an instruction before the branch.
10711 StoreInst *OtherStore = 0;
10712 if (OtherBr->isUnconditional()) {
10713 // If this isn't a store, or isn't a store to the same location, bail out.
10714 --BBI;
10715 OtherStore = dyn_cast<StoreInst>(BBI);
10716 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10717 return false;
10718 } else {
10719 // Otherwise, the other block ended with a conditional branch. If one of the
10720 // destinations is StoreBB, then we have the if/then case.
10721 if (OtherBr->getSuccessor(0) != StoreBB &&
10722 OtherBr->getSuccessor(1) != StoreBB)
10723 return false;
10724
10725 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10726 // if/then triangle. See if there is a store to the same ptr as SI that
10727 // lives in OtherBB.
10728 for (;; --BBI) {
10729 // Check to see if we find the matching store.
10730 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10731 if (OtherStore->getOperand(1) != SI.getOperand(1))
10732 return false;
10733 break;
10734 }
10735 // If we find something that may be using the stored value, or if we run
10736 // out of instructions, we can't do the xform.
10737 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10738 BBI == OtherBB->begin())
10739 return false;
10740 }
10741
10742 // In order to eliminate the store in OtherBr, we have to
10743 // make sure nothing reads the stored value in StoreBB.
10744 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10745 // FIXME: This should really be AA driven.
10746 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10747 return false;
10748 }
10749 }
10750
10751 // Insert a PHI node now if we need it.
10752 Value *MergedVal = OtherStore->getOperand(0);
10753 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010754 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010755 PN->reserveOperandSpace(2);
10756 PN->addIncoming(SI.getOperand(0), SI.getParent());
10757 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10758 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10759 }
10760
10761 // Advance to a place where it is safe to insert the new store and
10762 // insert it.
10763 BBI = DestBB->begin();
10764 while (isa<PHINode>(BBI)) ++BBI;
10765 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10766 OtherStore->isVolatile()), *BBI);
10767
10768 // Nuke the old stores.
10769 EraseInstFromFunction(SI);
10770 EraseInstFromFunction(*OtherStore);
10771 ++NumCombined;
10772 return true;
10773}
10774
10775
10776Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10777 // Change br (not X), label True, label False to: br X, label False, True
10778 Value *X = 0;
10779 BasicBlock *TrueDest;
10780 BasicBlock *FalseDest;
10781 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10782 !isa<Constant>(X)) {
10783 // Swap Destinations and condition...
10784 BI.setCondition(X);
10785 BI.setSuccessor(0, FalseDest);
10786 BI.setSuccessor(1, TrueDest);
10787 return &BI;
10788 }
10789
10790 // Cannonicalize fcmp_one -> fcmp_oeq
10791 FCmpInst::Predicate FPred; Value *Y;
10792 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10793 TrueDest, FalseDest)))
10794 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10795 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10796 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10797 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10798 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10799 NewSCC->takeName(I);
10800 // Swap Destinations and condition...
10801 BI.setCondition(NewSCC);
10802 BI.setSuccessor(0, FalseDest);
10803 BI.setSuccessor(1, TrueDest);
10804 RemoveFromWorkList(I);
10805 I->eraseFromParent();
10806 AddToWorkList(NewSCC);
10807 return &BI;
10808 }
10809
10810 // Cannonicalize icmp_ne -> icmp_eq
10811 ICmpInst::Predicate IPred;
10812 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10813 TrueDest, FalseDest)))
10814 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10815 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10816 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10817 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10818 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10819 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10820 NewSCC->takeName(I);
10821 // Swap Destinations and condition...
10822 BI.setCondition(NewSCC);
10823 BI.setSuccessor(0, FalseDest);
10824 BI.setSuccessor(1, TrueDest);
10825 RemoveFromWorkList(I);
10826 I->eraseFromParent();;
10827 AddToWorkList(NewSCC);
10828 return &BI;
10829 }
10830
10831 return 0;
10832}
10833
10834Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10835 Value *Cond = SI.getCondition();
10836 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10837 if (I->getOpcode() == Instruction::Add)
10838 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10839 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10840 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10841 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10842 AddRHS));
10843 SI.setOperand(0, I->getOperand(0));
10844 AddToWorkList(I);
10845 return &SI;
10846 }
10847 }
10848 return 0;
10849}
10850
10851/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10852/// is to leave as a vector operation.
10853static bool CheapToScalarize(Value *V, bool isConstant) {
10854 if (isa<ConstantAggregateZero>(V))
10855 return true;
10856 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10857 if (isConstant) return true;
10858 // If all elts are the same, we can extract.
10859 Constant *Op0 = C->getOperand(0);
10860 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10861 if (C->getOperand(i) != Op0)
10862 return false;
10863 return true;
10864 }
10865 Instruction *I = dyn_cast<Instruction>(V);
10866 if (!I) return false;
10867
10868 // Insert element gets simplified to the inserted element or is deleted if
10869 // this is constant idx extract element and its a constant idx insertelt.
10870 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10871 isa<ConstantInt>(I->getOperand(2)))
10872 return true;
10873 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10874 return true;
10875 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10876 if (BO->hasOneUse() &&
10877 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10878 CheapToScalarize(BO->getOperand(1), isConstant)))
10879 return true;
10880 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10881 if (CI->hasOneUse() &&
10882 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10883 CheapToScalarize(CI->getOperand(1), isConstant)))
10884 return true;
10885
10886 return false;
10887}
10888
10889/// Read and decode a shufflevector mask.
10890///
10891/// It turns undef elements into values that are larger than the number of
10892/// elements in the input.
10893static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10894 unsigned NElts = SVI->getType()->getNumElements();
10895 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10896 return std::vector<unsigned>(NElts, 0);
10897 if (isa<UndefValue>(SVI->getOperand(2)))
10898 return std::vector<unsigned>(NElts, 2*NElts);
10899
10900 std::vector<unsigned> Result;
10901 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10902 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10903 if (isa<UndefValue>(CP->getOperand(i)))
10904 Result.push_back(NElts*2); // undef -> 8
10905 else
10906 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10907 return Result;
10908}
10909
10910/// FindScalarElement - Given a vector and an element number, see if the scalar
10911/// value is already around as a register, for example if it were inserted then
10912/// extracted from the vector.
10913static Value *FindScalarElement(Value *V, unsigned EltNo) {
10914 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10915 const VectorType *PTy = cast<VectorType>(V->getType());
10916 unsigned Width = PTy->getNumElements();
10917 if (EltNo >= Width) // Out of range access.
10918 return UndefValue::get(PTy->getElementType());
10919
10920 if (isa<UndefValue>(V))
10921 return UndefValue::get(PTy->getElementType());
10922 else if (isa<ConstantAggregateZero>(V))
10923 return Constant::getNullValue(PTy->getElementType());
10924 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10925 return CP->getOperand(EltNo);
10926 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10927 // If this is an insert to a variable element, we don't know what it is.
10928 if (!isa<ConstantInt>(III->getOperand(2)))
10929 return 0;
10930 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10931
10932 // If this is an insert to the element we are looking for, return the
10933 // inserted value.
10934 if (EltNo == IIElt)
10935 return III->getOperand(1);
10936
10937 // Otherwise, the insertelement doesn't modify the value, recurse on its
10938 // vector input.
10939 return FindScalarElement(III->getOperand(0), EltNo);
10940 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10941 unsigned InEl = getShuffleMask(SVI)[EltNo];
10942 if (InEl < Width)
10943 return FindScalarElement(SVI->getOperand(0), InEl);
10944 else if (InEl < Width*2)
10945 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10946 else
10947 return UndefValue::get(PTy->getElementType());
10948 }
10949
10950 // Otherwise, we don't know.
10951 return 0;
10952}
10953
10954Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10955
10956 // If vector val is undef, replace extract with scalar undef.
10957 if (isa<UndefValue>(EI.getOperand(0)))
10958 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10959
10960 // If vector val is constant 0, replace extract with scalar 0.
10961 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10962 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10963
10964 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10965 // If vector val is constant with uniform operands, replace EI
10966 // with that operand
10967 Constant *op0 = C->getOperand(0);
10968 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10969 if (C->getOperand(i) != op0) {
10970 op0 = 0;
10971 break;
10972 }
10973 if (op0)
10974 return ReplaceInstUsesWith(EI, op0);
10975 }
10976
10977 // If extracting a specified index from the vector, see if we can recursively
10978 // find a previously computed scalar that was inserted into the vector.
10979 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10980 unsigned IndexVal = IdxC->getZExtValue();
10981 unsigned VectorWidth =
10982 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10983
10984 // If this is extracting an invalid index, turn this into undef, to avoid
10985 // crashing the code below.
10986 if (IndexVal >= VectorWidth)
10987 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10988
10989 // This instruction only demands the single element from the input vector.
10990 // If the input vector has a single use, simplify it based on this use
10991 // property.
10992 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10993 uint64_t UndefElts;
10994 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10995 1 << IndexVal,
10996 UndefElts)) {
10997 EI.setOperand(0, V);
10998 return &EI;
10999 }
11000 }
11001
11002 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11003 return ReplaceInstUsesWith(EI, Elt);
11004
11005 // If the this extractelement is directly using a bitcast from a vector of
11006 // the same number of elements, see if we can find the source element from
11007 // it. In this case, we will end up needing to bitcast the scalars.
11008 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11009 if (const VectorType *VT =
11010 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11011 if (VT->getNumElements() == VectorWidth)
11012 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11013 return new BitCastInst(Elt, EI.getType());
11014 }
11015 }
11016
11017 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11018 if (I->hasOneUse()) {
11019 // Push extractelement into predecessor operation if legal and
11020 // profitable to do so
11021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11022 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11023 if (CheapToScalarize(BO, isConstantElt)) {
11024 ExtractElementInst *newEI0 =
11025 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11026 EI.getName()+".lhs");
11027 ExtractElementInst *newEI1 =
11028 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11029 EI.getName()+".rhs");
11030 InsertNewInstBefore(newEI0, EI);
11031 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011032 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011033 }
11034 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011035 unsigned AS =
11036 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011037 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11038 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011039 GetElementPtrInst *GEP =
11040 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011041 InsertNewInstBefore(GEP, EI);
11042 return new LoadInst(GEP);
11043 }
11044 }
11045 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11046 // Extracting the inserted element?
11047 if (IE->getOperand(2) == EI.getOperand(1))
11048 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11049 // If the inserted and extracted elements are constants, they must not
11050 // be the same value, extract from the pre-inserted value instead.
11051 if (isa<Constant>(IE->getOperand(2)) &&
11052 isa<Constant>(EI.getOperand(1))) {
11053 AddUsesToWorkList(EI);
11054 EI.setOperand(0, IE->getOperand(0));
11055 return &EI;
11056 }
11057 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11058 // If this is extracting an element from a shufflevector, figure out where
11059 // it came from and extract from the appropriate input element instead.
11060 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11061 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11062 Value *Src;
11063 if (SrcIdx < SVI->getType()->getNumElements())
11064 Src = SVI->getOperand(0);
11065 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11066 SrcIdx -= SVI->getType()->getNumElements();
11067 Src = SVI->getOperand(1);
11068 } else {
11069 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11070 }
11071 return new ExtractElementInst(Src, SrcIdx);
11072 }
11073 }
11074 }
11075 return 0;
11076}
11077
11078/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11079/// elements from either LHS or RHS, return the shuffle mask and true.
11080/// Otherwise, return false.
11081static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11082 std::vector<Constant*> &Mask) {
11083 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11084 "Invalid CollectSingleShuffleElements");
11085 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11086
11087 if (isa<UndefValue>(V)) {
11088 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11089 return true;
11090 } else if (V == LHS) {
11091 for (unsigned i = 0; i != NumElts; ++i)
11092 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11093 return true;
11094 } else if (V == RHS) {
11095 for (unsigned i = 0; i != NumElts; ++i)
11096 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11097 return true;
11098 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11099 // If this is an insert of an extract from some other vector, include it.
11100 Value *VecOp = IEI->getOperand(0);
11101 Value *ScalarOp = IEI->getOperand(1);
11102 Value *IdxOp = IEI->getOperand(2);
11103
11104 if (!isa<ConstantInt>(IdxOp))
11105 return false;
11106 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11107
11108 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11109 // Okay, we can handle this if the vector we are insertinting into is
11110 // transitively ok.
11111 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11112 // If so, update the mask to reflect the inserted undef.
11113 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11114 return true;
11115 }
11116 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11117 if (isa<ConstantInt>(EI->getOperand(1)) &&
11118 EI->getOperand(0)->getType() == V->getType()) {
11119 unsigned ExtractedIdx =
11120 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11121
11122 // This must be extracting from either LHS or RHS.
11123 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11124 // Okay, we can handle this if the vector we are insertinting into is
11125 // transitively ok.
11126 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11127 // If so, update the mask to reflect the inserted value.
11128 if (EI->getOperand(0) == LHS) {
11129 Mask[InsertedIdx & (NumElts-1)] =
11130 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11131 } else {
11132 assert(EI->getOperand(0) == RHS);
11133 Mask[InsertedIdx & (NumElts-1)] =
11134 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11135
11136 }
11137 return true;
11138 }
11139 }
11140 }
11141 }
11142 }
11143 // TODO: Handle shufflevector here!
11144
11145 return false;
11146}
11147
11148/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11149/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11150/// that computes V and the LHS value of the shuffle.
11151static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11152 Value *&RHS) {
11153 assert(isa<VectorType>(V->getType()) &&
11154 (RHS == 0 || V->getType() == RHS->getType()) &&
11155 "Invalid shuffle!");
11156 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11157
11158 if (isa<UndefValue>(V)) {
11159 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11160 return V;
11161 } else if (isa<ConstantAggregateZero>(V)) {
11162 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11163 return V;
11164 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11165 // If this is an insert of an extract from some other vector, include it.
11166 Value *VecOp = IEI->getOperand(0);
11167 Value *ScalarOp = IEI->getOperand(1);
11168 Value *IdxOp = IEI->getOperand(2);
11169
11170 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11171 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11172 EI->getOperand(0)->getType() == V->getType()) {
11173 unsigned ExtractedIdx =
11174 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11175 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11176
11177 // Either the extracted from or inserted into vector must be RHSVec,
11178 // otherwise we'd end up with a shuffle of three inputs.
11179 if (EI->getOperand(0) == RHS || RHS == 0) {
11180 RHS = EI->getOperand(0);
11181 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11182 Mask[InsertedIdx & (NumElts-1)] =
11183 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11184 return V;
11185 }
11186
11187 if (VecOp == RHS) {
11188 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11189 // Everything but the extracted element is replaced with the RHS.
11190 for (unsigned i = 0; i != NumElts; ++i) {
11191 if (i != InsertedIdx)
11192 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11193 }
11194 return V;
11195 }
11196
11197 // If this insertelement is a chain that comes from exactly these two
11198 // vectors, return the vector and the effective shuffle.
11199 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11200 return EI->getOperand(0);
11201
11202 }
11203 }
11204 }
11205 // TODO: Handle shufflevector here!
11206
11207 // Otherwise, can't do anything fancy. Return an identity vector.
11208 for (unsigned i = 0; i != NumElts; ++i)
11209 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11210 return V;
11211}
11212
11213Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11214 Value *VecOp = IE.getOperand(0);
11215 Value *ScalarOp = IE.getOperand(1);
11216 Value *IdxOp = IE.getOperand(2);
11217
11218 // Inserting an undef or into an undefined place, remove this.
11219 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11220 ReplaceInstUsesWith(IE, VecOp);
11221
11222 // If the inserted element was extracted from some other vector, and if the
11223 // indexes are constant, try to turn this into a shufflevector operation.
11224 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11225 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11226 EI->getOperand(0)->getType() == IE.getType()) {
11227 unsigned NumVectorElts = IE.getType()->getNumElements();
11228 unsigned ExtractedIdx =
11229 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11230 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11231
11232 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11233 return ReplaceInstUsesWith(IE, VecOp);
11234
11235 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11236 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11237
11238 // If we are extracting a value from a vector, then inserting it right
11239 // back into the same place, just use the input vector.
11240 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11241 return ReplaceInstUsesWith(IE, VecOp);
11242
11243 // We could theoretically do this for ANY input. However, doing so could
11244 // turn chains of insertelement instructions into a chain of shufflevector
11245 // instructions, and right now we do not merge shufflevectors. As such,
11246 // only do this in a situation where it is clear that there is benefit.
11247 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11248 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11249 // the values of VecOp, except then one read from EIOp0.
11250 // Build a new shuffle mask.
11251 std::vector<Constant*> Mask;
11252 if (isa<UndefValue>(VecOp))
11253 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11254 else {
11255 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11256 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11257 NumVectorElts));
11258 }
11259 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11260 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11261 ConstantVector::get(Mask));
11262 }
11263
11264 // If this insertelement isn't used by some other insertelement, turn it
11265 // (and any insertelements it points to), into one big shuffle.
11266 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11267 std::vector<Constant*> Mask;
11268 Value *RHS = 0;
11269 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11270 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11271 // We now have a shuffle of LHS, RHS, Mask.
11272 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11273 }
11274 }
11275 }
11276
11277 return 0;
11278}
11279
11280
11281Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11282 Value *LHS = SVI.getOperand(0);
11283 Value *RHS = SVI.getOperand(1);
11284 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11285
11286 bool MadeChange = false;
11287
11288 // Undefined shuffle mask -> undefined value.
11289 if (isa<UndefValue>(SVI.getOperand(2)))
11290 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11291
11292 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11293 // the undef, change them to undefs.
11294 if (isa<UndefValue>(SVI.getOperand(1))) {
11295 // Scan to see if there are any references to the RHS. If so, replace them
11296 // with undef element refs and set MadeChange to true.
11297 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11298 if (Mask[i] >= e && Mask[i] != 2*e) {
11299 Mask[i] = 2*e;
11300 MadeChange = true;
11301 }
11302 }
11303
11304 if (MadeChange) {
11305 // Remap any references to RHS to use LHS.
11306 std::vector<Constant*> Elts;
11307 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11308 if (Mask[i] == 2*e)
11309 Elts.push_back(UndefValue::get(Type::Int32Ty));
11310 else
11311 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11312 }
11313 SVI.setOperand(2, ConstantVector::get(Elts));
11314 }
11315 }
11316
11317 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11318 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11319 if (LHS == RHS || isa<UndefValue>(LHS)) {
11320 if (isa<UndefValue>(LHS) && LHS == RHS) {
11321 // shuffle(undef,undef,mask) -> undef.
11322 return ReplaceInstUsesWith(SVI, LHS);
11323 }
11324
11325 // Remap any references to RHS to use LHS.
11326 std::vector<Constant*> Elts;
11327 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11328 if (Mask[i] >= 2*e)
11329 Elts.push_back(UndefValue::get(Type::Int32Ty));
11330 else {
11331 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11332 (Mask[i] < e && isa<UndefValue>(LHS)))
11333 Mask[i] = 2*e; // Turn into undef.
11334 else
11335 Mask[i] &= (e-1); // Force to LHS.
11336 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11337 }
11338 }
11339 SVI.setOperand(0, SVI.getOperand(1));
11340 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11341 SVI.setOperand(2, ConstantVector::get(Elts));
11342 LHS = SVI.getOperand(0);
11343 RHS = SVI.getOperand(1);
11344 MadeChange = true;
11345 }
11346
11347 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11348 bool isLHSID = true, isRHSID = true;
11349
11350 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11351 if (Mask[i] >= e*2) continue; // Ignore undef values.
11352 // Is this an identity shuffle of the LHS value?
11353 isLHSID &= (Mask[i] == i);
11354
11355 // Is this an identity shuffle of the RHS value?
11356 isRHSID &= (Mask[i]-e == i);
11357 }
11358
11359 // Eliminate identity shuffles.
11360 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11361 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11362
11363 // If the LHS is a shufflevector itself, see if we can combine it with this
11364 // one without producing an unusual shuffle. Here we are really conservative:
11365 // we are absolutely afraid of producing a shuffle mask not in the input
11366 // program, because the code gen may not be smart enough to turn a merged
11367 // shuffle into two specific shuffles: it may produce worse code. As such,
11368 // we only merge two shuffles if the result is one of the two input shuffle
11369 // masks. In this case, merging the shuffles just removes one instruction,
11370 // which we know is safe. This is good for things like turning:
11371 // (splat(splat)) -> splat.
11372 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11373 if (isa<UndefValue>(RHS)) {
11374 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11375
11376 std::vector<unsigned> NewMask;
11377 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11378 if (Mask[i] >= 2*e)
11379 NewMask.push_back(2*e);
11380 else
11381 NewMask.push_back(LHSMask[Mask[i]]);
11382
11383 // If the result mask is equal to the src shuffle or this shuffle mask, do
11384 // the replacement.
11385 if (NewMask == LHSMask || NewMask == Mask) {
11386 std::vector<Constant*> Elts;
11387 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11388 if (NewMask[i] >= e*2) {
11389 Elts.push_back(UndefValue::get(Type::Int32Ty));
11390 } else {
11391 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11392 }
11393 }
11394 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11395 LHSSVI->getOperand(1),
11396 ConstantVector::get(Elts));
11397 }
11398 }
11399 }
11400
11401 return MadeChange ? &SVI : 0;
11402}
11403
11404
11405
11406
11407/// TryToSinkInstruction - Try to move the specified instruction from its
11408/// current block into the beginning of DestBlock, which can only happen if it's
11409/// safe to move the instruction past all of the instructions between it and the
11410/// end of its block.
11411static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11412 assert(I->hasOneUse() && "Invariants didn't hold!");
11413
11414 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011415 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11416 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417
11418 // Do not sink alloca instructions out of the entry block.
11419 if (isa<AllocaInst>(I) && I->getParent() ==
11420 &DestBlock->getParent()->getEntryBlock())
11421 return false;
11422
11423 // We can only sink load instructions if there is nothing between the load and
11424 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011425 if (I->mayReadFromMemory()) {
11426 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011427 Scan != E; ++Scan)
11428 if (Scan->mayWriteToMemory())
11429 return false;
11430 }
11431
11432 BasicBlock::iterator InsertPos = DestBlock->begin();
11433 while (isa<PHINode>(InsertPos)) ++InsertPos;
11434
11435 I->moveBefore(InsertPos);
11436 ++NumSunkInst;
11437 return true;
11438}
11439
11440
11441/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11442/// all reachable code to the worklist.
11443///
11444/// This has a couple of tricks to make the code faster and more powerful. In
11445/// particular, we constant fold and DCE instructions as we go, to avoid adding
11446/// them to the worklist (this significantly speeds up instcombine on code where
11447/// many instructions are dead or constant). Additionally, if we find a branch
11448/// whose condition is a known constant, we only visit the reachable successors.
11449///
11450static void AddReachableCodeToWorklist(BasicBlock *BB,
11451 SmallPtrSet<BasicBlock*, 64> &Visited,
11452 InstCombiner &IC,
11453 const TargetData *TD) {
11454 std::vector<BasicBlock*> Worklist;
11455 Worklist.push_back(BB);
11456
11457 while (!Worklist.empty()) {
11458 BB = Worklist.back();
11459 Worklist.pop_back();
11460
11461 // We have now visited this block! If we've already been here, ignore it.
11462 if (!Visited.insert(BB)) continue;
11463
11464 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11465 Instruction *Inst = BBI++;
11466
11467 // DCE instruction if trivially dead.
11468 if (isInstructionTriviallyDead(Inst)) {
11469 ++NumDeadInst;
11470 DOUT << "IC: DCE: " << *Inst;
11471 Inst->eraseFromParent();
11472 continue;
11473 }
11474
11475 // ConstantProp instruction if trivially constant.
11476 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11477 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11478 Inst->replaceAllUsesWith(C);
11479 ++NumConstProp;
11480 Inst->eraseFromParent();
11481 continue;
11482 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011483
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011484 IC.AddToWorkList(Inst);
11485 }
11486
11487 // Recursively visit successors. If this is a branch or switch on a
11488 // constant, only visit the reachable successor.
11489 TerminatorInst *TI = BB->getTerminator();
11490 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11491 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11492 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011493 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011494 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011495 continue;
11496 }
11497 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11498 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11499 // See if this is an explicit destination.
11500 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11501 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011502 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011503 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011504 continue;
11505 }
11506
11507 // Otherwise it is the default destination.
11508 Worklist.push_back(SI->getSuccessor(0));
11509 continue;
11510 }
11511 }
11512
11513 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11514 Worklist.push_back(TI->getSuccessor(i));
11515 }
11516}
11517
11518bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11519 bool Changed = false;
11520 TD = &getAnalysis<TargetData>();
11521
11522 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11523 << F.getNameStr() << "\n");
11524
11525 {
11526 // Do a depth-first traversal of the function, populate the worklist with
11527 // the reachable instructions. Ignore blocks that are not reachable. Keep
11528 // track of which blocks we visit.
11529 SmallPtrSet<BasicBlock*, 64> Visited;
11530 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11531
11532 // Do a quick scan over the function. If we find any blocks that are
11533 // unreachable, remove any instructions inside of them. This prevents
11534 // the instcombine code from having to deal with some bad special cases.
11535 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11536 if (!Visited.count(BB)) {
11537 Instruction *Term = BB->getTerminator();
11538 while (Term != BB->begin()) { // Remove instrs bottom-up
11539 BasicBlock::iterator I = Term; --I;
11540
11541 DOUT << "IC: DCE: " << *I;
11542 ++NumDeadInst;
11543
11544 if (!I->use_empty())
11545 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11546 I->eraseFromParent();
11547 }
11548 }
11549 }
11550
11551 while (!Worklist.empty()) {
11552 Instruction *I = RemoveOneFromWorkList();
11553 if (I == 0) continue; // skip null values.
11554
11555 // Check to see if we can DCE the instruction.
11556 if (isInstructionTriviallyDead(I)) {
11557 // Add operands to the worklist.
11558 if (I->getNumOperands() < 4)
11559 AddUsesToWorkList(*I);
11560 ++NumDeadInst;
11561
11562 DOUT << "IC: DCE: " << *I;
11563
11564 I->eraseFromParent();
11565 RemoveFromWorkList(I);
11566 continue;
11567 }
11568
11569 // Instruction isn't dead, see if we can constant propagate it.
11570 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11571 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11572
11573 // Add operands to the worklist.
11574 AddUsesToWorkList(*I);
11575 ReplaceInstUsesWith(*I, C);
11576
11577 ++NumConstProp;
11578 I->eraseFromParent();
11579 RemoveFromWorkList(I);
11580 continue;
11581 }
11582
11583 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011584 // FIXME: Remove GetResultInst test when first class support for aggregates
11585 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011586 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011587 BasicBlock *BB = I->getParent();
11588 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11589 if (UserParent != BB) {
11590 bool UserIsSuccessor = false;
11591 // See if the user is one of our successors.
11592 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11593 if (*SI == UserParent) {
11594 UserIsSuccessor = true;
11595 break;
11596 }
11597
11598 // If the user is one of our immediate successors, and if that successor
11599 // only has us as a predecessors (we'd have to split the critical edge
11600 // otherwise), we can keep going.
11601 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11602 next(pred_begin(UserParent)) == pred_end(UserParent))
11603 // Okay, the CFG is simple enough, try to sink this instruction.
11604 Changed |= TryToSinkInstruction(I, UserParent);
11605 }
11606 }
11607
11608 // Now that we have an instruction, try combining it to simplify it...
11609#ifndef NDEBUG
11610 std::string OrigI;
11611#endif
11612 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11613 if (Instruction *Result = visit(*I)) {
11614 ++NumCombined;
11615 // Should we replace the old instruction with a new one?
11616 if (Result != I) {
11617 DOUT << "IC: Old = " << *I
11618 << " New = " << *Result;
11619
11620 // Everything uses the new instruction now.
11621 I->replaceAllUsesWith(Result);
11622
11623 // Push the new instruction and any users onto the worklist.
11624 AddToWorkList(Result);
11625 AddUsersToWorkList(*Result);
11626
11627 // Move the name to the new instruction first.
11628 Result->takeName(I);
11629
11630 // Insert the new instruction into the basic block...
11631 BasicBlock *InstParent = I->getParent();
11632 BasicBlock::iterator InsertPos = I;
11633
11634 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11635 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11636 ++InsertPos;
11637
11638 InstParent->getInstList().insert(InsertPos, Result);
11639
11640 // Make sure that we reprocess all operands now that we reduced their
11641 // use counts.
11642 AddUsesToWorkList(*I);
11643
11644 // Instructions can end up on the worklist more than once. Make sure
11645 // we do not process an instruction that has been deleted.
11646 RemoveFromWorkList(I);
11647
11648 // Erase the old instruction.
11649 InstParent->getInstList().erase(I);
11650 } else {
11651#ifndef NDEBUG
11652 DOUT << "IC: Mod = " << OrigI
11653 << " New = " << *I;
11654#endif
11655
11656 // If the instruction was modified, it's possible that it is now dead.
11657 // if so, remove it.
11658 if (isInstructionTriviallyDead(I)) {
11659 // Make sure we process all operands now that we are reducing their
11660 // use counts.
11661 AddUsesToWorkList(*I);
11662
11663 // Instructions may end up in the worklist more than once. Erase all
11664 // occurrences of this instruction.
11665 RemoveFromWorkList(I);
11666 I->eraseFromParent();
11667 } else {
11668 AddToWorkList(I);
11669 AddUsersToWorkList(*I);
11670 }
11671 }
11672 Changed = true;
11673 }
11674 }
11675
11676 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011677
11678 // Do an explicit clear, this shrinks the map if needed.
11679 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011680 return Changed;
11681}
11682
11683
11684bool InstCombiner::runOnFunction(Function &F) {
11685 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11686
11687 bool EverMadeChange = false;
11688
11689 // Iterate while there is work to do.
11690 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011691 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011692 EverMadeChange = true;
11693 return EverMadeChange;
11694}
11695
11696FunctionPass *llvm::createInstructionCombiningPass() {
11697 return new InstCombiner();
11698}
11699