blob: 7b974731b1b05a6d013aa20024f15d1d63d66b29 [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
11// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
13//
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>
60#include <sstream>
61using namespace llvm;
62using namespace llvm::PatternMatch;
63
64STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70namespace {
71 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
74 // Worklist of all of the instructions that need to be simplified.
75 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
77 TargetData *TD;
78 bool MustPreserveLCSSA;
79 public:
80 static char ID; // Pass identification, replacement for typeid
81 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
107
108
109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
113 void AddUsersToWorkList(Value &I) {
114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115 UI != UE; ++UI)
116 AddToWorkList(cast<Instruction>(*UI));
117 }
118
119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125 AddToWorkList(Op);
126 }
127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139 AddToWorkList(Op);
140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
146
147 public:
148 virtual bool runOnFunction(Function &F);
149
150 bool DoOneIteration(Function &F, unsigned ItNum);
151
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<TargetData>();
154 AU.addPreservedID(LCSSAID);
155 AU.setPreservesCFG();
156 }
157
158 TargetData &getTargetData() const { return *TD; }
159
160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
164 // I - Change was made, I is still valid, I may be dead though
165 // otherwise - Change was made, replace I with returned instruction
166 //
167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
195
196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199 BinaryOperator &I);
200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
202 Instruction *commonPointerCastTransforms(CastInst &CI);
203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 Instruction *visitBitCast(BitCastInst &CI);
215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
217 Instruction *visitSelectInst(SelectInst &CI);
218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222 Instruction *visitAllocationInst(AllocationInst &AI);
223 Instruction *visitFreeInst(FreeInst &FI);
224 Instruction *visitLoadInst(LoadInst &LI);
225 Instruction *visitStoreInst(StoreInst &SI);
226 Instruction *visitBranchInst(BranchInst &BI);
227 Instruction *visitSwitchInst(SwitchInst &SI);
228 Instruction *visitInsertElementInst(InsertElementInst &IE);
229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232 // visitInstruction - Specify what to return for unhandled instructions...
233 Instruction *visitInstruction(Instruction &I) { return 0; }
234
235 private:
236 Instruction *visitCallSite(CallSite CS);
237 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000239 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240 bool DoXform = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241
242 public:
243 // InsertNewInstBefore - insert an instruction New before instruction Old
244 // in the program. Add the new instruction to the worklist.
245 //
246 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
247 assert(New && New->getParent() == 0 &&
248 "New instruction already inserted into a basic block!");
249 BasicBlock *BB = Old.getParent();
250 BB->getInstList().insert(&Old, New); // Insert inst
251 AddToWorkList(New);
252 return New;
253 }
254
255 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256 /// This also adds the cast to the worklist. Finally, this returns the
257 /// cast.
258 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
259 Instruction &Pos) {
260 if (V->getType() == Ty) return V;
261
262 if (Constant *CV = dyn_cast<Constant>(V))
263 return ConstantExpr::getCast(opc, CV, Ty);
264
265 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
266 AddToWorkList(C);
267 return C;
268 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000269
270 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
272 }
273
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
275 // ReplaceInstUsesWith - This method is to be used when an instruction is
276 // found to be dead, replacable with another preexisting expression. Here
277 // we add all uses of I to the worklist, replace all uses of I with the new
278 // value, then return I, so that the inst combiner will know that I was
279 // modified.
280 //
281 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
282 AddUsersToWorkList(I); // Add all modified instrs to worklist
283 if (&I != V) {
284 I.replaceAllUsesWith(V);
285 return &I;
286 } else {
287 // If we are replacing the instruction with itself, this must be in a
288 // segment of unreachable code, so just clobber the instruction.
289 I.replaceAllUsesWith(UndefValue::get(I.getType()));
290 return &I;
291 }
292 }
293
294 // UpdateValueUsesWith - This method is to be used when an value is
295 // found to be replacable with another preexisting expression or was
296 // updated. Here we add all uses of I to the worklist, replace all uses of
297 // I with the new value (unless the instruction was just updated), then
298 // return true, so that the inst combiner will know that I was modified.
299 //
300 bool UpdateValueUsesWith(Value *Old, Value *New) {
301 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
302 if (Old != New)
303 Old->replaceAllUsesWith(New);
304 if (Instruction *I = dyn_cast<Instruction>(Old))
305 AddToWorkList(I);
306 if (Instruction *I = dyn_cast<Instruction>(New))
307 AddToWorkList(I);
308 return true;
309 }
310
311 // EraseInstFromFunction - When dealing with an instruction that has side
312 // effects or produces a void value, we can't rely on DCE to delete the
313 // instruction. Instead, visit methods should return the value returned by
314 // this function.
315 Instruction *EraseInstFromFunction(Instruction &I) {
316 assert(I.use_empty() && "Cannot erase instruction that is used!");
317 AddUsesToWorkList(I);
318 RemoveFromWorkList(&I);
319 I.eraseFromParent();
320 return 0; // Don't do anything with FI
321 }
322
323 private:
324 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325 /// InsertBefore instruction. This is specialized a bit to avoid inserting
326 /// casts that are known to not do anything...
327 ///
328 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329 Value *V, const Type *DestTy,
330 Instruction *InsertBefore);
331
332 /// SimplifyCommutative - This performs a few simplifications for
333 /// commutative operators.
334 bool SimplifyCommutative(BinaryOperator &I);
335
336 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337 /// most-complex to least-complex order.
338 bool SimplifyCompare(CmpInst &I);
339
340 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341 /// on the demanded bits.
342 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
343 APInt& KnownZero, APInt& KnownOne,
344 unsigned Depth = 0);
345
346 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347 uint64_t &UndefElts, unsigned Depth = 0);
348
349 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350 // PHI node as operand #0, see if we can fold the instruction into the PHI
351 // (which is only possible if all operands to the PHI are constants).
352 Instruction *FoldOpIntoPhi(Instruction &I);
353
354 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 // operator and they all are only used by the PHI, PHI together their
356 // inputs, and do the operation once, to the result of the PHI.
357 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
358 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
359
360
361 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362 ConstantInt *AndRHS, BinaryOperator &TheAnd);
363
364 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
365 bool isSub, Instruction &I);
366 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
367 bool isSigned, bool Inside, Instruction &IB);
368 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
369 Instruction *MatchBSwap(BinaryOperator &I);
370 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000371 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
372
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373
374 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000375
376 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
377 APInt& KnownOne, unsigned Depth = 0);
378 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
379 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
380 unsigned CastOpc,
381 int &NumCastsRemoved);
382 unsigned GetOrEnforceKnownAlignment(Value *V,
383 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 };
385
386 char InstCombiner::ID = 0;
387 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
388}
389
390// getComplexity: Assign a complexity or rank value to LLVM Values...
391// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
392static unsigned getComplexity(Value *V) {
393 if (isa<Instruction>(V)) {
394 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
395 return 3;
396 return 4;
397 }
398 if (isa<Argument>(V)) return 3;
399 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
400}
401
402// isOnlyUse - Return true if this instruction will be deleted if we stop using
403// it.
404static bool isOnlyUse(Value *V) {
405 return V->hasOneUse() || isa<Constant>(V);
406}
407
408// getPromotedType - Return the specified type promoted as it would be to pass
409// though a va_arg area...
410static const Type *getPromotedType(const Type *Ty) {
411 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
412 if (ITy->getBitWidth() < 32)
413 return Type::Int32Ty;
414 }
415 return Ty;
416}
417
418/// getBitCastOperand - If the specified operand is a CastInst or a constant
419/// expression bitcast, return the operand value, otherwise return null.
420static Value *getBitCastOperand(Value *V) {
421 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
422 return I->getOperand(0);
423 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
424 if (CE->getOpcode() == Instruction::BitCast)
425 return CE->getOperand(0);
426 return 0;
427}
428
429/// This function is a wrapper around CastInst::isEliminableCastPair. It
430/// simply extracts arguments and returns what that function returns.
431static Instruction::CastOps
432isEliminableCastPair(
433 const CastInst *CI, ///< The first cast instruction
434 unsigned opcode, ///< The opcode of the second cast instruction
435 const Type *DstTy, ///< The target type for the second cast instruction
436 TargetData *TD ///< The target data for pointer size
437) {
438
439 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
440 const Type *MidTy = CI->getType(); // B from above
441
442 // Get the opcodes of the two Cast instructions
443 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
444 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
445
446 return Instruction::CastOps(
447 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
448 DstTy, TD->getIntPtrType()));
449}
450
451/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
452/// in any code being generated. It does not require codegen if V is simple
453/// enough or if the cast can be folded into other casts.
454static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
455 const Type *Ty, TargetData *TD) {
456 if (V->getType() == Ty || isa<Constant>(V)) return false;
457
458 // If this is another cast that can be eliminated, it isn't codegen either.
459 if (const CastInst *CI = dyn_cast<CastInst>(V))
460 if (isEliminableCastPair(CI, opcode, Ty, TD))
461 return false;
462 return true;
463}
464
465/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
466/// InsertBefore instruction. This is specialized a bit to avoid inserting
467/// casts that are known to not do anything...
468///
469Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
470 Value *V, const Type *DestTy,
471 Instruction *InsertBefore) {
472 if (V->getType() == DestTy) return V;
473 if (Constant *C = dyn_cast<Constant>(V))
474 return ConstantExpr::getCast(opcode, C, DestTy);
475
476 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
477}
478
479// SimplifyCommutative - This performs a few simplifications for commutative
480// operators:
481//
482// 1. Order operands such that they are listed from right (least complex) to
483// left (most complex). This puts constants before unary operators before
484// binary operators.
485//
486// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
487// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
488//
489bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
490 bool Changed = false;
491 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
492 Changed = !I.swapOperands();
493
494 if (!I.isAssociative()) return Changed;
495 Instruction::BinaryOps Opcode = I.getOpcode();
496 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
497 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
498 if (isa<Constant>(I.getOperand(1))) {
499 Constant *Folded = ConstantExpr::get(I.getOpcode(),
500 cast<Constant>(I.getOperand(1)),
501 cast<Constant>(Op->getOperand(1)));
502 I.setOperand(0, Op->getOperand(0));
503 I.setOperand(1, Folded);
504 return true;
505 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
506 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
507 isOnlyUse(Op) && isOnlyUse(Op1)) {
508 Constant *C1 = cast<Constant>(Op->getOperand(1));
509 Constant *C2 = cast<Constant>(Op1->getOperand(1));
510
511 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
513 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
514 Op1->getOperand(0),
515 Op1->getName(), &I);
516 AddToWorkList(New);
517 I.setOperand(0, New);
518 I.setOperand(1, Folded);
519 return true;
520 }
521 }
522 return Changed;
523}
524
525/// SimplifyCompare - For a CmpInst this function just orders the operands
526/// so that theyare listed from right (least complex) to left (most complex).
527/// This puts constants before unary operators before binary operators.
528bool InstCombiner::SimplifyCompare(CmpInst &I) {
529 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
530 return false;
531 I.swapOperands();
532 // Compare instructions are not associative so there's nothing else we can do.
533 return true;
534}
535
536// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
537// if the LHS is a constant zero (which is the 'negate' form).
538//
539static inline Value *dyn_castNegVal(Value *V) {
540 if (BinaryOperator::isNeg(V))
541 return BinaryOperator::getNegArgument(V);
542
543 // Constants can be considered to be negated values if they can be folded.
544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545 return ConstantExpr::getNeg(C);
546 return 0;
547}
548
549static inline Value *dyn_castNotVal(Value *V) {
550 if (BinaryOperator::isNot(V))
551 return BinaryOperator::getNotArgument(V);
552
553 // Constants can be considered to be not'ed values...
554 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
555 return ConstantInt::get(~C->getValue());
556 return 0;
557}
558
559// dyn_castFoldableMul - If this value is a multiply that can be folded into
560// other computations (because it has a constant operand), return the
561// non-constant operand of the multiply, and set CST to point to the multiplier.
562// Otherwise, return null.
563//
564static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
565 if (V->hasOneUse() && V->getType()->isInteger())
566 if (Instruction *I = dyn_cast<Instruction>(V)) {
567 if (I->getOpcode() == Instruction::Mul)
568 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
569 return I->getOperand(0);
570 if (I->getOpcode() == Instruction::Shl)
571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
572 // The multiplier is really 1 << CST.
573 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
574 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
575 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
576 return I->getOperand(0);
577 }
578 }
579 return 0;
580}
581
582/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
583/// expression, return it.
584static User *dyn_castGetElementPtr(Value *V) {
585 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
587 if (CE->getOpcode() == Instruction::GetElementPtr)
588 return cast<User>(V);
589 return false;
590}
591
Dan Gohman2d648bb2008-04-10 18:43:06 +0000592/// getOpcode - If this is an Instruction or a ConstantExpr, return the
593/// opcode value. Otherwise return UserOp1.
594static unsigned getOpcode(User *U) {
595 if (Instruction *I = dyn_cast<Instruction>(U))
596 return I->getOpcode();
597 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
598 return CE->getOpcode();
599 // Use UserOp1 to mean there's no opcode.
600 return Instruction::UserOp1;
601}
602
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603/// AddOne - Add one to a ConstantInt
604static ConstantInt *AddOne(ConstantInt *C) {
605 APInt Val(C->getValue());
606 return ConstantInt::get(++Val);
607}
608/// SubOne - Subtract one from a ConstantInt
609static ConstantInt *SubOne(ConstantInt *C) {
610 APInt Val(C->getValue());
611 return ConstantInt::get(--Val);
612}
613/// Add - Add two ConstantInts together
614static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
615 return ConstantInt::get(C1->getValue() + C2->getValue());
616}
617/// And - Bitwise AND two ConstantInts together
618static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
619 return ConstantInt::get(C1->getValue() & C2->getValue());
620}
621/// Subtract - Subtract one ConstantInt from another
622static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
623 return ConstantInt::get(C1->getValue() - C2->getValue());
624}
625/// Multiply - Multiply two ConstantInts together
626static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() * C2->getValue());
628}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000629/// MultiplyOverflows - True if the multiply can not be expressed in an int
630/// this size.
631static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
632 uint32_t W = C1->getBitWidth();
633 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
634 if (sign) {
635 LHSExt.sext(W * 2);
636 RHSExt.sext(W * 2);
637 } else {
638 LHSExt.zext(W * 2);
639 RHSExt.zext(W * 2);
640 }
641
642 APInt MulExt = LHSExt * RHSExt;
643
644 if (sign) {
645 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
646 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
647 return MulExt.slt(Min) || MulExt.sgt(Max);
648 } else
649 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
650}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651
652/// ComputeMaskedBits - Determine which of the bits specified in Mask are
653/// known to be either zero or one and return them in the KnownZero/KnownOne
654/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
655/// processing.
656/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
657/// we cannot optimize based on the assumption that it is zero without changing
658/// it to be an explicit zero. If we don't change it to zero, other code could
659/// optimized based on the contradictory assumption that it is non-zero.
660/// Because instcombine aggressively folds operations with undef args anyway,
661/// this won't lose us code quality.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000662void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
663 APInt& KnownZero, APInt& KnownOne,
664 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 assert(V && "No Value?");
666 assert(Depth <= 6 && "Limit Search Depth");
667 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000668 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
669 "Not integer or pointer type!");
670 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
671 (!isa<IntegerType>(V->getType()) ||
672 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 KnownZero.getBitWidth() == BitWidth &&
674 KnownOne.getBitWidth() == BitWidth &&
675 "V, Mask, KnownOne and KnownZero should have same BitWidth");
676 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
677 // We know all of the bits for a constant!
678 KnownOne = CI->getValue() & Mask;
679 KnownZero = ~KnownOne & Mask;
680 return;
681 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000682 // Null is all-zeros.
683 if (isa<ConstantPointerNull>(V)) {
684 KnownOne.clear();
685 KnownZero = Mask;
686 return;
687 }
688 // The address of an aligned GlobalValue has trailing zeros.
689 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
690 unsigned Align = GV->getAlignment();
691 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
692 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
693 if (Align > 0)
694 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
695 CountTrailingZeros_32(Align));
696 else
697 KnownZero.clear();
698 KnownOne.clear();
699 return;
700 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701
702 if (Depth == 6 || Mask == 0)
703 return; // Limit search depth.
704
Dan Gohman2d648bb2008-04-10 18:43:06 +0000705 User *I = dyn_cast<User>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 if (!I) return;
707
708 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
709 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
710
Dan Gohman2d648bb2008-04-10 18:43:06 +0000711 switch (getOpcode(I)) {
712 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 case Instruction::And: {
714 // If either the LHS or the RHS are Zero, the result is zero.
715 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
716 APInt Mask2(Mask & ~KnownZero);
717 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
720
721 // Output known-1 bits are only known if set in both the LHS & RHS.
722 KnownOne &= KnownOne2;
723 // Output known-0 are known to be clear if zero in either the LHS | RHS.
724 KnownZero |= KnownZero2;
725 return;
726 }
727 case Instruction::Or: {
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
729 APInt Mask2(Mask & ~KnownOne);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-0 bits are only known if clear in both the LHS & RHS.
735 KnownZero &= KnownZero2;
736 // Output known-1 are known to be set if set in either the LHS | RHS.
737 KnownOne |= KnownOne2;
738 return;
739 }
740 case Instruction::Xor: {
741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
745
746 // Output known-0 bits are known if clear or set in both the LHS & RHS.
747 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
748 // Output known-1 are known to be set if set in only one of the LHS, RHS.
749 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
750 KnownZero = KnownZeroOut;
751 return;
752 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000753 case Instruction::Mul: {
754 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
755 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
756 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
759
760 // If low bits are zero in either operand, output low known-0 bits.
761 // More trickiness is possible, but this is sufficient for the
762 // interesting case of alignment computation.
763 KnownOne.clear();
764 unsigned TrailZ = KnownZero.countTrailingOnes() +
765 KnownZero2.countTrailingOnes();
766 TrailZ = std::min(TrailZ, BitWidth);
767 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
768 KnownZero &= Mask;
769 return;
770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 case Instruction::Select:
772 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
773 ComputeMaskedBits(I->getOperand(1), Mask, 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 // Only known if known in both the LHS and RHS.
778 KnownOne &= KnownOne2;
779 KnownZero &= KnownZero2;
780 return;
781 case Instruction::FPTrunc:
782 case Instruction::FPExt:
783 case Instruction::FPToUI:
784 case Instruction::FPToSI:
785 case Instruction::SIToFP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 case Instruction::UIToFP:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000787 return; // Can't work with floating point.
788 case Instruction::PtrToInt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 case Instruction::IntToPtr:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000790 // We can't handle these if we don't know the pointer size.
791 if (!TD) return;
792 // Fall through and handle them the same as zext/trunc.
793 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 case Instruction::Trunc: {
795 // All these have integer operands
Dan Gohman2d648bb2008-04-10 18:43:06 +0000796 const Type *SrcTy = I->getOperand(0)->getType();
797 uint32_t SrcBitWidth = TD ?
798 TD->getTypeSizeInBits(SrcTy) :
799 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000801 MaskIn.zextOrTrunc(SrcBitWidth);
802 KnownZero.zextOrTrunc(SrcBitWidth);
803 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000805 KnownZero.zextOrTrunc(BitWidth);
806 KnownOne.zextOrTrunc(BitWidth);
807 // Any top bits are known to be zero.
808 if (BitWidth > SrcBitWidth)
809 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 return;
811 }
812 case Instruction::BitCast: {
813 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000814 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
816 return;
817 }
818 break;
819 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 case Instruction::SExt: {
821 // Compute the bits in the result that are not present in the input.
822 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
823 uint32_t SrcBitWidth = SrcTy->getBitWidth();
824
825 APInt MaskIn(Mask);
826 MaskIn.trunc(SrcBitWidth);
827 KnownZero.trunc(SrcBitWidth);
828 KnownOne.trunc(SrcBitWidth);
829 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
830 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
831 KnownZero.zext(BitWidth);
832 KnownOne.zext(BitWidth);
833
834 // If the sign bit of the input is known set or clear, then we know the
835 // top bits of the result.
836 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
837 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
838 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
839 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
840 return;
841 }
842 case Instruction::Shl:
843 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
844 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
845 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
846 APInt Mask2(Mask.lshr(ShiftAmt));
847 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
848 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
849 KnownZero <<= ShiftAmt;
850 KnownOne <<= ShiftAmt;
851 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
852 return;
853 }
854 break;
855 case Instruction::LShr:
856 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
857 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
858 // Compute the new bits that are at the top now.
859 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
860
861 // Unsigned shift right.
862 APInt Mask2(Mask.shl(ShiftAmt));
863 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
864 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
865 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
866 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
867 // high bits known zero.
868 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
869 return;
870 }
871 break;
872 case Instruction::AShr:
873 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
874 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
875 // Compute the new bits that are at the top now.
876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
877
878 // Signed shift right.
879 APInt Mask2(Mask.shl(ShiftAmt));
880 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
881 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
882 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
883 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
884
885 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
886 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
887 KnownZero |= HighBits;
888 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
889 KnownOne |= HighBits;
890 return;
891 }
892 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000893 case Instruction::Sub: {
894 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
895 // We know that the top bits of C-X are clear if X contains less bits
896 // than C (i.e. no wrap-around can happen). For example, 20-X is
897 // positive if we can prove that X is >= 0 and < 16.
898 if (!CLHS->getValue().isNegative()) {
899 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
900 // NLZ can't be BitWidth with no sign bit
901 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
902 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
903
904 // If all of the MaskV bits are known to be zero, then we know the output
905 // top bits are zero, because we now know that the output is from [0-C].
906 if ((KnownZero & MaskV) == MaskV) {
907 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
908 // Top bits known zero.
909 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
910 KnownOne = APInt(BitWidth, 0); // No one bits known.
911 } else {
912 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
913 }
914 return;
915 }
916 }
917 }
918 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000919 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
922 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
923 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
924 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
925
926 // Output known-0 bits are known if clear or set in both the low clear bits
927 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
928 // low 3 bits clear.
929 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
930 KnownZero2.countTrailingOnes());
931
932 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
933 KnownOne = APInt(BitWidth, 0);
934 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000935 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000936 case Instruction::SRem:
937 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
938 APInt RA = Rem->getValue();
939 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
940 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
941 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
942 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
943
944 // The sign of a remainder is equal to the sign of the first
945 // operand (zero being positive).
946 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
947 KnownZero2 |= ~LowBits;
948 else if (KnownOne2[BitWidth-1])
949 KnownOne2 |= ~LowBits;
950
951 KnownZero |= KnownZero2 & Mask;
952 KnownOne |= KnownOne2 & Mask;
953
954 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
955 }
956 }
957 break;
958 case Instruction::URem:
959 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
960 APInt RA = Rem->getValue();
961 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
962 APInt LowBits = (RA - 1) | RA;
963 APInt Mask2 = LowBits & Mask;
964 KnownZero |= ~LowBits & Mask;
965 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 }
968 } else {
969 // Since the result is less than or equal to RHS, any leading zero bits
970 // in RHS must also exist in the result.
971 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000972 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
973 Depth+1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000974
975 uint32_t Leaders = KnownZero2.countLeadingOnes();
976 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
977 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
978 }
979 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000980
981 case Instruction::Alloca:
982 case Instruction::Malloc: {
983 AllocationInst *AI = cast<AllocationInst>(V);
984 unsigned Align = AI->getAlignment();
985 if (Align == 0 && TD) {
986 if (isa<AllocaInst>(AI))
987 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
988 else if (isa<MallocInst>(AI)) {
989 // Malloc returns maximally aligned memory.
990 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
991 Align =
992 std::max(Align,
993 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
994 Align =
995 std::max(Align,
996 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
997 }
998 }
999
1000 if (Align > 0)
1001 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1002 CountTrailingZeros_32(Align));
1003 break;
1004 }
1005 case Instruction::GetElementPtr: {
1006 // Analyze all of the subscripts of this getelementptr instruction
1007 // to determine if we can prove known low zero bits.
1008 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1009 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1010 ComputeMaskedBits(I->getOperand(0), LocalMask,
1011 LocalKnownZero, LocalKnownOne, Depth+1);
1012 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1013
1014 gep_type_iterator GTI = gep_type_begin(I);
1015 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1016 Value *Index = I->getOperand(i);
1017 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1018 // Handle struct member offset arithmetic.
1019 if (!TD) return;
1020 const StructLayout *SL = TD->getStructLayout(STy);
1021 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1022 uint64_t Offset = SL->getElementOffset(Idx);
1023 TrailZ = std::min(TrailZ,
1024 CountTrailingZeros_64(Offset));
1025 } else {
1026 // Handle array index arithmetic.
1027 const Type *IndexedTy = GTI.getIndexedType();
1028 if (!IndexedTy->isSized()) return;
1029 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1030 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1031 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1032 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1033 ComputeMaskedBits(Index, LocalMask,
1034 LocalKnownZero, LocalKnownOne, Depth+1);
1035 TrailZ = std::min(TrailZ,
1036 CountTrailingZeros_64(TypeSize) +
1037 LocalKnownZero.countTrailingOnes());
1038 }
1039 }
1040
1041 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1042 break;
1043 }
1044 case Instruction::PHI: {
1045 PHINode *P = cast<PHINode>(I);
1046 // Handle the case of a simple two-predecessor recurrence PHI.
1047 // There's a lot more that could theoretically be done here, but
1048 // this is sufficient to catch some interesting cases.
1049 if (P->getNumIncomingValues() == 2) {
1050 for (unsigned i = 0; i != 2; ++i) {
1051 Value *L = P->getIncomingValue(i);
1052 Value *R = P->getIncomingValue(!i);
1053 User *LU = dyn_cast<User>(L);
1054 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1055 // Check for operations that have the property that if
1056 // both their operands have low zero bits, the result
1057 // will have low zero bits.
1058 if (Opcode == Instruction::Add ||
1059 Opcode == Instruction::Sub ||
1060 Opcode == Instruction::And ||
1061 Opcode == Instruction::Or ||
1062 Opcode == Instruction::Mul) {
1063 Value *LL = LU->getOperand(0);
1064 Value *LR = LU->getOperand(1);
1065 // Find a recurrence.
1066 if (LL == I)
1067 L = LR;
1068 else if (LR == I)
1069 L = LL;
1070 else
1071 break;
1072 // Ok, we have a PHI of the form L op= R. Check for low
1073 // zero bits.
1074 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1075 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1076 Mask2 = APInt::getLowBitsSet(BitWidth,
1077 KnownZero2.countTrailingOnes());
1078 KnownOne2.clear();
1079 KnownZero2.clear();
1080 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1081 KnownZero = Mask &
1082 APInt::getLowBitsSet(BitWidth,
1083 KnownZero2.countTrailingOnes());
1084 break;
1085 }
1086 }
1087 }
1088 break;
1089 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 }
1091}
1092
1093/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1094/// this predicate to simplify operations downstream. Mask is known to be zero
1095/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001096bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1097 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1099 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1100 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1101 return (KnownZero & Mask) == Mask;
1102}
1103
1104/// ShrinkDemandedConstant - Check to see if the specified operand of the
1105/// specified instruction is a constant integer. If so, check to see if there
1106/// are any bits set in the constant that are not demanded. If so, shrink the
1107/// constant and return true.
1108static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1109 APInt Demanded) {
1110 assert(I && "No instruction?");
1111 assert(OpNo < I->getNumOperands() && "Operand index too large");
1112
1113 // If the operand is not a constant integer, nothing to do.
1114 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1115 if (!OpC) return false;
1116
1117 // If there are no bits set that aren't demanded, nothing to do.
1118 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1119 if ((~Demanded & OpC->getValue()) == 0)
1120 return false;
1121
1122 // This instruction is producing bits that are not demanded. Shrink the RHS.
1123 Demanded &= OpC->getValue();
1124 I->setOperand(OpNo, ConstantInt::get(Demanded));
1125 return true;
1126}
1127
1128// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1129// set of known zero and one bits, compute the maximum and minimum values that
1130// could have the specified known zero and known one bits, returning them in
1131// min/max.
1132static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1133 const APInt& KnownZero,
1134 const APInt& KnownOne,
1135 APInt& Min, APInt& Max) {
1136 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1137 assert(KnownZero.getBitWidth() == BitWidth &&
1138 KnownOne.getBitWidth() == BitWidth &&
1139 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1140 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1141 APInt UnknownBits = ~(KnownZero|KnownOne);
1142
1143 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1144 // bit if it is unknown.
1145 Min = KnownOne;
1146 Max = KnownOne|UnknownBits;
1147
1148 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1149 Min.set(BitWidth-1);
1150 Max.clear(BitWidth-1);
1151 }
1152}
1153
1154// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1155// a set of known zero and one bits, compute the maximum and minimum values that
1156// could have the specified known zero and known one bits, returning them in
1157// min/max.
1158static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001159 const APInt &KnownZero,
1160 const APInt &KnownOne,
1161 APInt &Min, APInt &Max) {
1162 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 assert(KnownZero.getBitWidth() == BitWidth &&
1164 KnownOne.getBitWidth() == BitWidth &&
1165 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1166 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1167 APInt UnknownBits = ~(KnownZero|KnownOne);
1168
1169 // The minimum value is when the unknown bits are all zeros.
1170 Min = KnownOne;
1171 // The maximum value is when the unknown bits are all ones.
1172 Max = KnownOne|UnknownBits;
1173}
1174
1175/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1176/// value based on the demanded bits. When this function is called, it is known
1177/// that only the bits set in DemandedMask of the result of V are ever used
1178/// downstream. Consequently, depending on the mask and V, it may be possible
1179/// to replace V with a constant or one of its operands. In such cases, this
1180/// function does the replacement and returns true. In all other cases, it
1181/// returns false after analyzing the expression and setting KnownOne and known
1182/// to be one in the expression. KnownZero contains all the bits that are known
1183/// to be zero in the expression. These are provided to potentially allow the
1184/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1185/// the expression. KnownOne and KnownZero always follow the invariant that
1186/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1187/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1188/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1189/// and KnownOne must all be the same.
1190bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1191 APInt& KnownZero, APInt& KnownOne,
1192 unsigned Depth) {
1193 assert(V != 0 && "Null pointer of Value???");
1194 assert(Depth <= 6 && "Limit Search Depth");
1195 uint32_t BitWidth = DemandedMask.getBitWidth();
1196 const IntegerType *VTy = cast<IntegerType>(V->getType());
1197 assert(VTy->getBitWidth() == BitWidth &&
1198 KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 "Value *V, DemandedMask, KnownZero and KnownOne \
1201 must have same BitWidth");
1202 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1203 // We know all of the bits for a constant!
1204 KnownOne = CI->getValue() & DemandedMask;
1205 KnownZero = ~KnownOne & DemandedMask;
1206 return false;
1207 }
1208
1209 KnownZero.clear();
1210 KnownOne.clear();
1211 if (!V->hasOneUse()) { // Other users may use these bits.
1212 if (Depth != 0) { // Not at the root.
1213 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1214 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1215 return false;
1216 }
1217 // If this is the root being simplified, allow it to have multiple uses,
1218 // just set the DemandedMask to all bits.
1219 DemandedMask = APInt::getAllOnesValue(BitWidth);
1220 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1221 if (V != UndefValue::get(VTy))
1222 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1223 return false;
1224 } else if (Depth == 6) { // Limit search depth.
1225 return false;
1226 }
1227
1228 Instruction *I = dyn_cast<Instruction>(V);
1229 if (!I) return false; // Only analyze instructions.
1230
1231 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1232 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1233 switch (I->getOpcode()) {
1234 default: break;
1235 case Instruction::And:
1236 // If either the LHS or the RHS are Zero, the result is zero.
1237 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1238 RHSKnownZero, RHSKnownOne, Depth+1))
1239 return true;
1240 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1241 "Bits known to be one AND zero?");
1242
1243 // If something is known zero on the RHS, the bits aren't demanded on the
1244 // LHS.
1245 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1246 LHSKnownZero, LHSKnownOne, Depth+1))
1247 return true;
1248 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1249 "Bits known to be one AND zero?");
1250
1251 // If all of the demanded bits are known 1 on one side, return the other.
1252 // These bits cannot contribute to the result of the 'and'.
1253 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1254 (DemandedMask & ~LHSKnownZero))
1255 return UpdateValueUsesWith(I, I->getOperand(0));
1256 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1257 (DemandedMask & ~RHSKnownZero))
1258 return UpdateValueUsesWith(I, I->getOperand(1));
1259
1260 // If all of the demanded bits in the inputs are known zeros, return zero.
1261 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1262 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1263
1264 // If the RHS is a constant, see if we can simplify it.
1265 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1266 return UpdateValueUsesWith(I, I);
1267
1268 // Output known-1 bits are only known if set in both the LHS & RHS.
1269 RHSKnownOne &= LHSKnownOne;
1270 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1271 RHSKnownZero |= LHSKnownZero;
1272 break;
1273 case Instruction::Or:
1274 // If either the LHS or the RHS are One, the result is One.
1275 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1276 RHSKnownZero, RHSKnownOne, Depth+1))
1277 return true;
1278 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1279 "Bits known to be one AND zero?");
1280 // If something is known one on the RHS, the bits aren't demanded on the
1281 // LHS.
1282 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1283 LHSKnownZero, LHSKnownOne, Depth+1))
1284 return true;
1285 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1286 "Bits known to be one AND zero?");
1287
1288 // If all of the demanded bits are known zero on one side, return the other.
1289 // These bits cannot contribute to the result of the 'or'.
1290 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1291 (DemandedMask & ~LHSKnownOne))
1292 return UpdateValueUsesWith(I, I->getOperand(0));
1293 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1294 (DemandedMask & ~RHSKnownOne))
1295 return UpdateValueUsesWith(I, I->getOperand(1));
1296
1297 // If all of the potentially set bits on one side are known to be set on
1298 // the other side, just use the 'other' side.
1299 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1300 (DemandedMask & (~RHSKnownZero)))
1301 return UpdateValueUsesWith(I, I->getOperand(0));
1302 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1303 (DemandedMask & (~LHSKnownZero)))
1304 return UpdateValueUsesWith(I, I->getOperand(1));
1305
1306 // If the RHS is a constant, see if we can simplify it.
1307 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1308 return UpdateValueUsesWith(I, I);
1309
1310 // Output known-0 bits are only known if clear in both the LHS & RHS.
1311 RHSKnownZero &= LHSKnownZero;
1312 // Output known-1 are known to be set if set in either the LHS | RHS.
1313 RHSKnownOne |= LHSKnownOne;
1314 break;
1315 case Instruction::Xor: {
1316 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1317 RHSKnownZero, RHSKnownOne, Depth+1))
1318 return true;
1319 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1320 "Bits known to be one AND zero?");
1321 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1322 LHSKnownZero, LHSKnownOne, Depth+1))
1323 return true;
1324 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1325 "Bits known to be one AND zero?");
1326
1327 // If all of the demanded bits are known zero on one side, return the other.
1328 // These bits cannot contribute to the result of the 'xor'.
1329 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1330 return UpdateValueUsesWith(I, I->getOperand(0));
1331 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1332 return UpdateValueUsesWith(I, I->getOperand(1));
1333
1334 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1335 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1336 (RHSKnownOne & LHSKnownOne);
1337 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1338 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1339 (RHSKnownOne & LHSKnownZero);
1340
1341 // If all of the demanded bits are known to be zero on one side or the
1342 // other, turn this into an *inclusive* or.
1343 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1344 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1345 Instruction *Or =
1346 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1347 I->getName());
1348 InsertNewInstBefore(Or, *I);
1349 return UpdateValueUsesWith(I, Or);
1350 }
1351
1352 // If all of the demanded bits on one side are known, and all of the set
1353 // bits on that side are also known to be set on the other side, turn this
1354 // into an AND, as we know the bits will be cleared.
1355 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1356 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1357 // all known
1358 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1359 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1360 Instruction *And =
1361 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1362 InsertNewInstBefore(And, *I);
1363 return UpdateValueUsesWith(I, And);
1364 }
1365 }
1366
1367 // If the RHS is a constant, see if we can simplify it.
1368 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1369 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1370 return UpdateValueUsesWith(I, I);
1371
1372 RHSKnownZero = KnownZeroOut;
1373 RHSKnownOne = KnownOneOut;
1374 break;
1375 }
1376 case Instruction::Select:
1377 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1378 RHSKnownZero, RHSKnownOne, Depth+1))
1379 return true;
1380 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1381 LHSKnownZero, LHSKnownOne, Depth+1))
1382 return true;
1383 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1384 "Bits known to be one AND zero?");
1385 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1386 "Bits known to be one AND zero?");
1387
1388 // If the operands are constants, see if we can simplify them.
1389 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1390 return UpdateValueUsesWith(I, I);
1391 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1392 return UpdateValueUsesWith(I, I);
1393
1394 // Only known if known in both the LHS and RHS.
1395 RHSKnownOne &= LHSKnownOne;
1396 RHSKnownZero &= LHSKnownZero;
1397 break;
1398 case Instruction::Trunc: {
1399 uint32_t truncBf =
1400 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1401 DemandedMask.zext(truncBf);
1402 RHSKnownZero.zext(truncBf);
1403 RHSKnownOne.zext(truncBf);
1404 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1405 RHSKnownZero, RHSKnownOne, Depth+1))
1406 return true;
1407 DemandedMask.trunc(BitWidth);
1408 RHSKnownZero.trunc(BitWidth);
1409 RHSKnownOne.trunc(BitWidth);
1410 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1411 "Bits known to be one AND zero?");
1412 break;
1413 }
1414 case Instruction::BitCast:
1415 if (!I->getOperand(0)->getType()->isInteger())
1416 return false;
1417
1418 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1419 RHSKnownZero, RHSKnownOne, Depth+1))
1420 return true;
1421 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1422 "Bits known to be one AND zero?");
1423 break;
1424 case Instruction::ZExt: {
1425 // Compute the bits in the result that are not present in the input.
1426 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1427 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1428
1429 DemandedMask.trunc(SrcBitWidth);
1430 RHSKnownZero.trunc(SrcBitWidth);
1431 RHSKnownOne.trunc(SrcBitWidth);
1432 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1433 RHSKnownZero, RHSKnownOne, Depth+1))
1434 return true;
1435 DemandedMask.zext(BitWidth);
1436 RHSKnownZero.zext(BitWidth);
1437 RHSKnownOne.zext(BitWidth);
1438 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440 // The top bits are known to be zero.
1441 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1442 break;
1443 }
1444 case Instruction::SExt: {
1445 // Compute the bits in the result that are not present in the input.
1446 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1447 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1448
1449 APInt InputDemandedBits = DemandedMask &
1450 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1451
1452 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1453 // If any of the sign extended bits are demanded, we know that the sign
1454 // bit is demanded.
1455 if ((NewBits & DemandedMask) != 0)
1456 InputDemandedBits.set(SrcBitWidth-1);
1457
1458 InputDemandedBits.trunc(SrcBitWidth);
1459 RHSKnownZero.trunc(SrcBitWidth);
1460 RHSKnownOne.trunc(SrcBitWidth);
1461 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1462 RHSKnownZero, RHSKnownOne, Depth+1))
1463 return true;
1464 InputDemandedBits.zext(BitWidth);
1465 RHSKnownZero.zext(BitWidth);
1466 RHSKnownOne.zext(BitWidth);
1467 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1468 "Bits known to be one AND zero?");
1469
1470 // If the sign bit of the input is known set or clear, then we know the
1471 // top bits of the result.
1472
1473 // If the input sign bit is known zero, or if the NewBits are not demanded
1474 // convert this into a zero extension.
1475 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1476 {
1477 // Convert to ZExt cast
1478 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1479 return UpdateValueUsesWith(I, NewCast);
1480 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1481 RHSKnownOne |= NewBits;
1482 }
1483 break;
1484 }
1485 case Instruction::Add: {
1486 // Figure out what the input bits are. If the top bits of the and result
1487 // are not demanded, then the add doesn't demand them from its input
1488 // either.
1489 uint32_t NLZ = DemandedMask.countLeadingZeros();
1490
1491 // If there is a constant on the RHS, there are a variety of xformations
1492 // we can do.
1493 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1494 // If null, this should be simplified elsewhere. Some of the xforms here
1495 // won't work if the RHS is zero.
1496 if (RHS->isZero())
1497 break;
1498
1499 // If the top bit of the output is demanded, demand everything from the
1500 // input. Otherwise, we demand all the input bits except NLZ top bits.
1501 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1502
1503 // Find information about known zero/one bits in the input.
1504 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1505 LHSKnownZero, LHSKnownOne, Depth+1))
1506 return true;
1507
1508 // If the RHS of the add has bits set that can't affect the input, reduce
1509 // the constant.
1510 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1511 return UpdateValueUsesWith(I, I);
1512
1513 // Avoid excess work.
1514 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1515 break;
1516
1517 // Turn it into OR if input bits are zero.
1518 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1519 Instruction *Or =
1520 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1521 I->getName());
1522 InsertNewInstBefore(Or, *I);
1523 return UpdateValueUsesWith(I, Or);
1524 }
1525
1526 // We can say something about the output known-zero and known-one bits,
1527 // depending on potential carries from the input constant and the
1528 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1529 // bits set and the RHS constant is 0x01001, then we know we have a known
1530 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1531
1532 // To compute this, we first compute the potential carry bits. These are
1533 // the bits which may be modified. I'm not aware of a better way to do
1534 // this scan.
1535 const APInt& RHSVal = RHS->getValue();
1536 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1537
1538 // Now that we know which bits have carries, compute the known-1/0 sets.
1539
1540 // Bits are known one if they are known zero in one operand and one in the
1541 // other, and there is no input carry.
1542 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1543 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1544
1545 // Bits are known zero if they are known zero in both operands and there
1546 // is no input carry.
1547 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1548 } else {
1549 // If the high-bits of this ADD are not demanded, then it does not demand
1550 // the high bits of its LHS or RHS.
1551 if (DemandedMask[BitWidth-1] == 0) {
1552 // Right fill the mask of bits for this ADD to demand the most
1553 // significant bit and all those below it.
1554 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1555 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1556 LHSKnownZero, LHSKnownOne, Depth+1))
1557 return true;
1558 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1559 LHSKnownZero, LHSKnownOne, Depth+1))
1560 return true;
1561 }
1562 }
1563 break;
1564 }
1565 case Instruction::Sub:
1566 // If the high-bits of this SUB are not demanded, then it does not demand
1567 // the high bits of its LHS or RHS.
1568 if (DemandedMask[BitWidth-1] == 0) {
1569 // Right fill the mask of bits for this SUB to demand the most
1570 // significant bit and all those below it.
1571 uint32_t NLZ = DemandedMask.countLeadingZeros();
1572 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1573 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1574 LHSKnownZero, LHSKnownOne, Depth+1))
1575 return true;
1576 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1577 LHSKnownZero, LHSKnownOne, Depth+1))
1578 return true;
1579 }
1580 break;
1581 case Instruction::Shl:
1582 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1583 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1584 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1585 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1586 RHSKnownZero, RHSKnownOne, Depth+1))
1587 return true;
1588 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1589 "Bits known to be one AND zero?");
1590 RHSKnownZero <<= ShiftAmt;
1591 RHSKnownOne <<= ShiftAmt;
1592 // low bits known zero.
1593 if (ShiftAmt)
1594 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1595 }
1596 break;
1597 case Instruction::LShr:
1598 // For a logical shift right
1599 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1600 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1601
1602 // Unsigned shift right.
1603 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1604 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1605 RHSKnownZero, RHSKnownOne, Depth+1))
1606 return true;
1607 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1608 "Bits known to be one AND zero?");
1609 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1610 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1611 if (ShiftAmt) {
1612 // Compute the new bits that are at the top now.
1613 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1614 RHSKnownZero |= HighBits; // high bits known zero.
1615 }
1616 }
1617 break;
1618 case Instruction::AShr:
1619 // If this is an arithmetic shift right and only the low-bit is set, we can
1620 // always convert this into a logical shr, even if the shift amount is
1621 // variable. The low bit of the shift cannot be an input sign bit unless
1622 // the shift amount is >= the size of the datatype, which is undefined.
1623 if (DemandedMask == 1) {
1624 // Perform the logical shift right.
1625 Value *NewVal = BinaryOperator::createLShr(
1626 I->getOperand(0), I->getOperand(1), I->getName());
1627 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1628 return UpdateValueUsesWith(I, NewVal);
1629 }
1630
1631 // If the sign bit is the only bit demanded by this ashr, then there is no
1632 // need to do it, the shift doesn't change the high bit.
1633 if (DemandedMask.isSignBit())
1634 return UpdateValueUsesWith(I, I->getOperand(0));
1635
1636 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1637 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1638
1639 // Signed shift right.
1640 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1641 // If any of the "high bits" are demanded, we should set the sign bit as
1642 // demanded.
1643 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1644 DemandedMaskIn.set(BitWidth-1);
1645 if (SimplifyDemandedBits(I->getOperand(0),
1646 DemandedMaskIn,
1647 RHSKnownZero, RHSKnownOne, Depth+1))
1648 return true;
1649 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1650 "Bits known to be one AND zero?");
1651 // Compute the new bits that are at the top now.
1652 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1653 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1654 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1655
1656 // Handle the sign bits.
1657 APInt SignBit(APInt::getSignBit(BitWidth));
1658 // Adjust to where it is now in the mask.
1659 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1660
1661 // If the input sign bit is known to be zero, or if none of the top bits
1662 // are demanded, turn this into an unsigned shift right.
1663 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1664 (HighBits & ~DemandedMask) == HighBits) {
1665 // Perform the logical shift right.
1666 Value *NewVal = BinaryOperator::createLShr(
1667 I->getOperand(0), SA, I->getName());
1668 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1669 return UpdateValueUsesWith(I, NewVal);
1670 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1671 RHSKnownOne |= HighBits;
1672 }
1673 }
1674 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001675 case Instruction::SRem:
1676 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1677 APInt RA = Rem->getValue();
1678 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1679 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1680 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1681 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1682 LHSKnownZero, LHSKnownOne, Depth+1))
1683 return true;
1684
1685 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1686 LHSKnownZero |= ~LowBits;
1687 else if (LHSKnownOne[BitWidth-1])
1688 LHSKnownOne |= ~LowBits;
1689
1690 KnownZero |= LHSKnownZero & DemandedMask;
1691 KnownOne |= LHSKnownOne & DemandedMask;
1692
1693 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1694 }
1695 }
1696 break;
1697 case Instruction::URem:
1698 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1699 APInt RA = Rem->getValue();
1700 if (RA.isPowerOf2()) {
1701 APInt LowBits = (RA - 1) | RA;
1702 APInt Mask2 = LowBits & DemandedMask;
1703 KnownZero |= ~LowBits & DemandedMask;
1704 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1705 KnownZero, KnownOne, Depth+1))
1706 return true;
1707
1708 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1709 }
1710 } else {
1711 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1712 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1713 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1714 KnownZero2, KnownOne2, Depth+1))
1715 return true;
1716
1717 uint32_t Leaders = KnownZero2.countLeadingOnes();
1718 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1719 }
1720 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 }
1722
1723 // If the client is only demanding bits that we know, return the known
1724 // constant.
1725 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1726 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1727 return false;
1728}
1729
1730
1731/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1732/// 64 or fewer elements. DemandedElts contains the set of elements that are
1733/// actually used by the caller. This method analyzes which elements of the
1734/// operand are undef and returns that information in UndefElts.
1735///
1736/// If the information about demanded elements can be used to simplify the
1737/// operation, the operation is simplified, then the resultant value is
1738/// returned. This returns null if no change was made.
1739Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1740 uint64_t &UndefElts,
1741 unsigned Depth) {
1742 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1743 assert(VWidth <= 64 && "Vector too wide to analyze!");
1744 uint64_t EltMask = ~0ULL >> (64-VWidth);
1745 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1746 "Invalid DemandedElts!");
1747
1748 if (isa<UndefValue>(V)) {
1749 // If the entire vector is undefined, just return this info.
1750 UndefElts = EltMask;
1751 return 0;
1752 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1753 UndefElts = EltMask;
1754 return UndefValue::get(V->getType());
1755 }
1756
1757 UndefElts = 0;
1758 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1759 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1760 Constant *Undef = UndefValue::get(EltTy);
1761
1762 std::vector<Constant*> Elts;
1763 for (unsigned i = 0; i != VWidth; ++i)
1764 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1765 Elts.push_back(Undef);
1766 UndefElts |= (1ULL << i);
1767 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1768 Elts.push_back(Undef);
1769 UndefElts |= (1ULL << i);
1770 } else { // Otherwise, defined.
1771 Elts.push_back(CP->getOperand(i));
1772 }
1773
1774 // If we changed the constant, return it.
1775 Constant *NewCP = ConstantVector::get(Elts);
1776 return NewCP != CP ? NewCP : 0;
1777 } else if (isa<ConstantAggregateZero>(V)) {
1778 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1779 // set to undef.
1780 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1781 Constant *Zero = Constant::getNullValue(EltTy);
1782 Constant *Undef = UndefValue::get(EltTy);
1783 std::vector<Constant*> Elts;
1784 for (unsigned i = 0; i != VWidth; ++i)
1785 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1786 UndefElts = DemandedElts ^ EltMask;
1787 return ConstantVector::get(Elts);
1788 }
1789
1790 if (!V->hasOneUse()) { // Other users may use these bits.
1791 if (Depth != 0) { // Not at the root.
1792 // TODO: Just compute the UndefElts information recursively.
1793 return false;
1794 }
1795 return false;
1796 } else if (Depth == 10) { // Limit search depth.
1797 return false;
1798 }
1799
1800 Instruction *I = dyn_cast<Instruction>(V);
1801 if (!I) return false; // Only analyze instructions.
1802
1803 bool MadeChange = false;
1804 uint64_t UndefElts2;
1805 Value *TmpV;
1806 switch (I->getOpcode()) {
1807 default: break;
1808
1809 case Instruction::InsertElement: {
1810 // If this is a variable index, we don't know which element it overwrites.
1811 // demand exactly the same input as we produce.
1812 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1813 if (Idx == 0) {
1814 // Note that we can't propagate undef elt info, because we don't know
1815 // which elt is getting updated.
1816 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1817 UndefElts2, Depth+1);
1818 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1819 break;
1820 }
1821
1822 // If this is inserting an element that isn't demanded, remove this
1823 // insertelement.
1824 unsigned IdxNo = Idx->getZExtValue();
1825 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1826 return AddSoonDeadInstToWorklist(*I, 0);
1827
1828 // Otherwise, the element inserted overwrites whatever was there, so the
1829 // input demanded set is simpler than the output set.
1830 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1831 DemandedElts & ~(1ULL << IdxNo),
1832 UndefElts, Depth+1);
1833 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1834
1835 // The inserted element is defined.
1836 UndefElts |= 1ULL << IdxNo;
1837 break;
1838 }
1839 case Instruction::BitCast: {
1840 // Vector->vector casts only.
1841 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1842 if (!VTy) break;
1843 unsigned InVWidth = VTy->getNumElements();
1844 uint64_t InputDemandedElts = 0;
1845 unsigned Ratio;
1846
1847 if (VWidth == InVWidth) {
1848 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1849 // elements as are demanded of us.
1850 Ratio = 1;
1851 InputDemandedElts = DemandedElts;
1852 } else if (VWidth > InVWidth) {
1853 // Untested so far.
1854 break;
1855
1856 // If there are more elements in the result than there are in the source,
1857 // then an input element is live if any of the corresponding output
1858 // elements are live.
1859 Ratio = VWidth/InVWidth;
1860 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1861 if (DemandedElts & (1ULL << OutIdx))
1862 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1863 }
1864 } else {
1865 // Untested so far.
1866 break;
1867
1868 // If there are more elements in the source than there are in the result,
1869 // then an input element is live if the corresponding output element is
1870 // live.
1871 Ratio = InVWidth/VWidth;
1872 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1873 if (DemandedElts & (1ULL << InIdx/Ratio))
1874 InputDemandedElts |= 1ULL << InIdx;
1875 }
1876
1877 // div/rem demand all inputs, because they don't want divide by zero.
1878 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1879 UndefElts2, Depth+1);
1880 if (TmpV) {
1881 I->setOperand(0, TmpV);
1882 MadeChange = true;
1883 }
1884
1885 UndefElts = UndefElts2;
1886 if (VWidth > InVWidth) {
1887 assert(0 && "Unimp");
1888 // If there are more elements in the result than there are in the source,
1889 // then an output element is undef if the corresponding input element is
1890 // undef.
1891 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1892 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1893 UndefElts |= 1ULL << OutIdx;
1894 } else if (VWidth < InVWidth) {
1895 assert(0 && "Unimp");
1896 // If there are more elements in the source than there are in the result,
1897 // then a result element is undef if all of the corresponding input
1898 // elements are undef.
1899 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1900 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1901 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1902 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1903 }
1904 break;
1905 }
1906 case Instruction::And:
1907 case Instruction::Or:
1908 case Instruction::Xor:
1909 case Instruction::Add:
1910 case Instruction::Sub:
1911 case Instruction::Mul:
1912 // div/rem demand all inputs, because they don't want divide by zero.
1913 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1914 UndefElts, Depth+1);
1915 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1916 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1917 UndefElts2, Depth+1);
1918 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1919
1920 // Output elements are undefined if both are undefined. Consider things
1921 // like undef&0. The result is known zero, not undef.
1922 UndefElts &= UndefElts2;
1923 break;
1924
1925 case Instruction::Call: {
1926 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1927 if (!II) break;
1928 switch (II->getIntrinsicID()) {
1929 default: break;
1930
1931 // Binary vector operations that work column-wise. A dest element is a
1932 // function of the corresponding input elements from the two inputs.
1933 case Intrinsic::x86_sse_sub_ss:
1934 case Intrinsic::x86_sse_mul_ss:
1935 case Intrinsic::x86_sse_min_ss:
1936 case Intrinsic::x86_sse_max_ss:
1937 case Intrinsic::x86_sse2_sub_sd:
1938 case Intrinsic::x86_sse2_mul_sd:
1939 case Intrinsic::x86_sse2_min_sd:
1940 case Intrinsic::x86_sse2_max_sd:
1941 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1942 UndefElts, Depth+1);
1943 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1944 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1945 UndefElts2, Depth+1);
1946 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1947
1948 // If only the low elt is demanded and this is a scalarizable intrinsic,
1949 // scalarize it now.
1950 if (DemandedElts == 1) {
1951 switch (II->getIntrinsicID()) {
1952 default: break;
1953 case Intrinsic::x86_sse_sub_ss:
1954 case Intrinsic::x86_sse_mul_ss:
1955 case Intrinsic::x86_sse2_sub_sd:
1956 case Intrinsic::x86_sse2_mul_sd:
1957 // TODO: Lower MIN/MAX/ABS/etc
1958 Value *LHS = II->getOperand(1);
1959 Value *RHS = II->getOperand(2);
1960 // Extract the element as scalars.
1961 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1962 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1963
1964 switch (II->getIntrinsicID()) {
1965 default: assert(0 && "Case stmts out of sync!");
1966 case Intrinsic::x86_sse_sub_ss:
1967 case Intrinsic::x86_sse2_sub_sd:
1968 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1969 II->getName()), *II);
1970 break;
1971 case Intrinsic::x86_sse_mul_ss:
1972 case Intrinsic::x86_sse2_mul_sd:
1973 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1974 II->getName()), *II);
1975 break;
1976 }
1977
1978 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001979 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1980 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001981 InsertNewInstBefore(New, *II);
1982 AddSoonDeadInstToWorklist(*II, 0);
1983 return New;
1984 }
1985 }
1986
1987 // Output elements are undefined if both are undefined. Consider things
1988 // like undef&0. The result is known zero, not undef.
1989 UndefElts &= UndefElts2;
1990 break;
1991 }
1992 break;
1993 }
1994 }
1995 return MadeChange ? I : 0;
1996}
1997
Nick Lewycky2de09a92007-09-06 02:40:25 +00001998/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00002000/// @brief Determine if the icmp Predicate is true when both operands are equal
2001static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002002 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2003 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2004 pred == ICmpInst::ICMP_SLE;
2005}
2006
Nick Lewycky2de09a92007-09-06 02:40:25 +00002007/// @returns true if the specified compare instruction is
2008/// true when both operands are equal...
2009/// @brief Determine if the ICmpInst returns true when both operands are equal
2010static bool isTrueWhenEqual(ICmpInst &ICI) {
2011 return isTrueWhenEqual(ICI.getPredicate());
2012}
2013
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014/// AssociativeOpt - Perform an optimization on an associative operator. This
2015/// function is designed to check a chain of associative operators for a
2016/// potential to apply a certain optimization. Since the optimization may be
2017/// applicable if the expression was reassociated, this checks the chain, then
2018/// reassociates the expression as necessary to expose the optimization
2019/// opportunity. This makes use of a special Functor, which must define
2020/// 'shouldApply' and 'apply' methods.
2021///
2022template<typename Functor>
2023Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2024 unsigned Opcode = Root.getOpcode();
2025 Value *LHS = Root.getOperand(0);
2026
2027 // Quick check, see if the immediate LHS matches...
2028 if (F.shouldApply(LHS))
2029 return F.apply(Root);
2030
2031 // Otherwise, if the LHS is not of the same opcode as the root, return.
2032 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2033 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2034 // Should we apply this transform to the RHS?
2035 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2036
2037 // If not to the RHS, check to see if we should apply to the LHS...
2038 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2039 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2040 ShouldApply = true;
2041 }
2042
2043 // If the functor wants to apply the optimization to the RHS of LHSI,
2044 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2045 if (ShouldApply) {
2046 BasicBlock *BB = Root.getParent();
2047
2048 // Now all of the instructions are in the current basic block, go ahead
2049 // and perform the reassociation.
2050 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2051
2052 // First move the selected RHS to the LHS of the root...
2053 Root.setOperand(0, LHSI->getOperand(1));
2054
2055 // Make what used to be the LHS of the root be the user of the root...
2056 Value *ExtraOperand = TmpLHSI->getOperand(1);
2057 if (&Root == TmpLHSI) {
2058 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2059 return 0;
2060 }
2061 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2062 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2063 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2064 BasicBlock::iterator ARI = &Root; ++ARI;
2065 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2066 ARI = Root;
2067
2068 // Now propagate the ExtraOperand down the chain of instructions until we
2069 // get to LHSI.
2070 while (TmpLHSI != LHSI) {
2071 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2072 // Move the instruction to immediately before the chain we are
2073 // constructing to avoid breaking dominance properties.
2074 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2075 BB->getInstList().insert(ARI, NextLHSI);
2076 ARI = NextLHSI;
2077
2078 Value *NextOp = NextLHSI->getOperand(1);
2079 NextLHSI->setOperand(1, ExtraOperand);
2080 TmpLHSI = NextLHSI;
2081 ExtraOperand = NextOp;
2082 }
2083
2084 // Now that the instructions are reassociated, have the functor perform
2085 // the transformation...
2086 return F.apply(Root);
2087 }
2088
2089 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2090 }
2091 return 0;
2092}
2093
2094
2095// AddRHS - Implements: X + X --> X << 1
2096struct AddRHS {
2097 Value *RHS;
2098 AddRHS(Value *rhs) : RHS(rhs) {}
2099 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2100 Instruction *apply(BinaryOperator &Add) const {
2101 return BinaryOperator::createShl(Add.getOperand(0),
2102 ConstantInt::get(Add.getType(), 1));
2103 }
2104};
2105
2106// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2107// iff C1&C2 == 0
2108struct AddMaskingAnd {
2109 Constant *C2;
2110 AddMaskingAnd(Constant *c) : C2(c) {}
2111 bool shouldApply(Value *LHS) const {
2112 ConstantInt *C1;
2113 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2114 ConstantExpr::getAnd(C1, C2)->isNullValue();
2115 }
2116 Instruction *apply(BinaryOperator &Add) const {
2117 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
2118 }
2119};
2120
2121static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2122 InstCombiner *IC) {
2123 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2124 if (Constant *SOC = dyn_cast<Constant>(SO))
2125 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2126
2127 return IC->InsertNewInstBefore(CastInst::create(
2128 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2129 }
2130
2131 // Figure out if the constant is the left or the right argument.
2132 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2133 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2134
2135 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2136 if (ConstIsRHS)
2137 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2138 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2139 }
2140
2141 Value *Op0 = SO, *Op1 = ConstOperand;
2142 if (!ConstIsRHS)
2143 std::swap(Op0, Op1);
2144 Instruction *New;
2145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2146 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2147 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2148 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2149 SO->getName()+".cmp");
2150 else {
2151 assert(0 && "Unknown binary instruction type!");
2152 abort();
2153 }
2154 return IC->InsertNewInstBefore(New, I);
2155}
2156
2157// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2158// constant as the other operand, try to fold the binary operator into the
2159// select arguments. This also works for Cast instructions, which obviously do
2160// not have a second operand.
2161static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2162 InstCombiner *IC) {
2163 // Don't modify shared select instructions
2164 if (!SI->hasOneUse()) return 0;
2165 Value *TV = SI->getOperand(1);
2166 Value *FV = SI->getOperand(2);
2167
2168 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2169 // Bool selects with constant operands can be folded to logical ops.
2170 if (SI->getType() == Type::Int1Ty) return 0;
2171
2172 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2173 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2174
Gabor Greifd6da1d02008-04-06 20:25:17 +00002175 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2176 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 }
2178 return 0;
2179}
2180
2181
2182/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2183/// node as operand #0, see if we can fold the instruction into the PHI (which
2184/// is only possible if all operands to the PHI are constants).
2185Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2186 PHINode *PN = cast<PHINode>(I.getOperand(0));
2187 unsigned NumPHIValues = PN->getNumIncomingValues();
2188 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2189
2190 // Check to see if all of the operands of the PHI are constants. If there is
2191 // one non-constant value, remember the BB it is. If there is more than one
2192 // or if *it* is a PHI, bail out.
2193 BasicBlock *NonConstBB = 0;
2194 for (unsigned i = 0; i != NumPHIValues; ++i)
2195 if (!isa<Constant>(PN->getIncomingValue(i))) {
2196 if (NonConstBB) return 0; // More than one non-const value.
2197 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2198 NonConstBB = PN->getIncomingBlock(i);
2199
2200 // If the incoming non-constant value is in I's block, we have an infinite
2201 // loop.
2202 if (NonConstBB == I.getParent())
2203 return 0;
2204 }
2205
2206 // If there is exactly one non-constant value, we can insert a copy of the
2207 // operation in that block. However, if this is a critical edge, we would be
2208 // inserting the computation one some other paths (e.g. inside a loop). Only
2209 // do this if the pred block is unconditionally branching into the phi block.
2210 if (NonConstBB) {
2211 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2212 if (!BI || !BI->isUnconditional()) return 0;
2213 }
2214
2215 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002216 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002217 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2218 InsertNewInstBefore(NewPN, *PN);
2219 NewPN->takeName(PN);
2220
2221 // Next, add all of the operands to the PHI.
2222 if (I.getNumOperands() == 2) {
2223 Constant *C = cast<Constant>(I.getOperand(1));
2224 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002225 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2227 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2228 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2229 else
2230 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2231 } else {
2232 assert(PN->getIncomingBlock(i) == NonConstBB);
2233 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2234 InV = BinaryOperator::create(BO->getOpcode(),
2235 PN->getIncomingValue(i), C, "phitmp",
2236 NonConstBB->getTerminator());
2237 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2238 InV = CmpInst::create(CI->getOpcode(),
2239 CI->getPredicate(),
2240 PN->getIncomingValue(i), C, "phitmp",
2241 NonConstBB->getTerminator());
2242 else
2243 assert(0 && "Unknown binop!");
2244
2245 AddToWorkList(cast<Instruction>(InV));
2246 }
2247 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2248 }
2249 } else {
2250 CastInst *CI = cast<CastInst>(&I);
2251 const Type *RetTy = CI->getType();
2252 for (unsigned i = 0; i != NumPHIValues; ++i) {
2253 Value *InV;
2254 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2255 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2256 } else {
2257 assert(PN->getIncomingBlock(i) == NonConstBB);
2258 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2259 I.getType(), "phitmp",
2260 NonConstBB->getTerminator());
2261 AddToWorkList(cast<Instruction>(InV));
2262 }
2263 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2264 }
2265 }
2266 return ReplaceInstUsesWith(I, NewPN);
2267}
2268
Chris Lattner55476162008-01-29 06:52:45 +00002269
2270/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2271/// value is never equal to -0.0.
2272///
2273/// Note that this function will need to be revisited when we support nondefault
2274/// rounding modes!
2275///
2276static bool CannotBeNegativeZero(const Value *V) {
2277 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2278 return !CFP->getValueAPF().isNegZero();
2279
2280 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2282 if (I->getOpcode() == Instruction::Add &&
2283 isa<ConstantFP>(I->getOperand(1)) &&
2284 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2285 return true;
2286
2287 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2288 if (II->getIntrinsicID() == Intrinsic::sqrt)
2289 return CannotBeNegativeZero(II->getOperand(1));
2290
2291 if (const CallInst *CI = dyn_cast<CallInst>(I))
2292 if (const Function *F = CI->getCalledFunction()) {
2293 if (F->isDeclaration()) {
2294 switch (F->getNameLen()) {
2295 case 3: // abs(x) != -0.0
2296 if (!strcmp(F->getNameStart(), "abs")) return true;
2297 break;
2298 case 4: // abs[lf](x) != -0.0
2299 if (!strcmp(F->getNameStart(), "absf")) return true;
2300 if (!strcmp(F->getNameStart(), "absl")) return true;
2301 break;
2302 }
2303 }
2304 }
2305 }
2306
2307 return false;
2308}
2309
2310
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2312 bool Changed = SimplifyCommutative(I);
2313 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2314
2315 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2316 // X + undef -> undef
2317 if (isa<UndefValue>(RHS))
2318 return ReplaceInstUsesWith(I, RHS);
2319
2320 // X + 0 --> X
2321 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2322 if (RHSC->isNullValue())
2323 return ReplaceInstUsesWith(I, LHS);
2324 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002325 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2326 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002327 return ReplaceInstUsesWith(I, LHS);
2328 }
2329
2330 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2331 // X + (signbit) --> X ^ signbit
2332 const APInt& Val = CI->getValue();
2333 uint32_t BitWidth = Val.getBitWidth();
2334 if (Val == APInt::getSignBit(BitWidth))
2335 return BinaryOperator::createXor(LHS, RHS);
2336
2337 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2338 // (X & 254)+1 -> (X&254)|1
2339 if (!isa<VectorType>(I.getType())) {
2340 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2341 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2342 KnownZero, KnownOne))
2343 return &I;
2344 }
2345 }
2346
2347 if (isa<PHINode>(LHS))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2349 return NV;
2350
2351 ConstantInt *XorRHS = 0;
2352 Value *XorLHS = 0;
2353 if (isa<ConstantInt>(RHSC) &&
2354 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2355 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2356 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2357
2358 uint32_t Size = TySizeBits / 2;
2359 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2360 APInt CFF80Val(-C0080Val);
2361 do {
2362 if (TySizeBits > Size) {
2363 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2364 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2365 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2366 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2367 // This is a sign extend if the top bits are known zero.
2368 if (!MaskedValueIsZero(XorLHS,
2369 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2370 Size = 0; // Not a sign ext, but can't be any others either.
2371 break;
2372 }
2373 }
2374 Size >>= 1;
2375 C0080Val = APIntOps::lshr(C0080Val, Size);
2376 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2377 } while (Size >= 1);
2378
2379 // FIXME: This shouldn't be necessary. When the backends can handle types
2380 // with funny bit widths then this whole cascade of if statements should
2381 // be removed. It is just here to get the size of the "middle" type back
2382 // up to something that the back ends can handle.
2383 const Type *MiddleType = 0;
2384 switch (Size) {
2385 default: break;
2386 case 32: MiddleType = Type::Int32Ty; break;
2387 case 16: MiddleType = Type::Int16Ty; break;
2388 case 8: MiddleType = Type::Int8Ty; break;
2389 }
2390 if (MiddleType) {
2391 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2392 InsertNewInstBefore(NewTrunc, I);
2393 return new SExtInst(NewTrunc, I.getType(), I.getName());
2394 }
2395 }
2396 }
2397
2398 // X + X --> X << 1
2399 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2400 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2401
2402 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2403 if (RHSI->getOpcode() == Instruction::Sub)
2404 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2405 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2406 }
2407 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2408 if (LHSI->getOpcode() == Instruction::Sub)
2409 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2410 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2411 }
2412 }
2413
2414 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002415 // -A + -B --> -(A + B)
2416 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002417 if (LHS->getType()->isIntOrIntVector()) {
2418 if (Value *RHSV = dyn_castNegVal(RHS)) {
2419 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2420 InsertNewInstBefore(NewAdd, I);
2421 return BinaryOperator::createNeg(NewAdd);
2422 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002423 }
2424
2425 return BinaryOperator::createSub(RHS, LHSV);
2426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427
2428 // A + -B --> A - B
2429 if (!isa<Constant>(RHS))
2430 if (Value *V = dyn_castNegVal(RHS))
2431 return BinaryOperator::createSub(LHS, V);
2432
2433
2434 ConstantInt *C2;
2435 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2436 if (X == RHS) // X*C + X --> X * (C+1)
2437 return BinaryOperator::createMul(RHS, AddOne(C2));
2438
2439 // X*C1 + X*C2 --> X * (C1+C2)
2440 ConstantInt *C1;
2441 if (X == dyn_castFoldableMul(RHS, C1))
2442 return BinaryOperator::createMul(X, Add(C1, C2));
2443 }
2444
2445 // X + X*C --> X * (C+1)
2446 if (dyn_castFoldableMul(RHS, C2) == LHS)
2447 return BinaryOperator::createMul(LHS, AddOne(C2));
2448
2449 // X + ~X --> -1 since ~X = -X-1
2450 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2451 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2452
2453
2454 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2455 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2456 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2457 return R;
2458
Nick Lewycky83598a72008-02-03 07:42:09 +00002459 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002460 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002461 Value *W, *X, *Y, *Z;
2462 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2463 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2464 if (W != Y) {
2465 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002466 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002467 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002468 std::swap(W, X);
2469 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002470 std::swap(Y, Z);
2471 std::swap(W, X);
2472 }
2473 }
2474
2475 if (W == Y) {
2476 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2477 LHS->getName()), I);
2478 return BinaryOperator::createMul(W, NewAdd);
2479 }
2480 }
2481 }
2482
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2484 Value *X = 0;
2485 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2486 return BinaryOperator::createSub(SubOne(CRHS), X);
2487
2488 // (X & FF00) + xx00 -> (X+xx00) & FF00
2489 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2490 Constant *Anded = And(CRHS, C2);
2491 if (Anded == CRHS) {
2492 // See if all bits from the first bit set in the Add RHS up are included
2493 // in the mask. First, get the rightmost bit.
2494 const APInt& AddRHSV = CRHS->getValue();
2495
2496 // Form a mask of all bits from the lowest bit added through the top.
2497 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2498
2499 // See if the and mask includes all of these bits.
2500 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2501
2502 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2503 // Okay, the xform is safe. Insert the new add pronto.
2504 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2505 LHS->getName()), I);
2506 return BinaryOperator::createAnd(NewAdd, C2);
2507 }
2508 }
2509 }
2510
2511 // Try to fold constant add into select arguments.
2512 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2513 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2514 return R;
2515 }
2516
2517 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002518 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 {
2520 CastInst *CI = dyn_cast<CastInst>(LHS);
2521 Value *Other = RHS;
2522 if (!CI) {
2523 CI = dyn_cast<CastInst>(RHS);
2524 Other = LHS;
2525 }
2526 if (CI && CI->getType()->isSized() &&
2527 (CI->getType()->getPrimitiveSizeInBits() ==
2528 TD->getIntPtrType()->getPrimitiveSizeInBits())
2529 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002530 unsigned AS =
2531 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002532 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2533 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002534 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535 return new PtrToIntInst(I2, CI->getType());
2536 }
2537 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002538
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002539 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002540 {
2541 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2542 Value *Other = RHS;
2543 if (!SI) {
2544 SI = dyn_cast<SelectInst>(RHS);
2545 Other = LHS;
2546 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002547 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002548 Value *TV = SI->getTrueValue();
2549 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002550 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002551
2552 // Can we fold the add into the argument of the select?
2553 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002554 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2555 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002556 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002557 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2558 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002559 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002560 }
2561 }
Chris Lattner55476162008-01-29 06:52:45 +00002562
2563 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2564 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2565 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2566 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567
2568 return Changed ? &I : 0;
2569}
2570
2571// isSignBit - Return true if the value represented by the constant only has the
2572// highest order bit set.
2573static bool isSignBit(ConstantInt *CI) {
2574 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2575 return CI->getValue() == APInt::getSignBit(NumBits);
2576}
2577
2578Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2579 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2580
2581 if (Op0 == Op1) // sub X, X -> 0
2582 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2583
2584 // If this is a 'B = x-(-A)', change to B = x+A...
2585 if (Value *V = dyn_castNegVal(Op1))
2586 return BinaryOperator::createAdd(Op0, V);
2587
2588 if (isa<UndefValue>(Op0))
2589 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2590 if (isa<UndefValue>(Op1))
2591 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2592
2593 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2594 // Replace (-1 - A) with (~A)...
2595 if (C->isAllOnesValue())
2596 return BinaryOperator::createNot(Op1);
2597
2598 // C - ~X == X + (1+C)
2599 Value *X = 0;
2600 if (match(Op1, m_Not(m_Value(X))))
2601 return BinaryOperator::createAdd(X, AddOne(C));
2602
2603 // -(X >>u 31) -> (X >>s 31)
2604 // -(X >>s 31) -> (X >>u 31)
2605 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002606 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 if (SI->getOpcode() == Instruction::LShr) {
2608 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2609 // Check to see if we are shifting out everything but the sign bit.
2610 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2611 SI->getType()->getPrimitiveSizeInBits()-1) {
2612 // Ok, the transformation is safe. Insert AShr.
2613 return BinaryOperator::create(Instruction::AShr,
2614 SI->getOperand(0), CU, SI->getName());
2615 }
2616 }
2617 }
2618 else if (SI->getOpcode() == Instruction::AShr) {
2619 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2620 // Check to see if we are shifting out everything but the sign bit.
2621 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2622 SI->getType()->getPrimitiveSizeInBits()-1) {
2623 // Ok, the transformation is safe. Insert LShr.
2624 return BinaryOperator::createLShr(
2625 SI->getOperand(0), CU, SI->getName());
2626 }
2627 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002628 }
2629 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630 }
2631
2632 // Try to fold constant sub into select arguments.
2633 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2634 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2635 return R;
2636
2637 if (isa<PHINode>(Op0))
2638 if (Instruction *NV = FoldOpIntoPhi(I))
2639 return NV;
2640 }
2641
2642 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2643 if (Op1I->getOpcode() == Instruction::Add &&
2644 !Op0->getType()->isFPOrFPVector()) {
2645 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2646 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2647 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2648 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2649 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2650 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2651 // C1-(X+C2) --> (C1-C2)-X
2652 return BinaryOperator::createSub(Subtract(CI1, CI2),
2653 Op1I->getOperand(0));
2654 }
2655 }
2656
2657 if (Op1I->hasOneUse()) {
2658 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2659 // is not used by anyone else...
2660 //
2661 if (Op1I->getOpcode() == Instruction::Sub &&
2662 !Op1I->getType()->isFPOrFPVector()) {
2663 // Swap the two operands of the subexpr...
2664 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2665 Op1I->setOperand(0, IIOp1);
2666 Op1I->setOperand(1, IIOp0);
2667
2668 // Create the new top level add instruction...
2669 return BinaryOperator::createAdd(Op0, Op1);
2670 }
2671
2672 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2673 //
2674 if (Op1I->getOpcode() == Instruction::And &&
2675 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2676 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2677
2678 Value *NewNot =
2679 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2680 return BinaryOperator::createAnd(Op0, NewNot);
2681 }
2682
2683 // 0 - (X sdiv C) -> (X sdiv -C)
2684 if (Op1I->getOpcode() == Instruction::SDiv)
2685 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2686 if (CSI->isZero())
2687 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2688 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2689 ConstantExpr::getNeg(DivRHS));
2690
2691 // X - X*C --> X * (1-C)
2692 ConstantInt *C2 = 0;
2693 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2694 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2695 return BinaryOperator::createMul(Op0, CP1);
2696 }
Dan Gohmanda338742007-09-17 17:31:57 +00002697
2698 // X - ((X / Y) * Y) --> X % Y
2699 if (Op1I->getOpcode() == Instruction::Mul)
2700 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2701 if (Op0 == I->getOperand(0) &&
2702 Op1I->getOperand(1) == I->getOperand(1)) {
2703 if (I->getOpcode() == Instruction::SDiv)
2704 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2705 if (I->getOpcode() == Instruction::UDiv)
2706 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2707 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002708 }
2709 }
2710
2711 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002712 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 if (Op0I->getOpcode() == Instruction::Add) {
2714 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2715 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2716 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2717 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2718 } else if (Op0I->getOpcode() == Instruction::Sub) {
2719 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2720 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2721 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002722 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723
2724 ConstantInt *C1;
2725 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2726 if (X == Op1) // X*C - X --> X * (C-1)
2727 return BinaryOperator::createMul(Op1, SubOne(C1));
2728
2729 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2730 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Shengc7d7cdc2008-02-22 10:00:35 +00002731 return BinaryOperator::createMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 }
2733 return 0;
2734}
2735
2736/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2737/// comparison only checks the sign bit. If it only checks the sign bit, set
2738/// TrueIfSigned if the result of the comparison is true when the input value is
2739/// signed.
2740static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2741 bool &TrueIfSigned) {
2742 switch (pred) {
2743 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2744 TrueIfSigned = true;
2745 return RHS->isZero();
2746 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2747 TrueIfSigned = true;
2748 return RHS->isAllOnesValue();
2749 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2750 TrueIfSigned = false;
2751 return RHS->isAllOnesValue();
2752 case ICmpInst::ICMP_UGT:
2753 // True if LHS u> RHS and RHS == high-bit-mask - 1
2754 TrueIfSigned = true;
2755 return RHS->getValue() ==
2756 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2757 case ICmpInst::ICMP_UGE:
2758 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2759 TrueIfSigned = true;
2760 return RHS->getValue() ==
2761 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2762 default:
2763 return false;
2764 }
2765}
2766
2767Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2768 bool Changed = SimplifyCommutative(I);
2769 Value *Op0 = I.getOperand(0);
2770
2771 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773
2774 // Simplify mul instructions with a constant RHS...
2775 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2776 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2777
2778 // ((X << C1)*C2) == (X * (C2 << C1))
2779 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2780 if (SI->getOpcode() == Instruction::Shl)
2781 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2782 return BinaryOperator::createMul(SI->getOperand(0),
2783 ConstantExpr::getShl(CI, ShOp));
2784
2785 if (CI->isZero())
2786 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2787 if (CI->equalsInt(1)) // X * 1 == X
2788 return ReplaceInstUsesWith(I, Op0);
2789 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2790 return BinaryOperator::createNeg(Op0, I.getName());
2791
2792 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2793 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2794 return BinaryOperator::createShl(Op0,
2795 ConstantInt::get(Op0->getType(), Val.logBase2()));
2796 }
2797 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798 if (Op1F->isNullValue())
2799 return ReplaceInstUsesWith(I, Op1);
2800
2801 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2802 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002803 // We need a better interface for long double here.
2804 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2805 if (Op1F->isExactlyValue(1.0))
2806 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 }
2808
2809 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2810 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2811 isa<ConstantInt>(Op0I->getOperand(1))) {
2812 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2813 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2814 Op1, "tmp");
2815 InsertNewInstBefore(Add, I);
2816 Value *C1C2 = ConstantExpr::getMul(Op1,
2817 cast<Constant>(Op0I->getOperand(1)));
2818 return BinaryOperator::createAdd(Add, C1C2);
2819
2820 }
2821
2822 // Try to fold constant mul into select arguments.
2823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2824 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2825 return R;
2826
2827 if (isa<PHINode>(Op0))
2828 if (Instruction *NV = FoldOpIntoPhi(I))
2829 return NV;
2830 }
2831
2832 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2833 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2834 return BinaryOperator::createMul(Op0v, Op1v);
2835
2836 // If one of the operands of the multiply is a cast from a boolean value, then
2837 // we know the bool is either zero or one, so this is a 'masking' multiply.
2838 // See if we can simplify things based on how the boolean was originally
2839 // formed.
2840 CastInst *BoolCast = 0;
2841 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2842 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2843 BoolCast = CI;
2844 if (!BoolCast)
2845 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2846 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2847 BoolCast = CI;
2848 if (BoolCast) {
2849 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2850 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2851 const Type *SCOpTy = SCIOp0->getType();
2852 bool TIS = false;
2853
2854 // If the icmp is true iff the sign bit of X is set, then convert this
2855 // multiply into a shift/and combination.
2856 if (isa<ConstantInt>(SCIOp1) &&
2857 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2858 TIS) {
2859 // Shift the X value right to turn it into "all signbits".
2860 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2861 SCOpTy->getPrimitiveSizeInBits()-1);
2862 Value *V =
2863 InsertNewInstBefore(
2864 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2865 BoolCast->getOperand(0)->getName()+
2866 ".mask"), I);
2867
2868 // If the multiply type is not the same as the source type, sign extend
2869 // or truncate to the multiply type.
2870 if (I.getType() != V->getType()) {
2871 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2872 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2873 Instruction::CastOps opcode =
2874 (SrcBits == DstBits ? Instruction::BitCast :
2875 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2876 V = InsertCastBefore(opcode, V, I.getType(), I);
2877 }
2878
2879 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2880 return BinaryOperator::createAnd(V, OtherOp);
2881 }
2882 }
2883 }
2884
2885 return Changed ? &I : 0;
2886}
2887
2888/// This function implements the transforms on div instructions that work
2889/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2890/// used by the visitors to those instructions.
2891/// @brief Transforms common to all three div instructions
2892Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2894
Chris Lattner653ef3c2008-02-19 06:12:18 +00002895 // undef / X -> 0 for integer.
2896 // undef / X -> undef for FP (the undef could be a snan).
2897 if (isa<UndefValue>(Op0)) {
2898 if (Op0->getType()->isFPOrFPVector())
2899 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002900 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902
2903 // X / undef -> undef
2904 if (isa<UndefValue>(Op1))
2905 return ReplaceInstUsesWith(I, Op1);
2906
Chris Lattner5be238b2008-01-28 00:58:18 +00002907 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2908 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002910 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2911 // the same basic block, then we replace the select with Y, and the
2912 // condition of the select with false (if the cond value is in the same BB).
2913 // If the select has uses other than the div, this allows them to be
2914 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2915 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 if (ST->isNullValue()) {
2917 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2918 if (CondI && CondI->getParent() == I.getParent())
2919 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2920 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2921 I.setOperand(1, SI->getOperand(2));
2922 else
2923 UpdateValueUsesWith(SI, SI->getOperand(2));
2924 return &I;
2925 }
2926
Chris Lattner5be238b2008-01-28 00:58:18 +00002927 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2928 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002929 if (ST->isNullValue()) {
2930 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2931 if (CondI && CondI->getParent() == I.getParent())
2932 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2933 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2934 I.setOperand(1, SI->getOperand(1));
2935 else
2936 UpdateValueUsesWith(SI, SI->getOperand(1));
2937 return &I;
2938 }
2939 }
2940
2941 return 0;
2942}
2943
2944/// This function implements the transforms common to both integer division
2945/// instructions (udiv and sdiv). It is called by the visitors to those integer
2946/// division instructions.
2947/// @brief Common integer divide transforms
2948Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2950
2951 if (Instruction *Common = commonDivTransforms(I))
2952 return Common;
2953
2954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2955 // div X, 1 == X
2956 if (RHS->equalsInt(1))
2957 return ReplaceInstUsesWith(I, Op0);
2958
2959 // (X / C1) / C2 -> X / (C1*C2)
2960 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2961 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2962 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002963 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2965 else
2966 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2967 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002968 }
2969
2970 if (!RHS->isZero()) { // avoid X udiv 0
2971 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2972 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2973 return R;
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
2977 }
2978 }
2979
2980 // 0 / X == 0, we don't need to preserve faults!
2981 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2982 if (LHS->equalsInt(0))
2983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984
2985 return 0;
2986}
2987
2988Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2990
2991 // Handle the integer div common cases
2992 if (Instruction *Common = commonIDivTransforms(I))
2993 return Common;
2994
2995 // X udiv C^2 -> X >> C
2996 // Check to see if this is an unsigned division with an exact power of 2,
2997 // if so, convert to a right shift.
2998 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2999 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3000 return BinaryOperator::createLShr(Op0,
3001 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3002 }
3003
3004 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3005 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3006 if (RHSI->getOpcode() == Instruction::Shl &&
3007 isa<ConstantInt>(RHSI->getOperand(0))) {
3008 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3009 if (C1.isPowerOf2()) {
3010 Value *N = RHSI->getOperand(1);
3011 const Type *NTy = N->getType();
3012 if (uint32_t C2 = C1.logBase2()) {
3013 Constant *C2V = ConstantInt::get(NTy, C2);
3014 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
3015 }
3016 return BinaryOperator::createLShr(Op0, N);
3017 }
3018 }
3019 }
3020
3021 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3022 // where C1&C2 are powers of two.
3023 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3024 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3025 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3026 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3027 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3028 // Compute the shift amounts
3029 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3030 // Construct the "on true" case of the select
3031 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3032 Instruction *TSI = BinaryOperator::createLShr(
3033 Op0, TC, SI->getName()+".t");
3034 TSI = InsertNewInstBefore(TSI, I);
3035
3036 // Construct the "on false" case of the select
3037 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3038 Instruction *FSI = BinaryOperator::createLShr(
3039 Op0, FC, SI->getName()+".f");
3040 FSI = InsertNewInstBefore(FSI, I);
3041
3042 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003043 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003044 }
3045 }
3046 return 0;
3047}
3048
3049Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3051
3052 // Handle the integer div common cases
3053 if (Instruction *Common = commonIDivTransforms(I))
3054 return Common;
3055
3056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3057 // sdiv X, -1 == -X
3058 if (RHS->isAllOnesValue())
3059 return BinaryOperator::createNeg(Op0);
3060
3061 // -X/C -> X/-C
3062 if (Value *LHSNeg = dyn_castNegVal(Op0))
3063 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3064 }
3065
3066 // If the sign bits of both operands are zero (i.e. we can prove they are
3067 // unsigned inputs), turn this into a udiv.
3068 if (I.getType()->isInteger()) {
3069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3070 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003071 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3073 }
3074 }
3075
3076 return 0;
3077}
3078
3079Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3080 return commonDivTransforms(I);
3081}
3082
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083/// This function implements the transforms on rem instructions that work
3084/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3085/// is used by the visitors to those instructions.
3086/// @brief Transforms common to all three rem instructions
3087Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3088 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3089
Chris Lattner653ef3c2008-02-19 06:12:18 +00003090 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 if (Constant *LHS = dyn_cast<Constant>(Op0))
3092 if (LHS->isNullValue())
3093 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3094
Chris Lattner653ef3c2008-02-19 06:12:18 +00003095 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3096 if (I.getType()->isFPOrFPVector())
3097 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100 if (isa<UndefValue>(Op1))
3101 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3102
3103 // Handle cases involving: rem X, (select Cond, Y, Z)
3104 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3105 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3106 // the same basic block, then we replace the select with Y, and the
3107 // condition of the select with false (if the cond value is in the same
3108 // BB). If the select has uses other than the div, this allows them to be
3109 // simplified also.
3110 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3111 if (ST->isNullValue()) {
3112 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3113 if (CondI && CondI->getParent() == I.getParent())
3114 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3115 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3116 I.setOperand(1, SI->getOperand(2));
3117 else
3118 UpdateValueUsesWith(SI, SI->getOperand(2));
3119 return &I;
3120 }
3121 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3122 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3123 if (ST->isNullValue()) {
3124 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3125 if (CondI && CondI->getParent() == I.getParent())
3126 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3127 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3128 I.setOperand(1, SI->getOperand(1));
3129 else
3130 UpdateValueUsesWith(SI, SI->getOperand(1));
3131 return &I;
3132 }
3133 }
3134
3135 return 0;
3136}
3137
3138/// This function implements the transforms common to both integer remainder
3139/// instructions (urem and srem). It is called by the visitors to those integer
3140/// remainder instructions.
3141/// @brief Common integer remainder transforms
3142Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3144
3145 if (Instruction *common = commonRemTransforms(I))
3146 return common;
3147
3148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
3151 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152
3153 if (RHS->equalsInt(1)) // X % 1 == 0
3154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
3156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
3163 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
3166 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3167 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3168 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3169 KnownZero, KnownOne))
3170 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 }
3172 }
3173
3174 return 0;
3175}
3176
3177Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3178 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3179
3180 if (Instruction *common = commonIRemTransforms(I))
3181 return common;
3182
3183 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3184 // X urem C^2 -> X and C
3185 // Check to see if this is an unsigned remainder with an exact power of 2,
3186 // if so, convert to a bitwise and.
3187 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3188 if (C->getValue().isPowerOf2())
3189 return BinaryOperator::createAnd(Op0, SubOne(C));
3190 }
3191
3192 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3193 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3194 if (RHSI->getOpcode() == Instruction::Shl &&
3195 isa<ConstantInt>(RHSI->getOperand(0))) {
3196 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3197 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3198 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3199 "tmp"), I);
3200 return BinaryOperator::createAnd(Op0, Add);
3201 }
3202 }
3203 }
3204
3205 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3206 // where C1&C2 are powers of two.
3207 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3208 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3209 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3210 // STO == 0 and SFO == 0 handled above.
3211 if ((STO->getValue().isPowerOf2()) &&
3212 (SFO->getValue().isPowerOf2())) {
3213 Value *TrueAnd = InsertNewInstBefore(
3214 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3215 Value *FalseAnd = InsertNewInstBefore(
3216 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003217 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 }
3219 }
3220 }
3221
3222 return 0;
3223}
3224
3225Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227
Dan Gohmandb3dd962007-11-05 23:16:33 +00003228 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229 if (Instruction *common = commonIRemTransforms(I))
3230 return common;
3231
3232 if (Value *RHSNeg = dyn_castNegVal(Op1))
3233 if (!isa<ConstantInt>(RHSNeg) ||
3234 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3235 // X % -Y -> X % Y
3236 AddUsesToWorkList(I);
3237 I.setOperand(1, RHSNeg);
3238 return &I;
3239 }
3240
Dan Gohmandb3dd962007-11-05 23:16:33 +00003241 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003243 if (I.getType()->isInteger()) {
3244 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3245 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3246 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3247 return BinaryOperator::createURem(Op0, Op1, I.getName());
3248 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 }
3250
3251 return 0;
3252}
3253
3254Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3255 return commonRemTransforms(I);
3256}
3257
3258// isMaxValueMinusOne - return true if this is Max-1
3259static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3260 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3261 if (!isSigned)
3262 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3263 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3264}
3265
3266// isMinValuePlusOne - return true if this is Min+1
3267static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3268 if (!isSigned)
3269 return C->getValue() == 1; // unsigned
3270
3271 // Calculate 1111111111000000000000
3272 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3273 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3274}
3275
3276// isOneBitSet - Return true if there is exactly one bit set in the specified
3277// constant.
3278static bool isOneBitSet(const ConstantInt *CI) {
3279 return CI->getValue().isPowerOf2();
3280}
3281
3282// isHighOnes - Return true if the constant is of the form 1+0+.
3283// This is the same as lowones(~X).
3284static bool isHighOnes(const ConstantInt *CI) {
3285 return (~CI->getValue() + 1).isPowerOf2();
3286}
3287
3288/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3289/// are carefully arranged to allow folding of expressions such as:
3290///
3291/// (A < B) | (A > B) --> (A != B)
3292///
3293/// Note that this is only valid if the first and second predicates have the
3294/// same sign. Is illegal to do: (A u< B) | (A s> B)
3295///
3296/// Three bits are used to represent the condition, as follows:
3297/// 0 A > B
3298/// 1 A == B
3299/// 2 A < B
3300///
3301/// <=> Value Definition
3302/// 000 0 Always false
3303/// 001 1 A > B
3304/// 010 2 A == B
3305/// 011 3 A >= B
3306/// 100 4 A < B
3307/// 101 5 A != B
3308/// 110 6 A <= B
3309/// 111 7 Always true
3310///
3311static unsigned getICmpCode(const ICmpInst *ICI) {
3312 switch (ICI->getPredicate()) {
3313 // False -> 0
3314 case ICmpInst::ICMP_UGT: return 1; // 001
3315 case ICmpInst::ICMP_SGT: return 1; // 001
3316 case ICmpInst::ICMP_EQ: return 2; // 010
3317 case ICmpInst::ICMP_UGE: return 3; // 011
3318 case ICmpInst::ICMP_SGE: return 3; // 011
3319 case ICmpInst::ICMP_ULT: return 4; // 100
3320 case ICmpInst::ICMP_SLT: return 4; // 100
3321 case ICmpInst::ICMP_NE: return 5; // 101
3322 case ICmpInst::ICMP_ULE: return 6; // 110
3323 case ICmpInst::ICMP_SLE: return 6; // 110
3324 // True -> 7
3325 default:
3326 assert(0 && "Invalid ICmp predicate!");
3327 return 0;
3328 }
3329}
3330
3331/// getICmpValue - This is the complement of getICmpCode, which turns an
3332/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003333/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003334/// of predicate to use in new icmp instructions.
3335static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3336 switch (code) {
3337 default: assert(0 && "Illegal ICmp code!");
3338 case 0: return ConstantInt::getFalse();
3339 case 1:
3340 if (sign)
3341 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3342 else
3343 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3344 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3345 case 3:
3346 if (sign)
3347 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3348 else
3349 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3350 case 4:
3351 if (sign)
3352 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3353 else
3354 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3355 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3356 case 6:
3357 if (sign)
3358 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3359 else
3360 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3361 case 7: return ConstantInt::getTrue();
3362 }
3363}
3364
3365static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3366 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3367 (ICmpInst::isSignedPredicate(p1) &&
3368 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3369 (ICmpInst::isSignedPredicate(p2) &&
3370 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3371}
3372
3373namespace {
3374// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3375struct FoldICmpLogical {
3376 InstCombiner &IC;
3377 Value *LHS, *RHS;
3378 ICmpInst::Predicate pred;
3379 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3380 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3381 pred(ICI->getPredicate()) {}
3382 bool shouldApply(Value *V) const {
3383 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3384 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003385 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3386 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 return false;
3388 }
3389 Instruction *apply(Instruction &Log) const {
3390 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3391 if (ICI->getOperand(0) != LHS) {
3392 assert(ICI->getOperand(1) == LHS);
3393 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3394 }
3395
3396 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3397 unsigned LHSCode = getICmpCode(ICI);
3398 unsigned RHSCode = getICmpCode(RHSICI);
3399 unsigned Code;
3400 switch (Log.getOpcode()) {
3401 case Instruction::And: Code = LHSCode & RHSCode; break;
3402 case Instruction::Or: Code = LHSCode | RHSCode; break;
3403 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3404 default: assert(0 && "Illegal logical opcode!"); return 0;
3405 }
3406
3407 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3408 ICmpInst::isSignedPredicate(ICI->getPredicate());
3409
3410 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3411 if (Instruction *I = dyn_cast<Instruction>(RV))
3412 return I;
3413 // Otherwise, it's a constant boolean value...
3414 return IC.ReplaceInstUsesWith(Log, RV);
3415 }
3416};
3417} // end anonymous namespace
3418
3419// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3420// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3421// guaranteed to be a binary operator.
3422Instruction *InstCombiner::OptAndOp(Instruction *Op,
3423 ConstantInt *OpRHS,
3424 ConstantInt *AndRHS,
3425 BinaryOperator &TheAnd) {
3426 Value *X = Op->getOperand(0);
3427 Constant *Together = 0;
3428 if (!Op->isShift())
3429 Together = And(AndRHS, OpRHS);
3430
3431 switch (Op->getOpcode()) {
3432 case Instruction::Xor:
3433 if (Op->hasOneUse()) {
3434 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3435 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3436 InsertNewInstBefore(And, TheAnd);
3437 And->takeName(Op);
3438 return BinaryOperator::createXor(And, Together);
3439 }
3440 break;
3441 case Instruction::Or:
3442 if (Together == AndRHS) // (X | C) & C --> C
3443 return ReplaceInstUsesWith(TheAnd, AndRHS);
3444
3445 if (Op->hasOneUse() && Together != OpRHS) {
3446 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3447 Instruction *Or = BinaryOperator::createOr(X, Together);
3448 InsertNewInstBefore(Or, TheAnd);
3449 Or->takeName(Op);
3450 return BinaryOperator::createAnd(Or, AndRHS);
3451 }
3452 break;
3453 case Instruction::Add:
3454 if (Op->hasOneUse()) {
3455 // Adding a one to a single bit bit-field should be turned into an XOR
3456 // of the bit. First thing to check is to see if this AND is with a
3457 // single bit constant.
3458 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3459
3460 // If there is only one bit set...
3461 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3462 // Ok, at this point, we know that we are masking the result of the
3463 // ADD down to exactly one bit. If the constant we are adding has
3464 // no bits set below this bit, then we can eliminate the ADD.
3465 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3466
3467 // Check to see if any bits below the one bit set in AndRHSV are set.
3468 if ((AddRHS & (AndRHSV-1)) == 0) {
3469 // If not, the only thing that can effect the output of the AND is
3470 // the bit specified by AndRHSV. If that bit is set, the effect of
3471 // the XOR is to toggle the bit. If it is clear, then the ADD has
3472 // no effect.
3473 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3474 TheAnd.setOperand(0, X);
3475 return &TheAnd;
3476 } else {
3477 // Pull the XOR out of the AND.
3478 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3479 InsertNewInstBefore(NewAnd, TheAnd);
3480 NewAnd->takeName(Op);
3481 return BinaryOperator::createXor(NewAnd, AndRHS);
3482 }
3483 }
3484 }
3485 }
3486 break;
3487
3488 case Instruction::Shl: {
3489 // We know that the AND will not produce any of the bits shifted in, so if
3490 // the anded constant includes them, clear them now!
3491 //
3492 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3493 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3494 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3495 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3496
3497 if (CI->getValue() == ShlMask) {
3498 // Masking out bits that the shift already masks
3499 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3500 } else if (CI != AndRHS) { // Reducing bits set in and.
3501 TheAnd.setOperand(1, CI);
3502 return &TheAnd;
3503 }
3504 break;
3505 }
3506 case Instruction::LShr:
3507 {
3508 // We know that the AND will not produce any of the bits shifted in, so if
3509 // the anded constant includes them, clear them now! This only applies to
3510 // unsigned shifts, because a signed shr may bring in set bits!
3511 //
3512 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3513 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3514 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3515 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3516
3517 if (CI->getValue() == ShrMask) {
3518 // Masking out bits that the shift already masks.
3519 return ReplaceInstUsesWith(TheAnd, Op);
3520 } else if (CI != AndRHS) {
3521 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3522 return &TheAnd;
3523 }
3524 break;
3525 }
3526 case Instruction::AShr:
3527 // Signed shr.
3528 // See if this is shifting in some sign extension, then masking it out
3529 // with an and.
3530 if (Op->hasOneUse()) {
3531 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3532 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3533 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3534 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3535 if (C == AndRHS) { // Masking out bits shifted in.
3536 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3537 // Make the argument unsigned.
3538 Value *ShVal = Op->getOperand(0);
3539 ShVal = InsertNewInstBefore(
3540 BinaryOperator::createLShr(ShVal, OpRHS,
3541 Op->getName()), TheAnd);
3542 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3543 }
3544 }
3545 break;
3546 }
3547 return 0;
3548}
3549
3550
3551/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3552/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3553/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3554/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3555/// insert new instructions.
3556Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3557 bool isSigned, bool Inside,
3558 Instruction &IB) {
3559 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3560 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3561 "Lo is not <= Hi in range emission code!");
3562
3563 if (Inside) {
3564 if (Lo == Hi) // Trivially false.
3565 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3566
3567 // V >= Min && V < Hi --> V < Hi
3568 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3569 ICmpInst::Predicate pred = (isSigned ?
3570 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3571 return new ICmpInst(pred, V, Hi);
3572 }
3573
3574 // Emit V-Lo <u Hi-Lo
3575 Constant *NegLo = ConstantExpr::getNeg(Lo);
3576 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3577 InsertNewInstBefore(Add, IB);
3578 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3579 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3580 }
3581
3582 if (Lo == Hi) // Trivially true.
3583 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3584
3585 // V < Min || V >= Hi -> V > Hi-1
3586 Hi = SubOne(cast<ConstantInt>(Hi));
3587 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3588 ICmpInst::Predicate pred = (isSigned ?
3589 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3590 return new ICmpInst(pred, V, Hi);
3591 }
3592
3593 // Emit V-Lo >u Hi-1-Lo
3594 // Note that Hi has already had one subtracted from it, above.
3595 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3596 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3597 InsertNewInstBefore(Add, IB);
3598 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3599 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3600}
3601
3602// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3603// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3604// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3605// not, since all 1s are not contiguous.
3606static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3607 const APInt& V = Val->getValue();
3608 uint32_t BitWidth = Val->getType()->getBitWidth();
3609 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3610
3611 // look for the first zero bit after the run of ones
3612 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3613 // look for the first non-zero bit
3614 ME = V.getActiveBits();
3615 return true;
3616}
3617
3618/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3619/// where isSub determines whether the operator is a sub. If we can fold one of
3620/// the following xforms:
3621///
3622/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3623/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3624/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3625///
3626/// return (A +/- B).
3627///
3628Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3629 ConstantInt *Mask, bool isSub,
3630 Instruction &I) {
3631 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3632 if (!LHSI || LHSI->getNumOperands() != 2 ||
3633 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3634
3635 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3636
3637 switch (LHSI->getOpcode()) {
3638 default: return 0;
3639 case Instruction::And:
3640 if (And(N, Mask) == Mask) {
3641 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3642 if ((Mask->getValue().countLeadingZeros() +
3643 Mask->getValue().countPopulation()) ==
3644 Mask->getValue().getBitWidth())
3645 break;
3646
3647 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3648 // part, we don't need any explicit masks to take them out of A. If that
3649 // is all N is, ignore it.
3650 uint32_t MB = 0, ME = 0;
3651 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3652 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3653 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3654 if (MaskedValueIsZero(RHS, Mask))
3655 break;
3656 }
3657 }
3658 return 0;
3659 case Instruction::Or:
3660 case Instruction::Xor:
3661 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3662 if ((Mask->getValue().countLeadingZeros() +
3663 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3664 && And(N, Mask)->isZero())
3665 break;
3666 return 0;
3667 }
3668
3669 Instruction *New;
3670 if (isSub)
3671 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3672 else
3673 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3674 return InsertNewInstBefore(New, I);
3675}
3676
3677Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3678 bool Changed = SimplifyCommutative(I);
3679 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3680
3681 if (isa<UndefValue>(Op1)) // X & undef -> 0
3682 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3683
3684 // and X, X = X
3685 if (Op0 == Op1)
3686 return ReplaceInstUsesWith(I, Op1);
3687
3688 // See if we can simplify any instructions used by the instruction whose sole
3689 // purpose is to compute bits we don't care about.
3690 if (!isa<VectorType>(I.getType())) {
3691 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3692 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3693 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3694 KnownZero, KnownOne))
3695 return &I;
3696 } else {
3697 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3698 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3699 return ReplaceInstUsesWith(I, I.getOperand(0));
3700 } else if (isa<ConstantAggregateZero>(Op1)) {
3701 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3702 }
3703 }
3704
3705 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3706 const APInt& AndRHSMask = AndRHS->getValue();
3707 APInt NotAndRHS(~AndRHSMask);
3708
3709 // Optimize a variety of ((val OP C1) & C2) combinations...
3710 if (isa<BinaryOperator>(Op0)) {
3711 Instruction *Op0I = cast<Instruction>(Op0);
3712 Value *Op0LHS = Op0I->getOperand(0);
3713 Value *Op0RHS = Op0I->getOperand(1);
3714 switch (Op0I->getOpcode()) {
3715 case Instruction::Xor:
3716 case Instruction::Or:
3717 // If the mask is only needed on one incoming arm, push it up.
3718 if (Op0I->hasOneUse()) {
3719 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3720 // Not masking anything out for the LHS, move to RHS.
3721 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3722 Op0RHS->getName()+".masked");
3723 InsertNewInstBefore(NewRHS, I);
3724 return BinaryOperator::create(
3725 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3726 }
3727 if (!isa<Constant>(Op0RHS) &&
3728 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3729 // Not masking anything out for the RHS, move to LHS.
3730 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3731 Op0LHS->getName()+".masked");
3732 InsertNewInstBefore(NewLHS, I);
3733 return BinaryOperator::create(
3734 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3735 }
3736 }
3737
3738 break;
3739 case Instruction::Add:
3740 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3741 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3742 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3743 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3744 return BinaryOperator::createAnd(V, AndRHS);
3745 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3746 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3747 break;
3748
3749 case Instruction::Sub:
3750 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3751 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3752 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3753 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3754 return BinaryOperator::createAnd(V, AndRHS);
3755 break;
3756 }
3757
3758 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3759 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3760 return Res;
3761 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3762 // If this is an integer truncation or change from signed-to-unsigned, and
3763 // if the source is an and/or with immediate, transform it. This
3764 // frequently occurs for bitfield accesses.
3765 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3766 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3767 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003768 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 if (CastOp->getOpcode() == Instruction::And) {
3770 // Change: and (cast (and X, C1) to T), C2
3771 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3772 // This will fold the two constants together, which may allow
3773 // other simplifications.
3774 Instruction *NewCast = CastInst::createTruncOrBitCast(
3775 CastOp->getOperand(0), I.getType(),
3776 CastOp->getName()+".shrunk");
3777 NewCast = InsertNewInstBefore(NewCast, I);
3778 // trunc_or_bitcast(C1)&C2
3779 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3780 C3 = ConstantExpr::getAnd(C3, AndRHS);
3781 return BinaryOperator::createAnd(NewCast, C3);
3782 } else if (CastOp->getOpcode() == Instruction::Or) {
3783 // Change: and (cast (or X, C1) to T), C2
3784 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3785 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3786 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3787 return ReplaceInstUsesWith(I, AndRHS);
3788 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003789 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 }
3791 }
3792
3793 // Try to fold constant and into select arguments.
3794 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3795 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3796 return R;
3797 if (isa<PHINode>(Op0))
3798 if (Instruction *NV = FoldOpIntoPhi(I))
3799 return NV;
3800 }
3801
3802 Value *Op0NotVal = dyn_castNotVal(Op0);
3803 Value *Op1NotVal = dyn_castNotVal(Op1);
3804
3805 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3806 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3807
3808 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3809 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3810 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3811 I.getName()+".demorgan");
3812 InsertNewInstBefore(Or, I);
3813 return BinaryOperator::createNot(Or);
3814 }
3815
3816 {
3817 Value *A = 0, *B = 0, *C = 0, *D = 0;
3818 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3819 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3820 return ReplaceInstUsesWith(I, Op1);
3821
3822 // (A|B) & ~(A&B) -> A^B
3823 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3824 if ((A == C && B == D) || (A == D && B == C))
3825 return BinaryOperator::createXor(A, B);
3826 }
3827 }
3828
3829 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3830 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3831 return ReplaceInstUsesWith(I, Op0);
3832
3833 // ~(A&B) & (A|B) -> A^B
3834 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3835 if ((A == C && B == D) || (A == D && B == C))
3836 return BinaryOperator::createXor(A, B);
3837 }
3838 }
3839
3840 if (Op0->hasOneUse() &&
3841 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3842 if (A == Op1) { // (A^B)&A -> A&(A^B)
3843 I.swapOperands(); // Simplify below
3844 std::swap(Op0, Op1);
3845 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3846 cast<BinaryOperator>(Op0)->swapOperands();
3847 I.swapOperands(); // Simplify below
3848 std::swap(Op0, Op1);
3849 }
3850 }
3851 if (Op1->hasOneUse() &&
3852 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3853 if (B == Op0) { // B&(A^B) -> B&(B^A)
3854 cast<BinaryOperator>(Op1)->swapOperands();
3855 std::swap(A, B);
3856 }
3857 if (A == Op0) { // A&(A^B) -> A & ~B
3858 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3859 InsertNewInstBefore(NotB, I);
3860 return BinaryOperator::createAnd(A, NotB);
3861 }
3862 }
3863 }
3864
3865 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3866 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3867 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3868 return R;
3869
3870 Value *LHSVal, *RHSVal;
3871 ConstantInt *LHSCst, *RHSCst;
3872 ICmpInst::Predicate LHSCC, RHSCC;
3873 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3874 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3875 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3876 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3877 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3878 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3879 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003880 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3881
3882 // Don't try to fold ICMP_SLT + ICMP_ULT.
3883 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3884 ICmpInst::isSignedPredicate(LHSCC) ==
3885 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003886 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003887 ICmpInst::Predicate GT;
3888 if (ICmpInst::isSignedPredicate(LHSCC) ||
3889 (ICmpInst::isEquality(LHSCC) &&
3890 ICmpInst::isSignedPredicate(RHSCC)))
3891 GT = ICmpInst::ICMP_SGT;
3892 else
3893 GT = ICmpInst::ICMP_UGT;
3894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3896 ICmpInst *LHS = cast<ICmpInst>(Op0);
3897 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3898 std::swap(LHS, RHS);
3899 std::swap(LHSCst, RHSCst);
3900 std::swap(LHSCC, RHSCC);
3901 }
3902
3903 // At this point, we know we have have two icmp instructions
3904 // comparing a value against two constants and and'ing the result
3905 // together. Because of the above check, we know that we only have
3906 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3907 // (from the FoldICmpLogical check above), that the two constants
3908 // are not equal and that the larger constant is on the RHS
3909 assert(LHSCst != RHSCst && "Compares not folded above?");
3910
3911 switch (LHSCC) {
3912 default: assert(0 && "Unknown integer condition code!");
3913 case ICmpInst::ICMP_EQ:
3914 switch (RHSCC) {
3915 default: assert(0 && "Unknown integer condition code!");
3916 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3917 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3918 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3919 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3920 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3921 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3922 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3923 return ReplaceInstUsesWith(I, LHS);
3924 }
3925 case ICmpInst::ICMP_NE:
3926 switch (RHSCC) {
3927 default: assert(0 && "Unknown integer condition code!");
3928 case ICmpInst::ICMP_ULT:
3929 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3930 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3931 break; // (X != 13 & X u< 15) -> no change
3932 case ICmpInst::ICMP_SLT:
3933 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3934 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3935 break; // (X != 13 & X s< 15) -> no change
3936 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3937 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3938 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3939 return ReplaceInstUsesWith(I, RHS);
3940 case ICmpInst::ICMP_NE:
3941 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3942 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3943 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3944 LHSVal->getName()+".off");
3945 InsertNewInstBefore(Add, I);
3946 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3947 ConstantInt::get(Add->getType(), 1));
3948 }
3949 break; // (X != 13 & X != 15) -> no change
3950 }
3951 break;
3952 case ICmpInst::ICMP_ULT:
3953 switch (RHSCC) {
3954 default: assert(0 && "Unknown integer condition code!");
3955 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3956 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3957 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3958 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3959 break;
3960 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3961 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3962 return ReplaceInstUsesWith(I, LHS);
3963 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3964 break;
3965 }
3966 break;
3967 case ICmpInst::ICMP_SLT:
3968 switch (RHSCC) {
3969 default: assert(0 && "Unknown integer condition code!");
3970 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3971 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3972 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3973 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3974 break;
3975 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3976 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3977 return ReplaceInstUsesWith(I, LHS);
3978 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3979 break;
3980 }
3981 break;
3982 case ICmpInst::ICMP_UGT:
3983 switch (RHSCC) {
3984 default: assert(0 && "Unknown integer condition code!");
3985 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3986 return ReplaceInstUsesWith(I, LHS);
3987 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3988 return ReplaceInstUsesWith(I, RHS);
3989 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3990 break;
3991 case ICmpInst::ICMP_NE:
3992 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3993 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3994 break; // (X u> 13 & X != 15) -> no change
3995 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3996 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3997 true, I);
3998 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3999 break;
4000 }
4001 break;
4002 case ICmpInst::ICMP_SGT:
4003 switch (RHSCC) {
4004 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004005 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004006 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4007 return ReplaceInstUsesWith(I, RHS);
4008 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4009 break;
4010 case ICmpInst::ICMP_NE:
4011 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4012 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4013 break; // (X s> 13 & X != 15) -> no change
4014 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4015 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4016 true, I);
4017 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4018 break;
4019 }
4020 break;
4021 }
4022 }
4023 }
4024
4025 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4026 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4027 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4028 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4029 const Type *SrcTy = Op0C->getOperand(0)->getType();
4030 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4031 // Only do this if the casts both really cause code to be generated.
4032 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4033 I.getType(), TD) &&
4034 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4035 I.getType(), TD)) {
4036 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4037 Op1C->getOperand(0),
4038 I.getName());
4039 InsertNewInstBefore(NewOp, I);
4040 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4041 }
4042 }
4043
4044 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4045 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4046 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4047 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4048 SI0->getOperand(1) == SI1->getOperand(1) &&
4049 (SI0->hasOneUse() || SI1->hasOneUse())) {
4050 Instruction *NewOp =
4051 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4052 SI1->getOperand(0),
4053 SI0->getName()), I);
4054 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4055 SI1->getOperand(1));
4056 }
4057 }
4058
Chris Lattner91882432007-10-24 05:38:08 +00004059 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4060 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4061 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4062 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4063 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4064 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4065 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4066 // If either of the constants are nans, then the whole thing returns
4067 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004068 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004069 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4070 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4071 RHS->getOperand(0));
4072 }
4073 }
4074 }
4075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 return Changed ? &I : 0;
4077}
4078
4079/// CollectBSwapParts - Look to see if the specified value defines a single byte
4080/// in the result. If it does, and if the specified byte hasn't been filled in
4081/// yet, fill it in and return false.
4082static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4083 Instruction *I = dyn_cast<Instruction>(V);
4084 if (I == 0) return true;
4085
4086 // If this is an or instruction, it is an inner node of the bswap.
4087 if (I->getOpcode() == Instruction::Or)
4088 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4089 CollectBSwapParts(I->getOperand(1), ByteValues);
4090
4091 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4092 // If this is a shift by a constant int, and it is "24", then its operand
4093 // defines a byte. We only handle unsigned types here.
4094 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4095 // Not shifting the entire input by N-1 bytes?
4096 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4097 8*(ByteValues.size()-1))
4098 return true;
4099
4100 unsigned DestNo;
4101 if (I->getOpcode() == Instruction::Shl) {
4102 // X << 24 defines the top byte with the lowest of the input bytes.
4103 DestNo = ByteValues.size()-1;
4104 } else {
4105 // X >>u 24 defines the low byte with the highest of the input bytes.
4106 DestNo = 0;
4107 }
4108
4109 // If the destination byte value is already defined, the values are or'd
4110 // together, which isn't a bswap (unless it's an or of the same bits).
4111 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4112 return true;
4113 ByteValues[DestNo] = I->getOperand(0);
4114 return false;
4115 }
4116
4117 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4118 // don't have this.
4119 Value *Shift = 0, *ShiftLHS = 0;
4120 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4121 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4122 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4123 return true;
4124 Instruction *SI = cast<Instruction>(Shift);
4125
4126 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4127 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4128 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4129 return true;
4130
4131 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4132 unsigned DestByte;
4133 if (AndAmt->getValue().getActiveBits() > 64)
4134 return true;
4135 uint64_t AndAmtVal = AndAmt->getZExtValue();
4136 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4137 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4138 break;
4139 // Unknown mask for bswap.
4140 if (DestByte == ByteValues.size()) return true;
4141
4142 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4143 unsigned SrcByte;
4144 if (SI->getOpcode() == Instruction::Shl)
4145 SrcByte = DestByte - ShiftBytes;
4146 else
4147 SrcByte = DestByte + ShiftBytes;
4148
4149 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4150 if (SrcByte != ByteValues.size()-DestByte-1)
4151 return true;
4152
4153 // If the destination byte value is already defined, the values are or'd
4154 // together, which isn't a bswap (unless it's an or of the same bits).
4155 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4156 return true;
4157 ByteValues[DestByte] = SI->getOperand(0);
4158 return false;
4159}
4160
4161/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4162/// If so, insert the new bswap intrinsic and return it.
4163Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4164 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4165 if (!ITy || ITy->getBitWidth() % 16)
4166 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4167
4168 /// ByteValues - For each byte of the result, we keep track of which value
4169 /// defines each byte.
4170 SmallVector<Value*, 8> ByteValues;
4171 ByteValues.resize(ITy->getBitWidth()/8);
4172
4173 // Try to find all the pieces corresponding to the bswap.
4174 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4175 CollectBSwapParts(I.getOperand(1), ByteValues))
4176 return 0;
4177
4178 // Check to see if all of the bytes come from the same value.
4179 Value *V = ByteValues[0];
4180 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4181
4182 // Check to make sure that all of the bytes come from the same value.
4183 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4184 if (ByteValues[i] != V)
4185 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004186 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004188 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004189 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004190}
4191
4192
4193Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4194 bool Changed = SimplifyCommutative(I);
4195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4196
4197 if (isa<UndefValue>(Op1)) // X | undef -> -1
4198 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4199
4200 // or X, X = X
4201 if (Op0 == Op1)
4202 return ReplaceInstUsesWith(I, Op0);
4203
4204 // See if we can simplify any instructions used by the instruction whose sole
4205 // purpose is to compute bits we don't care about.
4206 if (!isa<VectorType>(I.getType())) {
4207 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4208 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4209 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4210 KnownZero, KnownOne))
4211 return &I;
4212 } else if (isa<ConstantAggregateZero>(Op1)) {
4213 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4214 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4215 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4216 return ReplaceInstUsesWith(I, I.getOperand(1));
4217 }
4218
4219
4220
4221 // or X, -1 == -1
4222 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4223 ConstantInt *C1 = 0; Value *X = 0;
4224 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4225 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4226 Instruction *Or = BinaryOperator::createOr(X, RHS);
4227 InsertNewInstBefore(Or, I);
4228 Or->takeName(Op0);
4229 return BinaryOperator::createAnd(Or,
4230 ConstantInt::get(RHS->getValue() | C1->getValue()));
4231 }
4232
4233 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4234 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4235 Instruction *Or = BinaryOperator::createOr(X, RHS);
4236 InsertNewInstBefore(Or, I);
4237 Or->takeName(Op0);
4238 return BinaryOperator::createXor(Or,
4239 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4240 }
4241
4242 // Try to fold constant and into select arguments.
4243 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4244 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4245 return R;
4246 if (isa<PHINode>(Op0))
4247 if (Instruction *NV = FoldOpIntoPhi(I))
4248 return NV;
4249 }
4250
4251 Value *A = 0, *B = 0;
4252 ConstantInt *C1 = 0, *C2 = 0;
4253
4254 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4255 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4256 return ReplaceInstUsesWith(I, Op1);
4257 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4258 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4259 return ReplaceInstUsesWith(I, Op0);
4260
4261 // (A | B) | C and A | (B | C) -> bswap if possible.
4262 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4263 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4264 match(Op1, m_Or(m_Value(), m_Value())) ||
4265 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4266 match(Op1, m_Shift(m_Value(), m_Value())))) {
4267 if (Instruction *BSwap = MatchBSwap(I))
4268 return BSwap;
4269 }
4270
4271 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4272 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4273 MaskedValueIsZero(Op1, C1->getValue())) {
4274 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4275 InsertNewInstBefore(NOr, I);
4276 NOr->takeName(Op0);
4277 return BinaryOperator::createXor(NOr, C1);
4278 }
4279
4280 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4281 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4282 MaskedValueIsZero(Op0, C1->getValue())) {
4283 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4284 InsertNewInstBefore(NOr, I);
4285 NOr->takeName(Op0);
4286 return BinaryOperator::createXor(NOr, C1);
4287 }
4288
4289 // (A & C)|(B & D)
4290 Value *C = 0, *D = 0;
4291 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4292 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4293 Value *V1 = 0, *V2 = 0, *V3 = 0;
4294 C1 = dyn_cast<ConstantInt>(C);
4295 C2 = dyn_cast<ConstantInt>(D);
4296 if (C1 && C2) { // (A & C1)|(B & C2)
4297 // If we have: ((V + N) & C1) | (V & C2)
4298 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4299 // replace with V+N.
4300 if (C1->getValue() == ~C2->getValue()) {
4301 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4302 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4303 // Add commutes, try both ways.
4304 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4305 return ReplaceInstUsesWith(I, A);
4306 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4307 return ReplaceInstUsesWith(I, A);
4308 }
4309 // Or commutes, try both ways.
4310 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4311 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4312 // Add commutes, try both ways.
4313 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4314 return ReplaceInstUsesWith(I, B);
4315 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4316 return ReplaceInstUsesWith(I, B);
4317 }
4318 }
4319 V1 = 0; V2 = 0; V3 = 0;
4320 }
4321
4322 // Check to see if we have any common things being and'ed. If so, find the
4323 // terms for V1 & (V2|V3).
4324 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4325 if (A == B) // (A & C)|(A & D) == A & (C|D)
4326 V1 = A, V2 = C, V3 = D;
4327 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4328 V1 = A, V2 = B, V3 = C;
4329 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4330 V1 = C, V2 = A, V3 = D;
4331 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4332 V1 = C, V2 = A, V3 = B;
4333
4334 if (V1) {
4335 Value *Or =
4336 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4337 return BinaryOperator::createAnd(V1, Or);
4338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004339 }
4340 }
4341
4342 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4343 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4344 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4345 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4346 SI0->getOperand(1) == SI1->getOperand(1) &&
4347 (SI0->hasOneUse() || SI1->hasOneUse())) {
4348 Instruction *NewOp =
4349 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4350 SI1->getOperand(0),
4351 SI0->getName()), I);
4352 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4353 SI1->getOperand(1));
4354 }
4355 }
4356
4357 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4358 if (A == Op1) // ~A | A == -1
4359 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4360 } else {
4361 A = 0;
4362 }
4363 // Note, A is still live here!
4364 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4365 if (Op0 == B)
4366 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4367
4368 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4369 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4370 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4371 I.getName()+".demorgan"), I);
4372 return BinaryOperator::createNot(And);
4373 }
4374 }
4375
4376 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4377 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4378 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4379 return R;
4380
4381 Value *LHSVal, *RHSVal;
4382 ConstantInt *LHSCst, *RHSCst;
4383 ICmpInst::Predicate LHSCC, RHSCC;
4384 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4385 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4386 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4387 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4388 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4389 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4390 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4391 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4392 // We can't fold (ugt x, C) | (sgt x, C2).
4393 PredicatesFoldable(LHSCC, RHSCC)) {
4394 // Ensure that the larger constant is on the RHS.
4395 ICmpInst *LHS = cast<ICmpInst>(Op0);
4396 bool NeedsSwap;
4397 if (ICmpInst::isSignedPredicate(LHSCC))
4398 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4399 else
4400 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4401
4402 if (NeedsSwap) {
4403 std::swap(LHS, RHS);
4404 std::swap(LHSCst, RHSCst);
4405 std::swap(LHSCC, RHSCC);
4406 }
4407
4408 // At this point, we know we have have two icmp instructions
4409 // comparing a value against two constants and or'ing the result
4410 // together. Because of the above check, we know that we only have
4411 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4412 // FoldICmpLogical check above), that the two constants are not
4413 // equal.
4414 assert(LHSCst != RHSCst && "Compares not folded above?");
4415
4416 switch (LHSCC) {
4417 default: assert(0 && "Unknown integer condition code!");
4418 case ICmpInst::ICMP_EQ:
4419 switch (RHSCC) {
4420 default: assert(0 && "Unknown integer condition code!");
4421 case ICmpInst::ICMP_EQ:
4422 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4423 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4424 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4425 LHSVal->getName()+".off");
4426 InsertNewInstBefore(Add, I);
4427 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4428 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4429 }
4430 break; // (X == 13 | X == 15) -> no change
4431 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4432 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4433 break;
4434 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4435 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4436 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4437 return ReplaceInstUsesWith(I, RHS);
4438 }
4439 break;
4440 case ICmpInst::ICMP_NE:
4441 switch (RHSCC) {
4442 default: assert(0 && "Unknown integer condition code!");
4443 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4444 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4445 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4446 return ReplaceInstUsesWith(I, LHS);
4447 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4448 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4449 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4450 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4451 }
4452 break;
4453 case ICmpInst::ICMP_ULT:
4454 switch (RHSCC) {
4455 default: assert(0 && "Unknown integer condition code!");
4456 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4457 break;
4458 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004459 // If RHSCst is [us]MAXINT, it is always false. Not handling
4460 // this can cause overflow.
4461 if (RHSCst->isMaxValue(false))
4462 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004463 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4464 false, I);
4465 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4466 break;
4467 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4468 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4469 return ReplaceInstUsesWith(I, RHS);
4470 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4471 break;
4472 }
4473 break;
4474 case ICmpInst::ICMP_SLT:
4475 switch (RHSCC) {
4476 default: assert(0 && "Unknown integer condition code!");
4477 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4478 break;
4479 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004480 // If RHSCst is [us]MAXINT, it is always false. Not handling
4481 // this can cause overflow.
4482 if (RHSCst->isMaxValue(true))
4483 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004484 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4485 false, I);
4486 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4487 break;
4488 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4489 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4490 return ReplaceInstUsesWith(I, RHS);
4491 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4492 break;
4493 }
4494 break;
4495 case ICmpInst::ICMP_UGT:
4496 switch (RHSCC) {
4497 default: assert(0 && "Unknown integer condition code!");
4498 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4499 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4500 return ReplaceInstUsesWith(I, LHS);
4501 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4502 break;
4503 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4504 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4505 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4506 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4507 break;
4508 }
4509 break;
4510 case ICmpInst::ICMP_SGT:
4511 switch (RHSCC) {
4512 default: assert(0 && "Unknown integer condition code!");
4513 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4514 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4515 return ReplaceInstUsesWith(I, LHS);
4516 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4517 break;
4518 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4519 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4520 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4521 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4522 break;
4523 }
4524 break;
4525 }
4526 }
4527 }
4528
4529 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004530 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4532 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004533 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4534 !isa<ICmpInst>(Op1C->getOperand(0))) {
4535 const Type *SrcTy = Op0C->getOperand(0)->getType();
4536 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4537 // Only do this if the casts both really cause code to be
4538 // generated.
4539 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4540 I.getType(), TD) &&
4541 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4542 I.getType(), TD)) {
4543 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4544 Op1C->getOperand(0),
4545 I.getName());
4546 InsertNewInstBefore(NewOp, I);
4547 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4548 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549 }
4550 }
Chris Lattner91882432007-10-24 05:38:08 +00004551 }
4552
4553
4554 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4555 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4556 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4557 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004558 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4559 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004560 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4561 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4562 // If either of the constants are nans, then the whole thing returns
4563 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004564 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004565 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4566
4567 // Otherwise, no need to compare the two constants, compare the
4568 // rest.
4569 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4570 RHS->getOperand(0));
4571 }
4572 }
4573 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004574
4575 return Changed ? &I : 0;
4576}
4577
4578// XorSelf - Implements: X ^ X --> 0
4579struct XorSelf {
4580 Value *RHS;
4581 XorSelf(Value *rhs) : RHS(rhs) {}
4582 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4583 Instruction *apply(BinaryOperator &Xor) const {
4584 return &Xor;
4585 }
4586};
4587
4588
4589Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4590 bool Changed = SimplifyCommutative(I);
4591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4592
Evan Chenge5cd8032008-03-25 20:07:13 +00004593 if (isa<UndefValue>(Op1)) {
4594 if (isa<UndefValue>(Op0))
4595 // Handle undef ^ undef -> 0 special case. This is a common
4596 // idiom (misuse).
4597 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004598 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004599 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004600
4601 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4602 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004603 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4605 }
4606
4607 // See if we can simplify any instructions used by the instruction whose sole
4608 // purpose is to compute bits we don't care about.
4609 if (!isa<VectorType>(I.getType())) {
4610 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4611 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4612 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4613 KnownZero, KnownOne))
4614 return &I;
4615 } else if (isa<ConstantAggregateZero>(Op1)) {
4616 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4617 }
4618
4619 // Is this a ~ operation?
4620 if (Value *NotOp = dyn_castNotVal(&I)) {
4621 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4622 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4623 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4624 if (Op0I->getOpcode() == Instruction::And ||
4625 Op0I->getOpcode() == Instruction::Or) {
4626 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4627 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4628 Instruction *NotY =
4629 BinaryOperator::createNot(Op0I->getOperand(1),
4630 Op0I->getOperand(1)->getName()+".not");
4631 InsertNewInstBefore(NotY, I);
4632 if (Op0I->getOpcode() == Instruction::And)
4633 return BinaryOperator::createOr(Op0NotVal, NotY);
4634 else
4635 return BinaryOperator::createAnd(Op0NotVal, NotY);
4636 }
4637 }
4638 }
4639 }
4640
4641
4642 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004643 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4644 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4645 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004646 return new ICmpInst(ICI->getInversePredicate(),
4647 ICI->getOperand(0), ICI->getOperand(1));
4648
Nick Lewycky1405e922007-08-06 20:04:16 +00004649 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4650 return new FCmpInst(FCI->getInversePredicate(),
4651 FCI->getOperand(0), FCI->getOperand(1));
4652 }
4653
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004654 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4655 // ~(c-X) == X-c-1 == X+(-c-1)
4656 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4657 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4658 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4659 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4660 ConstantInt::get(I.getType(), 1));
4661 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4662 }
4663
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004664 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004665 if (Op0I->getOpcode() == Instruction::Add) {
4666 // ~(X-c) --> (-c-1)-X
4667 if (RHS->isAllOnesValue()) {
4668 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4669 return BinaryOperator::createSub(
4670 ConstantExpr::getSub(NegOp0CI,
4671 ConstantInt::get(I.getType(), 1)),
4672 Op0I->getOperand(0));
4673 } else if (RHS->getValue().isSignBit()) {
4674 // (X + C) ^ signbit -> (X + C + signbit)
4675 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4676 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4677
4678 }
4679 } else if (Op0I->getOpcode() == Instruction::Or) {
4680 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4681 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4682 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4683 // Anything in both C1 and C2 is known to be zero, remove it from
4684 // NewRHS.
4685 Constant *CommonBits = And(Op0CI, RHS);
4686 NewRHS = ConstantExpr::getAnd(NewRHS,
4687 ConstantExpr::getNot(CommonBits));
4688 AddToWorkList(Op0I);
4689 I.setOperand(0, Op0I->getOperand(0));
4690 I.setOperand(1, NewRHS);
4691 return &I;
4692 }
4693 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004694 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004695 }
4696
4697 // Try to fold constant and into select arguments.
4698 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4699 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4700 return R;
4701 if (isa<PHINode>(Op0))
4702 if (Instruction *NV = FoldOpIntoPhi(I))
4703 return NV;
4704 }
4705
4706 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4707 if (X == Op1)
4708 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4709
4710 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4711 if (X == Op0)
4712 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4713
4714
4715 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4716 if (Op1I) {
4717 Value *A, *B;
4718 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4719 if (A == Op0) { // B^(B|A) == (A|B)^B
4720 Op1I->swapOperands();
4721 I.swapOperands();
4722 std::swap(Op0, Op1);
4723 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4724 I.swapOperands(); // Simplified below.
4725 std::swap(Op0, Op1);
4726 }
4727 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4728 if (Op0 == A) // A^(A^B) == B
4729 return ReplaceInstUsesWith(I, B);
4730 else if (Op0 == B) // A^(B^A) == B
4731 return ReplaceInstUsesWith(I, A);
4732 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4733 if (A == Op0) { // A^(A&B) -> A^(B&A)
4734 Op1I->swapOperands();
4735 std::swap(A, B);
4736 }
4737 if (B == Op0) { // A^(B&A) -> (B&A)^A
4738 I.swapOperands(); // Simplified below.
4739 std::swap(Op0, Op1);
4740 }
4741 }
4742 }
4743
4744 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4745 if (Op0I) {
4746 Value *A, *B;
4747 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4748 if (A == Op1) // (B|A)^B == (A|B)^B
4749 std::swap(A, B);
4750 if (B == Op1) { // (A|B)^B == A & ~B
4751 Instruction *NotB =
4752 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4753 return BinaryOperator::createAnd(A, NotB);
4754 }
4755 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4756 if (Op1 == A) // (A^B)^A == B
4757 return ReplaceInstUsesWith(I, B);
4758 else if (Op1 == B) // (B^A)^A == B
4759 return ReplaceInstUsesWith(I, A);
4760 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4761 if (A == Op1) // (A&B)^A -> (B&A)^A
4762 std::swap(A, B);
4763 if (B == Op1 && // (B&A)^A == ~B & A
4764 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4765 Instruction *N =
4766 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4767 return BinaryOperator::createAnd(N, Op1);
4768 }
4769 }
4770 }
4771
4772 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4773 if (Op0I && Op1I && Op0I->isShift() &&
4774 Op0I->getOpcode() == Op1I->getOpcode() &&
4775 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4776 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4777 Instruction *NewOp =
4778 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4779 Op1I->getOperand(0),
4780 Op0I->getName()), I);
4781 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4782 Op1I->getOperand(1));
4783 }
4784
4785 if (Op0I && Op1I) {
4786 Value *A, *B, *C, *D;
4787 // (A & B)^(A | B) -> A ^ B
4788 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4789 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4790 if ((A == C && B == D) || (A == D && B == C))
4791 return BinaryOperator::createXor(A, B);
4792 }
4793 // (A | B)^(A & B) -> A ^ B
4794 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4795 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4796 if ((A == C && B == D) || (A == D && B == C))
4797 return BinaryOperator::createXor(A, B);
4798 }
4799
4800 // (A & B)^(C & D)
4801 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4802 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4803 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4804 // (X & Y)^(X & Y) -> (Y^Z) & X
4805 Value *X = 0, *Y = 0, *Z = 0;
4806 if (A == C)
4807 X = A, Y = B, Z = D;
4808 else if (A == D)
4809 X = A, Y = B, Z = C;
4810 else if (B == C)
4811 X = B, Y = A, Z = D;
4812 else if (B == D)
4813 X = B, Y = A, Z = C;
4814
4815 if (X) {
4816 Instruction *NewOp =
4817 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4818 return BinaryOperator::createAnd(NewOp, X);
4819 }
4820 }
4821 }
4822
4823 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4824 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4825 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4826 return R;
4827
4828 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004829 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004830 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4831 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4832 const Type *SrcTy = Op0C->getOperand(0)->getType();
4833 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4834 // Only do this if the casts both really cause code to be generated.
4835 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4836 I.getType(), TD) &&
4837 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4838 I.getType(), TD)) {
4839 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4840 Op1C->getOperand(0),
4841 I.getName());
4842 InsertNewInstBefore(NewOp, I);
4843 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4844 }
4845 }
Chris Lattner91882432007-10-24 05:38:08 +00004846 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004847 return Changed ? &I : 0;
4848}
4849
4850/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4851/// overflowed for this type.
4852static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4853 ConstantInt *In2, bool IsSigned = false) {
4854 Result = cast<ConstantInt>(Add(In1, In2));
4855
4856 if (IsSigned)
4857 if (In2->getValue().isNegative())
4858 return Result->getValue().sgt(In1->getValue());
4859 else
4860 return Result->getValue().slt(In1->getValue());
4861 else
4862 return Result->getValue().ult(In1->getValue());
4863}
4864
4865/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4866/// code necessary to compute the offset from the base pointer (without adding
4867/// in the base pointer). Return the result as a signed integer of intptr size.
4868static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4869 TargetData &TD = IC.getTargetData();
4870 gep_type_iterator GTI = gep_type_begin(GEP);
4871 const Type *IntPtrTy = TD.getIntPtrType();
4872 Value *Result = Constant::getNullValue(IntPtrTy);
4873
4874 // Build a mask for high order bits.
4875 unsigned IntPtrWidth = TD.getPointerSize()*8;
4876 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4877
4878 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4879 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004880 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004881 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4882 if (OpC->isZero()) continue;
4883
4884 // Handle a struct index, which adds its field offset to the pointer.
4885 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4886 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4887
4888 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4889 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4890 else
4891 Result = IC.InsertNewInstBefore(
4892 BinaryOperator::createAdd(Result,
4893 ConstantInt::get(IntPtrTy, Size),
4894 GEP->getName()+".offs"), I);
4895 continue;
4896 }
4897
4898 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4899 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4900 Scale = ConstantExpr::getMul(OC, Scale);
4901 if (Constant *RC = dyn_cast<Constant>(Result))
4902 Result = ConstantExpr::getAdd(RC, Scale);
4903 else {
4904 // Emit an add instruction.
4905 Result = IC.InsertNewInstBefore(
4906 BinaryOperator::createAdd(Result, Scale,
4907 GEP->getName()+".offs"), I);
4908 }
4909 continue;
4910 }
4911 // Convert to correct type.
4912 if (Op->getType() != IntPtrTy) {
4913 if (Constant *OpC = dyn_cast<Constant>(Op))
4914 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4915 else
4916 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4917 Op->getName()+".c"), I);
4918 }
4919 if (Size != 1) {
4920 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4921 if (Constant *OpC = dyn_cast<Constant>(Op))
4922 Op = ConstantExpr::getMul(OpC, Scale);
4923 else // We'll let instcombine(mul) convert this to a shl if possible.
4924 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4925 GEP->getName()+".idx"), I);
4926 }
4927
4928 // Emit an add instruction.
4929 if (isa<Constant>(Op) && isa<Constant>(Result))
4930 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4931 cast<Constant>(Result));
4932 else
4933 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4934 GEP->getName()+".offs"), I);
4935 }
4936 return Result;
4937}
4938
4939/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4940/// else. At this point we know that the GEP is on the LHS of the comparison.
4941Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4942 ICmpInst::Predicate Cond,
4943 Instruction &I) {
4944 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4945
4946 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4947 if (isa<PointerType>(CI->getOperand(0)->getType()))
4948 RHS = CI->getOperand(0);
4949
4950 Value *PtrBase = GEPLHS->getOperand(0);
4951 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004952 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4953 // This transformation is valid because we know pointers can't overflow.
4954 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4955 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4956 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004957 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4958 // If the base pointers are different, but the indices are the same, just
4959 // compare the base pointer.
4960 if (PtrBase != GEPRHS->getOperand(0)) {
4961 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4962 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4963 GEPRHS->getOperand(0)->getType();
4964 if (IndicesTheSame)
4965 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4966 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4967 IndicesTheSame = false;
4968 break;
4969 }
4970
4971 // If all indices are the same, just compare the base pointers.
4972 if (IndicesTheSame)
4973 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4974 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4975
4976 // Otherwise, the base pointers are different and the indices are
4977 // different, bail out.
4978 return 0;
4979 }
4980
4981 // If one of the GEPs has all zero indices, recurse.
4982 bool AllZeros = true;
4983 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4984 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4985 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4986 AllZeros = false;
4987 break;
4988 }
4989 if (AllZeros)
4990 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4991 ICmpInst::getSwappedPredicate(Cond), I);
4992
4993 // If the other GEP has all zero indices, recurse.
4994 AllZeros = true;
4995 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4996 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4997 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4998 AllZeros = false;
4999 break;
5000 }
5001 if (AllZeros)
5002 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5003
5004 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5005 // If the GEPs only differ by one index, compare it.
5006 unsigned NumDifferences = 0; // Keep track of # differences.
5007 unsigned DiffOperand = 0; // The operand that differs.
5008 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5009 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5010 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5011 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5012 // Irreconcilable differences.
5013 NumDifferences = 2;
5014 break;
5015 } else {
5016 if (NumDifferences++) break;
5017 DiffOperand = i;
5018 }
5019 }
5020
5021 if (NumDifferences == 0) // SAME GEP?
5022 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005023 ConstantInt::get(Type::Int1Ty,
5024 isTrueWhenEqual(Cond)));
5025
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 else if (NumDifferences == 1) {
5027 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5028 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5029 // Make sure we do a signed comparison here.
5030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5031 }
5032 }
5033
5034 // Only lower this if the icmp is the only user of the GEP or if we expect
5035 // the result to fold to a constant!
5036 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5039 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5040 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5042 }
5043 }
5044 return 0;
5045}
5046
5047Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5048 bool Changed = SimplifyCompare(I);
5049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5050
5051 // Fold trivial predicates.
5052 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5053 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5054 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5055 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5056
5057 // Simplify 'fcmp pred X, X'
5058 if (Op0 == Op1) {
5059 switch (I.getPredicate()) {
5060 default: assert(0 && "Unknown predicate!");
5061 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5062 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5063 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5064 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5065 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5066 case FCmpInst::FCMP_OLT: // True if ordered and less than
5067 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5068 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5069
5070 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5071 case FCmpInst::FCMP_ULT: // True if unordered or less than
5072 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5073 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5074 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5075 I.setPredicate(FCmpInst::FCMP_UNO);
5076 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5077 return &I;
5078
5079 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5080 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5081 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5082 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5083 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5084 I.setPredicate(FCmpInst::FCMP_ORD);
5085 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5086 return &I;
5087 }
5088 }
5089
5090 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5091 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5092
5093 // Handle fcmp with constant RHS
5094 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5095 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5096 switch (LHSI->getOpcode()) {
5097 case Instruction::PHI:
5098 if (Instruction *NV = FoldOpIntoPhi(I))
5099 return NV;
5100 break;
5101 case Instruction::Select:
5102 // If either operand of the select is a constant, we can fold the
5103 // comparison into the select arms, which will cause one to be
5104 // constant folded and the select turned into a bitwise or.
5105 Value *Op1 = 0, *Op2 = 0;
5106 if (LHSI->hasOneUse()) {
5107 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5108 // Fold the known value into the constant operand.
5109 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5110 // Insert a new FCmp of the other select operand.
5111 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5112 LHSI->getOperand(2), RHSC,
5113 I.getName()), I);
5114 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5115 // Fold the known value into the constant operand.
5116 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5117 // Insert a new FCmp of the other select operand.
5118 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5119 LHSI->getOperand(1), RHSC,
5120 I.getName()), I);
5121 }
5122 }
5123
5124 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005125 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005126 break;
5127 }
5128 }
5129
5130 return Changed ? &I : 0;
5131}
5132
5133Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5134 bool Changed = SimplifyCompare(I);
5135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5136 const Type *Ty = Op0->getType();
5137
5138 // icmp X, X
5139 if (Op0 == Op1)
5140 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5141 isTrueWhenEqual(I)));
5142
5143 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5144 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005145
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005146 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5147 // addresses never equal each other! We already know that Op0 != Op1.
5148 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5149 isa<ConstantPointerNull>(Op0)) &&
5150 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5151 isa<ConstantPointerNull>(Op1)))
5152 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5153 !isTrueWhenEqual(I)));
5154
5155 // icmp's with boolean values can always be turned into bitwise operations
5156 if (Ty == Type::Int1Ty) {
5157 switch (I.getPredicate()) {
5158 default: assert(0 && "Invalid icmp instruction!");
5159 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
5160 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
5161 InsertNewInstBefore(Xor, I);
5162 return BinaryOperator::createNot(Xor);
5163 }
5164 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5165 return BinaryOperator::createXor(Op0, Op1);
5166
5167 case ICmpInst::ICMP_UGT:
5168 case ICmpInst::ICMP_SGT:
5169 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5170 // FALL THROUGH
5171 case ICmpInst::ICMP_ULT:
5172 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5173 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5174 InsertNewInstBefore(Not, I);
5175 return BinaryOperator::createAnd(Not, Op1);
5176 }
5177 case ICmpInst::ICMP_UGE:
5178 case ICmpInst::ICMP_SGE:
5179 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5180 // FALL THROUGH
5181 case ICmpInst::ICMP_ULE:
5182 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5183 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5184 InsertNewInstBefore(Not, I);
5185 return BinaryOperator::createOr(Not, Op1);
5186 }
5187 }
5188 }
5189
5190 // See if we are doing a comparison between a constant and an instruction that
5191 // can be folded into the comparison.
5192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005193 Value *A, *B;
5194
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005195 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5196 if (I.isEquality() && CI->isNullValue() &&
5197 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5198 // (icmp cond A B) if cond is equality
5199 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005200 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005201
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005202 switch (I.getPredicate()) {
5203 default: break;
5204 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5205 if (CI->isMinValue(false))
5206 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5207 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5208 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5209 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5210 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5211 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5212 if (CI->isMinValue(true))
5213 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5214 ConstantInt::getAllOnesValue(Op0->getType()));
5215
5216 break;
5217
5218 case ICmpInst::ICMP_SLT:
5219 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5220 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5221 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5222 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5223 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5225 break;
5226
5227 case ICmpInst::ICMP_UGT:
5228 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5229 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5230 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5232 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5233 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5234
5235 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5236 if (CI->isMaxValue(true))
5237 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5238 ConstantInt::getNullValue(Op0->getType()));
5239 break;
5240
5241 case ICmpInst::ICMP_SGT:
5242 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5243 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5244 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5245 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5246 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5248 break;
5249
5250 case ICmpInst::ICMP_ULE:
5251 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5253 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5254 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5255 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5256 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5257 break;
5258
5259 case ICmpInst::ICMP_SLE:
5260 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5261 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5262 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5264 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5265 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5266 break;
5267
5268 case ICmpInst::ICMP_UGE:
5269 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5270 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5271 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5272 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5273 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5274 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5275 break;
5276
5277 case ICmpInst::ICMP_SGE:
5278 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5279 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5280 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5281 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5282 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5283 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5284 break;
5285 }
5286
5287 // If we still have a icmp le or icmp ge instruction, turn it into the
5288 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5289 // already been handled above, this requires little checking.
5290 //
5291 switch (I.getPredicate()) {
5292 default: break;
5293 case ICmpInst::ICMP_ULE:
5294 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5295 case ICmpInst::ICMP_SLE:
5296 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5297 case ICmpInst::ICMP_UGE:
5298 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5299 case ICmpInst::ICMP_SGE:
5300 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5301 }
5302
5303 // See if we can fold the comparison based on bits known to be zero or one
5304 // in the input. If this comparison is a normal comparison, it demands all
5305 // bits, if it is a sign bit comparison, it only demands the sign bit.
5306
5307 bool UnusedBit;
5308 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5309
5310 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5312 if (SimplifyDemandedBits(Op0,
5313 isSignBit ? APInt::getSignBit(BitWidth)
5314 : APInt::getAllOnesValue(BitWidth),
5315 KnownZero, KnownOne, 0))
5316 return &I;
5317
5318 // Given the known and unknown bits, compute a range that the LHS could be
5319 // in.
5320 if ((KnownOne | KnownZero) != 0) {
5321 // Compute the Min, Max and RHS values based on the known bits. For the
5322 // EQ and NE we use unsigned values.
5323 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5324 const APInt& RHSVal = CI->getValue();
5325 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5326 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5327 Max);
5328 } else {
5329 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5330 Max);
5331 }
5332 switch (I.getPredicate()) { // LE/GE have been folded already.
5333 default: assert(0 && "Unknown icmp opcode!");
5334 case ICmpInst::ICMP_EQ:
5335 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5336 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5337 break;
5338 case ICmpInst::ICMP_NE:
5339 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5341 break;
5342 case ICmpInst::ICMP_ULT:
5343 if (Max.ult(RHSVal))
5344 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5345 if (Min.uge(RHSVal))
5346 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5347 break;
5348 case ICmpInst::ICMP_UGT:
5349 if (Min.ugt(RHSVal))
5350 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5351 if (Max.ule(RHSVal))
5352 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5353 break;
5354 case ICmpInst::ICMP_SLT:
5355 if (Max.slt(RHSVal))
5356 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5357 if (Min.sgt(RHSVal))
5358 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5359 break;
5360 case ICmpInst::ICMP_SGT:
5361 if (Min.sgt(RHSVal))
5362 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5363 if (Max.sle(RHSVal))
5364 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5365 break;
5366 }
5367 }
5368
5369 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5370 // instruction, see if that instruction also has constants so that the
5371 // instruction can be folded into the icmp
5372 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5373 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5374 return Res;
5375 }
5376
5377 // Handle icmp with constant (but not simple integer constant) RHS
5378 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5379 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5380 switch (LHSI->getOpcode()) {
5381 case Instruction::GetElementPtr:
5382 if (RHSC->isNullValue()) {
5383 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5384 bool isAllZeros = true;
5385 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5386 if (!isa<Constant>(LHSI->getOperand(i)) ||
5387 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5388 isAllZeros = false;
5389 break;
5390 }
5391 if (isAllZeros)
5392 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5393 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5394 }
5395 break;
5396
5397 case Instruction::PHI:
5398 if (Instruction *NV = FoldOpIntoPhi(I))
5399 return NV;
5400 break;
5401 case Instruction::Select: {
5402 // If either operand of the select is a constant, we can fold the
5403 // comparison into the select arms, which will cause one to be
5404 // constant folded and the select turned into a bitwise or.
5405 Value *Op1 = 0, *Op2 = 0;
5406 if (LHSI->hasOneUse()) {
5407 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5408 // Fold the known value into the constant operand.
5409 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5410 // Insert a new ICmp of the other select operand.
5411 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5412 LHSI->getOperand(2), RHSC,
5413 I.getName()), I);
5414 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5415 // Fold the known value into the constant operand.
5416 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5417 // Insert a new ICmp of the other select operand.
5418 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5419 LHSI->getOperand(1), RHSC,
5420 I.getName()), I);
5421 }
5422 }
5423
5424 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005425 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005426 break;
5427 }
5428 case Instruction::Malloc:
5429 // If we have (malloc != null), and if the malloc has a single use, we
5430 // can assume it is successful and remove the malloc.
5431 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5432 AddToWorkList(LHSI);
5433 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5434 !isTrueWhenEqual(I)));
5435 }
5436 break;
5437 }
5438 }
5439
5440 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5441 if (User *GEP = dyn_castGetElementPtr(Op0))
5442 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5443 return NI;
5444 if (User *GEP = dyn_castGetElementPtr(Op1))
5445 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5446 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5447 return NI;
5448
5449 // Test to see if the operands of the icmp are casted versions of other
5450 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5451 // now.
5452 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5453 if (isa<PointerType>(Op0->getType()) &&
5454 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5455 // We keep moving the cast from the left operand over to the right
5456 // operand, where it can often be eliminated completely.
5457 Op0 = CI->getOperand(0);
5458
5459 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5460 // so eliminate it as well.
5461 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5462 Op1 = CI2->getOperand(0);
5463
5464 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005465 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005466 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5467 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5468 } else {
5469 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005470 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005471 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005472 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005473 return new ICmpInst(I.getPredicate(), Op0, Op1);
5474 }
5475 }
5476
5477 if (isa<CastInst>(Op0)) {
5478 // Handle the special case of: icmp (cast bool to X), <cst>
5479 // This comes up when you have code like
5480 // int X = A < B;
5481 // if (X) ...
5482 // For generality, we handle any zero-extension of any operand comparison
5483 // with a constant or another cast from the same type.
5484 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5485 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5486 return R;
5487 }
5488
5489 if (I.isEquality()) {
5490 Value *A, *B, *C, *D;
5491 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5492 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5493 Value *OtherVal = A == Op1 ? B : A;
5494 return new ICmpInst(I.getPredicate(), OtherVal,
5495 Constant::getNullValue(A->getType()));
5496 }
5497
5498 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5499 // A^c1 == C^c2 --> A == C^(c1^c2)
5500 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5501 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5502 if (Op1->hasOneUse()) {
5503 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5504 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5505 return new ICmpInst(I.getPredicate(), A,
5506 InsertNewInstBefore(Xor, I));
5507 }
5508
5509 // A^B == A^D -> B == D
5510 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5511 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5512 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5513 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5514 }
5515 }
5516
5517 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5518 (A == Op0 || B == Op0)) {
5519 // A == (A^B) -> B == 0
5520 Value *OtherVal = A == Op0 ? B : A;
5521 return new ICmpInst(I.getPredicate(), OtherVal,
5522 Constant::getNullValue(A->getType()));
5523 }
5524 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5525 // (A-B) == A -> B == 0
5526 return new ICmpInst(I.getPredicate(), B,
5527 Constant::getNullValue(B->getType()));
5528 }
5529 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5530 // A == (A-B) -> B == 0
5531 return new ICmpInst(I.getPredicate(), B,
5532 Constant::getNullValue(B->getType()));
5533 }
5534
5535 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5536 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5537 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5538 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5539 Value *X = 0, *Y = 0, *Z = 0;
5540
5541 if (A == C) {
5542 X = B; Y = D; Z = A;
5543 } else if (A == D) {
5544 X = B; Y = C; Z = A;
5545 } else if (B == C) {
5546 X = A; Y = D; Z = B;
5547 } else if (B == D) {
5548 X = A; Y = C; Z = B;
5549 }
5550
5551 if (X) { // Build (X^Y) & Z
5552 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5553 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5554 I.setOperand(0, Op1);
5555 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5556 return &I;
5557 }
5558 }
5559 }
5560 return Changed ? &I : 0;
5561}
5562
5563
5564/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5565/// and CmpRHS are both known to be integer constants.
5566Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5567 ConstantInt *DivRHS) {
5568 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5569 const APInt &CmpRHSV = CmpRHS->getValue();
5570
5571 // FIXME: If the operand types don't match the type of the divide
5572 // then don't attempt this transform. The code below doesn't have the
5573 // logic to deal with a signed divide and an unsigned compare (and
5574 // vice versa). This is because (x /s C1) <s C2 produces different
5575 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5576 // (x /u C1) <u C2. Simply casting the operands and result won't
5577 // work. :( The if statement below tests that condition and bails
5578 // if it finds it.
5579 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5580 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5581 return 0;
5582 if (DivRHS->isZero())
5583 return 0; // The ProdOV computation fails on divide by zero.
5584
5585 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5586 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5587 // C2 (CI). By solving for X we can turn this into a range check
5588 // instead of computing a divide.
5589 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5590
5591 // Determine if the product overflows by seeing if the product is
5592 // not equal to the divide. Make sure we do the same kind of divide
5593 // as in the LHS instruction that we're folding.
5594 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5595 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5596
5597 // Get the ICmp opcode
5598 ICmpInst::Predicate Pred = ICI.getPredicate();
5599
5600 // Figure out the interval that is being checked. For example, a comparison
5601 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5602 // Compute this interval based on the constants involved and the signedness of
5603 // the compare/divide. This computes a half-open interval, keeping track of
5604 // whether either value in the interval overflows. After analysis each
5605 // overflow variable is set to 0 if it's corresponding bound variable is valid
5606 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5607 int LoOverflow = 0, HiOverflow = 0;
5608 ConstantInt *LoBound = 0, *HiBound = 0;
5609
5610
5611 if (!DivIsSigned) { // udiv
5612 // e.g. X/5 op 3 --> [15, 20)
5613 LoBound = Prod;
5614 HiOverflow = LoOverflow = ProdOV;
5615 if (!HiOverflow)
5616 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005617 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005618 if (CmpRHSV == 0) { // (X / pos) op 0
5619 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5620 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5621 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005622 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005623 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5624 HiOverflow = LoOverflow = ProdOV;
5625 if (!HiOverflow)
5626 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5627 } else { // (X / pos) op neg
5628 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5629 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5630 LoOverflow = AddWithOverflow(LoBound, Prod,
5631 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5632 HiBound = AddOne(Prod);
5633 HiOverflow = ProdOV ? -1 : 0;
5634 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005635 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005636 if (CmpRHSV == 0) { // (X / neg) op 0
5637 // e.g. X/-5 op 0 --> [-4, 5)
5638 LoBound = AddOne(DivRHS);
5639 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5640 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5641 HiOverflow = 1; // [INTMIN+1, overflow)
5642 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5643 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005644 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005645 // e.g. X/-5 op 3 --> [-19, -14)
5646 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5647 if (!LoOverflow)
5648 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5649 HiBound = AddOne(Prod);
5650 } else { // (X / neg) op neg
5651 // e.g. X/-5 op -3 --> [15, 20)
5652 LoBound = Prod;
5653 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5654 HiBound = Subtract(Prod, DivRHS);
5655 }
5656
5657 // Dividing by a negative swaps the condition. LT <-> GT
5658 Pred = ICmpInst::getSwappedPredicate(Pred);
5659 }
5660
5661 Value *X = DivI->getOperand(0);
5662 switch (Pred) {
5663 default: assert(0 && "Unhandled icmp opcode!");
5664 case ICmpInst::ICMP_EQ:
5665 if (LoOverflow && HiOverflow)
5666 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5667 else if (HiOverflow)
5668 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5669 ICmpInst::ICMP_UGE, X, LoBound);
5670 else if (LoOverflow)
5671 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5672 ICmpInst::ICMP_ULT, X, HiBound);
5673 else
5674 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5675 case ICmpInst::ICMP_NE:
5676 if (LoOverflow && HiOverflow)
5677 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5678 else if (HiOverflow)
5679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5680 ICmpInst::ICMP_ULT, X, LoBound);
5681 else if (LoOverflow)
5682 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5683 ICmpInst::ICMP_UGE, X, HiBound);
5684 else
5685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5686 case ICmpInst::ICMP_ULT:
5687 case ICmpInst::ICMP_SLT:
5688 if (LoOverflow == +1) // Low bound is greater than input range.
5689 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5690 if (LoOverflow == -1) // Low bound is less than input range.
5691 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5692 return new ICmpInst(Pred, X, LoBound);
5693 case ICmpInst::ICMP_UGT:
5694 case ICmpInst::ICMP_SGT:
5695 if (HiOverflow == +1) // High bound greater than input range.
5696 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5697 else if (HiOverflow == -1) // High bound less than input range.
5698 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5699 if (Pred == ICmpInst::ICMP_UGT)
5700 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5701 else
5702 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5703 }
5704}
5705
5706
5707/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5708///
5709Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5710 Instruction *LHSI,
5711 ConstantInt *RHS) {
5712 const APInt &RHSV = RHS->getValue();
5713
5714 switch (LHSI->getOpcode()) {
5715 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5716 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5717 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5718 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005719 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5720 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005721 Value *CompareVal = LHSI->getOperand(0);
5722
5723 // If the sign bit of the XorCST is not set, there is no change to
5724 // the operation, just stop using the Xor.
5725 if (!XorCST->getValue().isNegative()) {
5726 ICI.setOperand(0, CompareVal);
5727 AddToWorkList(LHSI);
5728 return &ICI;
5729 }
5730
5731 // Was the old condition true if the operand is positive?
5732 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5733
5734 // If so, the new one isn't.
5735 isTrueIfPositive ^= true;
5736
5737 if (isTrueIfPositive)
5738 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5739 else
5740 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5741 }
5742 }
5743 break;
5744 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5745 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5746 LHSI->getOperand(0)->hasOneUse()) {
5747 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5748
5749 // If the LHS is an AND of a truncating cast, we can widen the
5750 // and/compare to be the input width without changing the value
5751 // produced, eliminating a cast.
5752 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5753 // We can do this transformation if either the AND constant does not
5754 // have its sign bit set or if it is an equality comparison.
5755 // Extending a relational comparison when we're checking the sign
5756 // bit would not work.
5757 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005758 (ICI.isEquality() ||
5759 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005760 uint32_t BitWidth =
5761 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5762 APInt NewCST = AndCST->getValue();
5763 NewCST.zext(BitWidth);
5764 APInt NewCI = RHSV;
5765 NewCI.zext(BitWidth);
5766 Instruction *NewAnd =
5767 BinaryOperator::createAnd(Cast->getOperand(0),
5768 ConstantInt::get(NewCST),LHSI->getName());
5769 InsertNewInstBefore(NewAnd, ICI);
5770 return new ICmpInst(ICI.getPredicate(), NewAnd,
5771 ConstantInt::get(NewCI));
5772 }
5773 }
5774
5775 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5776 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5777 // happens a LOT in code produced by the C front-end, for bitfield
5778 // access.
5779 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5780 if (Shift && !Shift->isShift())
5781 Shift = 0;
5782
5783 ConstantInt *ShAmt;
5784 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5785 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5786 const Type *AndTy = AndCST->getType(); // Type of the and.
5787
5788 // We can fold this as long as we can't shift unknown bits
5789 // into the mask. This can only happen with signed shift
5790 // rights, as they sign-extend.
5791 if (ShAmt) {
5792 bool CanFold = Shift->isLogicalShift();
5793 if (!CanFold) {
5794 // To test for the bad case of the signed shr, see if any
5795 // of the bits shifted in could be tested after the mask.
5796 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5797 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5798
5799 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5800 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5801 AndCST->getValue()) == 0)
5802 CanFold = true;
5803 }
5804
5805 if (CanFold) {
5806 Constant *NewCst;
5807 if (Shift->getOpcode() == Instruction::Shl)
5808 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5809 else
5810 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5811
5812 // Check to see if we are shifting out any of the bits being
5813 // compared.
5814 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5815 // If we shifted bits out, the fold is not going to work out.
5816 // As a special case, check to see if this means that the
5817 // result is always true or false now.
5818 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5819 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5820 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5821 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5822 } else {
5823 ICI.setOperand(1, NewCst);
5824 Constant *NewAndCST;
5825 if (Shift->getOpcode() == Instruction::Shl)
5826 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5827 else
5828 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5829 LHSI->setOperand(1, NewAndCST);
5830 LHSI->setOperand(0, Shift->getOperand(0));
5831 AddToWorkList(Shift); // Shift is dead.
5832 AddUsesToWorkList(ICI);
5833 return &ICI;
5834 }
5835 }
5836 }
5837
5838 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5839 // preferable because it allows the C<<Y expression to be hoisted out
5840 // of a loop if Y is invariant and X is not.
5841 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5842 ICI.isEquality() && !Shift->isArithmeticShift() &&
5843 isa<Instruction>(Shift->getOperand(0))) {
5844 // Compute C << Y.
5845 Value *NS;
5846 if (Shift->getOpcode() == Instruction::LShr) {
5847 NS = BinaryOperator::createShl(AndCST,
5848 Shift->getOperand(1), "tmp");
5849 } else {
5850 // Insert a logical shift.
5851 NS = BinaryOperator::createLShr(AndCST,
5852 Shift->getOperand(1), "tmp");
5853 }
5854 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5855
5856 // Compute X & (C << Y).
5857 Instruction *NewAnd =
5858 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5859 InsertNewInstBefore(NewAnd, ICI);
5860
5861 ICI.setOperand(0, NewAnd);
5862 return &ICI;
5863 }
5864 }
5865 break;
5866
5867 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5868 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5869 if (!ShAmt) break;
5870
5871 uint32_t TypeBits = RHSV.getBitWidth();
5872
5873 // Check that the shift amount is in range. If not, don't perform
5874 // undefined shifts. When the shift is visited it will be
5875 // simplified.
5876 if (ShAmt->uge(TypeBits))
5877 break;
5878
5879 if (ICI.isEquality()) {
5880 // If we are comparing against bits always shifted out, the
5881 // comparison cannot succeed.
5882 Constant *Comp =
5883 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5884 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5885 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5886 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5887 return ReplaceInstUsesWith(ICI, Cst);
5888 }
5889
5890 if (LHSI->hasOneUse()) {
5891 // Otherwise strength reduce the shift into an and.
5892 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5893 Constant *Mask =
5894 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5895
5896 Instruction *AndI =
5897 BinaryOperator::createAnd(LHSI->getOperand(0),
5898 Mask, LHSI->getName()+".mask");
5899 Value *And = InsertNewInstBefore(AndI, ICI);
5900 return new ICmpInst(ICI.getPredicate(), And,
5901 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5902 }
5903 }
5904
5905 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5906 bool TrueIfSigned = false;
5907 if (LHSI->hasOneUse() &&
5908 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5909 // (X << 31) <s 0 --> (X&1) != 0
5910 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5911 (TypeBits-ShAmt->getZExtValue()-1));
5912 Instruction *AndI =
5913 BinaryOperator::createAnd(LHSI->getOperand(0),
5914 Mask, LHSI->getName()+".mask");
5915 Value *And = InsertNewInstBefore(AndI, ICI);
5916
5917 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5918 And, Constant::getNullValue(And->getType()));
5919 }
5920 break;
5921 }
5922
5923 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5924 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005925 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005926 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00005927 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005928
Chris Lattner5ee84f82008-03-21 05:19:58 +00005929 // Check that the shift amount is in range. If not, don't perform
5930 // undefined shifts. When the shift is visited it will be
5931 // simplified.
5932 uint32_t TypeBits = RHSV.getBitWidth();
5933 if (ShAmt->uge(TypeBits))
5934 break;
5935
5936 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005937
Chris Lattner5ee84f82008-03-21 05:19:58 +00005938 // If we are comparing against bits always shifted out, the
5939 // comparison cannot succeed.
5940 APInt Comp = RHSV << ShAmtVal;
5941 if (LHSI->getOpcode() == Instruction::LShr)
5942 Comp = Comp.lshr(ShAmtVal);
5943 else
5944 Comp = Comp.ashr(ShAmtVal);
5945
5946 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5947 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5948 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5949 return ReplaceInstUsesWith(ICI, Cst);
5950 }
5951
5952 // Otherwise, check to see if the bits shifted out are known to be zero.
5953 // If so, we can compare against the unshifted value:
5954 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5955 if (MaskedValueIsZero(LHSI->getOperand(0),
5956 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5957 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5958 ConstantExpr::getShl(RHS, ShAmt));
5959 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005960
Chris Lattner5ee84f82008-03-21 05:19:58 +00005961 if (LHSI->hasOneUse() || RHSV == 0) {
5962 // Otherwise strength reduce the shift into an and.
5963 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5964 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965
Chris Lattner5ee84f82008-03-21 05:19:58 +00005966 Instruction *AndI =
5967 BinaryOperator::createAnd(LHSI->getOperand(0),
5968 Mask, LHSI->getName()+".mask");
5969 Value *And = InsertNewInstBefore(AndI, ICI);
5970 return new ICmpInst(ICI.getPredicate(), And,
5971 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005972 }
5973 break;
5974 }
5975
5976 case Instruction::SDiv:
5977 case Instruction::UDiv:
5978 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5979 // Fold this div into the comparison, producing a range check.
5980 // Determine, based on the divide type, what the range is being
5981 // checked. If there is an overflow on the low or high side, remember
5982 // it, otherwise compute the range [low, hi) bounding the new value.
5983 // See: InsertRangeTest above for the kinds of replacements possible.
5984 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5985 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5986 DivRHS))
5987 return R;
5988 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00005989
5990 case Instruction::Add:
5991 // Fold: icmp pred (add, X, C1), C2
5992
5993 if (!ICI.isEquality()) {
5994 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5995 if (!LHSC) break;
5996 const APInt &LHSV = LHSC->getValue();
5997
5998 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5999 .subtract(LHSV);
6000
6001 if (ICI.isSignedPredicate()) {
6002 if (CR.getLower().isSignBit()) {
6003 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6004 ConstantInt::get(CR.getUpper()));
6005 } else if (CR.getUpper().isSignBit()) {
6006 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6007 ConstantInt::get(CR.getLower()));
6008 }
6009 } else {
6010 if (CR.getLower().isMinValue()) {
6011 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6012 ConstantInt::get(CR.getUpper()));
6013 } else if (CR.getUpper().isMinValue()) {
6014 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6015 ConstantInt::get(CR.getLower()));
6016 }
6017 }
6018 }
6019 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006020 }
6021
6022 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6023 if (ICI.isEquality()) {
6024 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6025
6026 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6027 // the second operand is a constant, simplify a bit.
6028 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6029 switch (BO->getOpcode()) {
6030 case Instruction::SRem:
6031 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6032 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6033 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6034 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6035 Instruction *NewRem =
6036 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6037 BO->getName());
6038 InsertNewInstBefore(NewRem, ICI);
6039 return new ICmpInst(ICI.getPredicate(), NewRem,
6040 Constant::getNullValue(BO->getType()));
6041 }
6042 }
6043 break;
6044 case Instruction::Add:
6045 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6046 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6047 if (BO->hasOneUse())
6048 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6049 Subtract(RHS, BOp1C));
6050 } else if (RHSV == 0) {
6051 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6052 // efficiently invertible, or if the add has just this one use.
6053 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6054
6055 if (Value *NegVal = dyn_castNegVal(BOp1))
6056 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6057 else if (Value *NegVal = dyn_castNegVal(BOp0))
6058 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6059 else if (BO->hasOneUse()) {
6060 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6061 InsertNewInstBefore(Neg, ICI);
6062 Neg->takeName(BO);
6063 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6064 }
6065 }
6066 break;
6067 case Instruction::Xor:
6068 // For the xor case, we can xor two constants together, eliminating
6069 // the explicit xor.
6070 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6072 ConstantExpr::getXor(RHS, BOC));
6073
6074 // FALLTHROUGH
6075 case Instruction::Sub:
6076 // Replace (([sub|xor] A, B) != 0) with (A != B)
6077 if (RHSV == 0)
6078 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6079 BO->getOperand(1));
6080 break;
6081
6082 case Instruction::Or:
6083 // If bits are being or'd in that are not present in the constant we
6084 // are comparing against, then the comparison could never succeed!
6085 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6086 Constant *NotCI = ConstantExpr::getNot(RHS);
6087 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6088 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6089 isICMP_NE));
6090 }
6091 break;
6092
6093 case Instruction::And:
6094 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6095 // If bits are being compared against that are and'd out, then the
6096 // comparison can never succeed!
6097 if ((RHSV & ~BOC->getValue()) != 0)
6098 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6099 isICMP_NE));
6100
6101 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6102 if (RHS == BOC && RHSV.isPowerOf2())
6103 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6104 ICmpInst::ICMP_NE, LHSI,
6105 Constant::getNullValue(RHS->getType()));
6106
6107 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6108 if (isSignBit(BOC)) {
6109 Value *X = BO->getOperand(0);
6110 Constant *Zero = Constant::getNullValue(X->getType());
6111 ICmpInst::Predicate pred = isICMP_NE ?
6112 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6113 return new ICmpInst(pred, X, Zero);
6114 }
6115
6116 // ((X & ~7) == 0) --> X < 8
6117 if (RHSV == 0 && isHighOnes(BOC)) {
6118 Value *X = BO->getOperand(0);
6119 Constant *NegX = ConstantExpr::getNeg(BOC);
6120 ICmpInst::Predicate pred = isICMP_NE ?
6121 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6122 return new ICmpInst(pred, X, NegX);
6123 }
6124 }
6125 default: break;
6126 }
6127 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6128 // Handle icmp {eq|ne} <intrinsic>, intcst.
6129 if (II->getIntrinsicID() == Intrinsic::bswap) {
6130 AddToWorkList(II);
6131 ICI.setOperand(0, II->getOperand(1));
6132 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6133 return &ICI;
6134 }
6135 }
6136 } else { // Not a ICMP_EQ/ICMP_NE
6137 // If the LHS is a cast from an integral value of the same size,
6138 // then since we know the RHS is a constant, try to simlify.
6139 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6140 Value *CastOp = Cast->getOperand(0);
6141 const Type *SrcTy = CastOp->getType();
6142 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6143 if (SrcTy->isInteger() &&
6144 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6145 // If this is an unsigned comparison, try to make the comparison use
6146 // smaller constant values.
6147 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6148 // X u< 128 => X s> -1
6149 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6150 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6151 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6152 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6153 // X u> 127 => X s< 0
6154 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6155 Constant::getNullValue(SrcTy));
6156 }
6157 }
6158 }
6159 }
6160 return 0;
6161}
6162
6163/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6164/// We only handle extending casts so far.
6165///
6166Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6167 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6168 Value *LHSCIOp = LHSCI->getOperand(0);
6169 const Type *SrcTy = LHSCIOp->getType();
6170 const Type *DestTy = LHSCI->getType();
6171 Value *RHSCIOp;
6172
6173 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6174 // integer type is the same size as the pointer type.
6175 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6176 getTargetData().getPointerSizeInBits() ==
6177 cast<IntegerType>(DestTy)->getBitWidth()) {
6178 Value *RHSOp = 0;
6179 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6180 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6181 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6182 RHSOp = RHSC->getOperand(0);
6183 // If the pointer types don't match, insert a bitcast.
6184 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006185 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006186 }
6187
6188 if (RHSOp)
6189 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6190 }
6191
6192 // The code below only handles extension cast instructions, so far.
6193 // Enforce this.
6194 if (LHSCI->getOpcode() != Instruction::ZExt &&
6195 LHSCI->getOpcode() != Instruction::SExt)
6196 return 0;
6197
6198 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6199 bool isSignedCmp = ICI.isSignedPredicate();
6200
6201 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6202 // Not an extension from the same type?
6203 RHSCIOp = CI->getOperand(0);
6204 if (RHSCIOp->getType() != LHSCIOp->getType())
6205 return 0;
6206
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006207 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006208 // and the other is a zext), then we can't handle this.
6209 if (CI->getOpcode() != LHSCI->getOpcode())
6210 return 0;
6211
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006212 // Deal with equality cases early.
6213 if (ICI.isEquality())
6214 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6215
6216 // A signed comparison of sign extended values simplifies into a
6217 // signed comparison.
6218 if (isSignedCmp && isSignedExt)
6219 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6220
6221 // The other three cases all fold into an unsigned comparison.
6222 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006223 }
6224
6225 // If we aren't dealing with a constant on the RHS, exit early
6226 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6227 if (!CI)
6228 return 0;
6229
6230 // Compute the constant that would happen if we truncated to SrcTy then
6231 // reextended to DestTy.
6232 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6233 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6234
6235 // If the re-extended constant didn't change...
6236 if (Res2 == CI) {
6237 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6238 // For example, we might have:
6239 // %A = sext short %X to uint
6240 // %B = icmp ugt uint %A, 1330
6241 // It is incorrect to transform this into
6242 // %B = icmp ugt short %X, 1330
6243 // because %A may have negative value.
6244 //
6245 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6246 // OR operation is EQ/NE.
6247 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6248 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6249 else
6250 return 0;
6251 }
6252
6253 // The re-extended constant changed so the constant cannot be represented
6254 // in the shorter type. Consequently, we cannot emit a simple comparison.
6255
6256 // First, handle some easy cases. We know the result cannot be equal at this
6257 // point so handle the ICI.isEquality() cases
6258 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6259 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6260 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6261 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6262
6263 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6264 // should have been folded away previously and not enter in here.
6265 Value *Result;
6266 if (isSignedCmp) {
6267 // We're performing a signed comparison.
6268 if (cast<ConstantInt>(CI)->getValue().isNegative())
6269 Result = ConstantInt::getFalse(); // X < (small) --> false
6270 else
6271 Result = ConstantInt::getTrue(); // X < (large) --> true
6272 } else {
6273 // We're performing an unsigned comparison.
6274 if (isSignedExt) {
6275 // We're performing an unsigned comp with a sign extended value.
6276 // This is true if the input is >= 0. [aka >s -1]
6277 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6278 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6279 NegOne, ICI.getName()), ICI);
6280 } else {
6281 // Unsigned extend & unsigned compare -> always true.
6282 Result = ConstantInt::getTrue();
6283 }
6284 }
6285
6286 // Finally, return the value computed.
6287 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6288 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6289 return ReplaceInstUsesWith(ICI, Result);
6290 } else {
6291 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6292 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6293 "ICmp should be folded!");
6294 if (Constant *CI = dyn_cast<Constant>(Result))
6295 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6296 else
6297 return BinaryOperator::createNot(Result);
6298 }
6299}
6300
6301Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6302 return commonShiftTransforms(I);
6303}
6304
6305Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6306 return commonShiftTransforms(I);
6307}
6308
6309Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006310 if (Instruction *R = commonShiftTransforms(I))
6311 return R;
6312
6313 Value *Op0 = I.getOperand(0);
6314
6315 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6316 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6317 if (CSI->isAllOnesValue())
6318 return ReplaceInstUsesWith(I, CSI);
6319
6320 // See if we can turn a signed shr into an unsigned shr.
6321 if (MaskedValueIsZero(Op0,
6322 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6323 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6324
6325 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006326}
6327
6328Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6329 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6331
6332 // shl X, 0 == X and shr X, 0 == X
6333 // shl 0, X == 0 and shr 0, X == 0
6334 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6335 Op0 == Constant::getNullValue(Op0->getType()))
6336 return ReplaceInstUsesWith(I, Op0);
6337
6338 if (isa<UndefValue>(Op0)) {
6339 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6340 return ReplaceInstUsesWith(I, Op0);
6341 else // undef << X -> 0, undef >>u X -> 0
6342 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6343 }
6344 if (isa<UndefValue>(Op1)) {
6345 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6346 return ReplaceInstUsesWith(I, Op0);
6347 else // X << undef, X >>u undef -> 0
6348 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6349 }
6350
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006351 // Try to fold constant and into select arguments.
6352 if (isa<Constant>(Op0))
6353 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6354 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6355 return R;
6356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006357 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6358 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6359 return Res;
6360 return 0;
6361}
6362
6363Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6364 BinaryOperator &I) {
6365 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6366
6367 // See if we can simplify any instructions used by the instruction whose sole
6368 // purpose is to compute bits we don't care about.
6369 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6370 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6371 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6372 KnownZero, KnownOne))
6373 return &I;
6374
6375 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6376 // of a signed value.
6377 //
6378 if (Op1->uge(TypeBits)) {
6379 if (I.getOpcode() != Instruction::AShr)
6380 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6381 else {
6382 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6383 return &I;
6384 }
6385 }
6386
6387 // ((X*C1) << C2) == (X * (C1 << C2))
6388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6389 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6390 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6391 return BinaryOperator::createMul(BO->getOperand(0),
6392 ConstantExpr::getShl(BOOp, Op1));
6393
6394 // Try to fold constant and into select arguments.
6395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6397 return R;
6398 if (isa<PHINode>(Op0))
6399 if (Instruction *NV = FoldOpIntoPhi(I))
6400 return NV;
6401
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006402 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6403 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6404 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6405 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6406 // place. Don't try to do this transformation in this case. Also, we
6407 // require that the input operand is a shift-by-constant so that we have
6408 // confidence that the shifts will get folded together. We could do this
6409 // xform in more cases, but it is unlikely to be profitable.
6410 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6411 isa<ConstantInt>(TrOp->getOperand(1))) {
6412 // Okay, we'll do this xform. Make the shift of shift.
6413 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6414 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6415 I.getName());
6416 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6417
6418 // For logical shifts, the truncation has the effect of making the high
6419 // part of the register be zeros. Emulate this by inserting an AND to
6420 // clear the top bits as needed. This 'and' will usually be zapped by
6421 // other xforms later if dead.
6422 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6423 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6424 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6425
6426 // The mask we constructed says what the trunc would do if occurring
6427 // between the shifts. We want to know the effect *after* the second
6428 // shift. We know that it is a logical shift by a constant, so adjust the
6429 // mask as appropriate.
6430 if (I.getOpcode() == Instruction::Shl)
6431 MaskV <<= Op1->getZExtValue();
6432 else {
6433 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6434 MaskV = MaskV.lshr(Op1->getZExtValue());
6435 }
6436
6437 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6438 TI->getName());
6439 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6440
6441 // Return the value truncated to the interesting size.
6442 return new TruncInst(And, I.getType());
6443 }
6444 }
6445
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006446 if (Op0->hasOneUse()) {
6447 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6448 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6449 Value *V1, *V2;
6450 ConstantInt *CC;
6451 switch (Op0BO->getOpcode()) {
6452 default: break;
6453 case Instruction::Add:
6454 case Instruction::And:
6455 case Instruction::Or:
6456 case Instruction::Xor: {
6457 // These operators commute.
6458 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6459 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6460 match(Op0BO->getOperand(1),
6461 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6462 Instruction *YS = BinaryOperator::createShl(
6463 Op0BO->getOperand(0), Op1,
6464 Op0BO->getName());
6465 InsertNewInstBefore(YS, I); // (Y << C)
6466 Instruction *X =
6467 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6468 Op0BO->getOperand(1)->getName());
6469 InsertNewInstBefore(X, I); // (X + (Y << C))
6470 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6471 return BinaryOperator::createAnd(X, ConstantInt::get(
6472 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6473 }
6474
6475 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6476 Value *Op0BOOp1 = Op0BO->getOperand(1);
6477 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6478 match(Op0BOOp1,
6479 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6480 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6481 V2 == Op1) {
6482 Instruction *YS = BinaryOperator::createShl(
6483 Op0BO->getOperand(0), Op1,
6484 Op0BO->getName());
6485 InsertNewInstBefore(YS, I); // (Y << C)
6486 Instruction *XM =
6487 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6488 V1->getName()+".mask");
6489 InsertNewInstBefore(XM, I); // X & (CC << C)
6490
6491 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6492 }
6493 }
6494
6495 // FALL THROUGH.
6496 case Instruction::Sub: {
6497 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6498 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6499 match(Op0BO->getOperand(0),
6500 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6501 Instruction *YS = BinaryOperator::createShl(
6502 Op0BO->getOperand(1), Op1,
6503 Op0BO->getName());
6504 InsertNewInstBefore(YS, I); // (Y << C)
6505 Instruction *X =
6506 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6507 Op0BO->getOperand(0)->getName());
6508 InsertNewInstBefore(X, I); // (X + (Y << C))
6509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6510 return BinaryOperator::createAnd(X, ConstantInt::get(
6511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6512 }
6513
6514 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6515 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6516 match(Op0BO->getOperand(0),
6517 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6518 m_ConstantInt(CC))) && V2 == Op1 &&
6519 cast<BinaryOperator>(Op0BO->getOperand(0))
6520 ->getOperand(0)->hasOneUse()) {
6521 Instruction *YS = BinaryOperator::createShl(
6522 Op0BO->getOperand(1), Op1,
6523 Op0BO->getName());
6524 InsertNewInstBefore(YS, I); // (Y << C)
6525 Instruction *XM =
6526 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6527 V1->getName()+".mask");
6528 InsertNewInstBefore(XM, I); // X & (CC << C)
6529
6530 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6531 }
6532
6533 break;
6534 }
6535 }
6536
6537
6538 // If the operand is an bitwise operator with a constant RHS, and the
6539 // shift is the only use, we can pull it out of the shift.
6540 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6541 bool isValid = true; // Valid only for And, Or, Xor
6542 bool highBitSet = false; // Transform if high bit of constant set?
6543
6544 switch (Op0BO->getOpcode()) {
6545 default: isValid = false; break; // Do not perform transform!
6546 case Instruction::Add:
6547 isValid = isLeftShift;
6548 break;
6549 case Instruction::Or:
6550 case Instruction::Xor:
6551 highBitSet = false;
6552 break;
6553 case Instruction::And:
6554 highBitSet = true;
6555 break;
6556 }
6557
6558 // If this is a signed shift right, and the high bit is modified
6559 // by the logical operation, do not perform the transformation.
6560 // The highBitSet boolean indicates the value of the high bit of
6561 // the constant which would cause it to be modified for this
6562 // operation.
6563 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006564 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006565 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566
6567 if (isValid) {
6568 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6569
6570 Instruction *NewShift =
6571 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6572 InsertNewInstBefore(NewShift, I);
6573 NewShift->takeName(Op0BO);
6574
6575 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6576 NewRHS);
6577 }
6578 }
6579 }
6580 }
6581
6582 // Find out if this is a shift of a shift by a constant.
6583 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6584 if (ShiftOp && !ShiftOp->isShift())
6585 ShiftOp = 0;
6586
6587 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6588 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6589 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6590 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6591 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6592 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6593 Value *X = ShiftOp->getOperand(0);
6594
6595 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6596 if (AmtSum > TypeBits)
6597 AmtSum = TypeBits;
6598
6599 const IntegerType *Ty = cast<IntegerType>(I.getType());
6600
6601 // Check for (X << c1) << c2 and (X >> c1) >> c2
6602 if (I.getOpcode() == ShiftOp->getOpcode()) {
6603 return BinaryOperator::create(I.getOpcode(), X,
6604 ConstantInt::get(Ty, AmtSum));
6605 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6606 I.getOpcode() == Instruction::AShr) {
6607 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6608 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6609 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6610 I.getOpcode() == Instruction::LShr) {
6611 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6612 Instruction *Shift =
6613 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6614 InsertNewInstBefore(Shift, I);
6615
6616 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6617 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6618 }
6619
6620 // Okay, if we get here, one shift must be left, and the other shift must be
6621 // right. See if the amounts are equal.
6622 if (ShiftAmt1 == ShiftAmt2) {
6623 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6624 if (I.getOpcode() == Instruction::Shl) {
6625 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6626 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6627 }
6628 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6629 if (I.getOpcode() == Instruction::LShr) {
6630 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6631 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6632 }
6633 // We can simplify ((X << C) >>s C) into a trunc + sext.
6634 // NOTE: we could do this for any C, but that would make 'unusual' integer
6635 // types. For now, just stick to ones well-supported by the code
6636 // generators.
6637 const Type *SExtType = 0;
6638 switch (Ty->getBitWidth() - ShiftAmt1) {
6639 case 1 :
6640 case 8 :
6641 case 16 :
6642 case 32 :
6643 case 64 :
6644 case 128:
6645 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6646 break;
6647 default: break;
6648 }
6649 if (SExtType) {
6650 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6651 InsertNewInstBefore(NewTrunc, I);
6652 return new SExtInst(NewTrunc, Ty);
6653 }
6654 // Otherwise, we can't handle it yet.
6655 } else if (ShiftAmt1 < ShiftAmt2) {
6656 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6657
6658 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6659 if (I.getOpcode() == Instruction::Shl) {
6660 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6661 ShiftOp->getOpcode() == Instruction::AShr);
6662 Instruction *Shift =
6663 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6664 InsertNewInstBefore(Shift, I);
6665
6666 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6667 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6668 }
6669
6670 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6671 if (I.getOpcode() == Instruction::LShr) {
6672 assert(ShiftOp->getOpcode() == Instruction::Shl);
6673 Instruction *Shift =
6674 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6675 InsertNewInstBefore(Shift, I);
6676
6677 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6678 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6679 }
6680
6681 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6682 } else {
6683 assert(ShiftAmt2 < ShiftAmt1);
6684 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6685
6686 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6687 if (I.getOpcode() == Instruction::Shl) {
6688 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6689 ShiftOp->getOpcode() == Instruction::AShr);
6690 Instruction *Shift =
6691 BinaryOperator::create(ShiftOp->getOpcode(), X,
6692 ConstantInt::get(Ty, ShiftDiff));
6693 InsertNewInstBefore(Shift, I);
6694
6695 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6696 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6697 }
6698
6699 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6700 if (I.getOpcode() == Instruction::LShr) {
6701 assert(ShiftOp->getOpcode() == Instruction::Shl);
6702 Instruction *Shift =
6703 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6704 InsertNewInstBefore(Shift, I);
6705
6706 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6707 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6708 }
6709
6710 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6711 }
6712 }
6713 return 0;
6714}
6715
6716
6717/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6718/// expression. If so, decompose it, returning some value X, such that Val is
6719/// X*Scale+Offset.
6720///
6721static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6722 int &Offset) {
6723 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6724 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6725 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006726 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006728 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6729 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6730 if (I->getOpcode() == Instruction::Shl) {
6731 // This is a value scaled by '1 << the shift amt'.
6732 Scale = 1U << RHS->getZExtValue();
6733 Offset = 0;
6734 return I->getOperand(0);
6735 } else if (I->getOpcode() == Instruction::Mul) {
6736 // This value is scaled by 'RHS'.
6737 Scale = RHS->getZExtValue();
6738 Offset = 0;
6739 return I->getOperand(0);
6740 } else if (I->getOpcode() == Instruction::Add) {
6741 // We have X+C. Check to see if we really have (X*C2)+C1,
6742 // where C1 is divisible by C2.
6743 unsigned SubScale;
6744 Value *SubVal =
6745 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6746 Offset += RHS->getZExtValue();
6747 Scale = SubScale;
6748 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006749 }
6750 }
6751 }
6752
6753 // Otherwise, we can't look past this.
6754 Scale = 1;
6755 Offset = 0;
6756 return Val;
6757}
6758
6759
6760/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6761/// try to eliminate the cast by moving the type information into the alloc.
6762Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6763 AllocationInst &AI) {
6764 const PointerType *PTy = cast<PointerType>(CI.getType());
6765
6766 // Remove any uses of AI that are dead.
6767 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6768
6769 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6770 Instruction *User = cast<Instruction>(*UI++);
6771 if (isInstructionTriviallyDead(User)) {
6772 while (UI != E && *UI == User)
6773 ++UI; // If this instruction uses AI more than once, don't break UI.
6774
6775 ++NumDeadInst;
6776 DOUT << "IC: DCE: " << *User;
6777 EraseInstFromFunction(*User);
6778 }
6779 }
6780
6781 // Get the type really allocated and the type casted to.
6782 const Type *AllocElTy = AI.getAllocatedType();
6783 const Type *CastElTy = PTy->getElementType();
6784 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6785
6786 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6787 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6788 if (CastElTyAlign < AllocElTyAlign) return 0;
6789
6790 // If the allocation has multiple uses, only promote it if we are strictly
6791 // increasing the alignment of the resultant allocation. If we keep it the
6792 // same, we open the door to infinite loops of various kinds.
6793 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6794
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006795 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6796 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006797 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6798
6799 // See if we can satisfy the modulus by pulling a scale out of the array
6800 // size argument.
6801 unsigned ArraySizeScale;
6802 int ArrayOffset;
6803 Value *NumElements = // See if the array size is a decomposable linear expr.
6804 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6805
6806 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6807 // do the xform.
6808 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6809 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6810
6811 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6812 Value *Amt = 0;
6813 if (Scale == 1) {
6814 Amt = NumElements;
6815 } else {
6816 // If the allocation size is constant, form a constant mul expression
6817 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6818 if (isa<ConstantInt>(NumElements))
6819 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6820 // otherwise multiply the amount and the number of elements
6821 else if (Scale != 1) {
6822 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6823 Amt = InsertNewInstBefore(Tmp, AI);
6824 }
6825 }
6826
6827 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6828 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6829 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6830 Amt = InsertNewInstBefore(Tmp, AI);
6831 }
6832
6833 AllocationInst *New;
6834 if (isa<MallocInst>(AI))
6835 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6836 else
6837 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6838 InsertNewInstBefore(New, AI);
6839 New->takeName(&AI);
6840
6841 // If the allocation has multiple uses, insert a cast and change all things
6842 // that used it to use the new cast. This will also hack on CI, but it will
6843 // die soon.
6844 if (!AI.hasOneUse()) {
6845 AddUsesToWorkList(AI);
6846 // New is the allocation instruction, pointer typed. AI is the original
6847 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6848 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6849 InsertNewInstBefore(NewCast, AI);
6850 AI.replaceAllUsesWith(NewCast);
6851 }
6852 return ReplaceInstUsesWith(CI, New);
6853}
6854
6855/// CanEvaluateInDifferentType - Return true if we can take the specified value
6856/// and return it as type Ty without inserting any new casts and without
6857/// changing the computed value. This is used by code that tries to decide
6858/// whether promoting or shrinking integer operations to wider or smaller types
6859/// will allow us to eliminate a truncate or extend.
6860///
6861/// This is a truncation operation if Ty is smaller than V->getType(), or an
6862/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00006863bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6864 unsigned CastOpc,
6865 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006866 // We can always evaluate constants in another type.
6867 if (isa<ConstantInt>(V))
6868 return true;
6869
6870 Instruction *I = dyn_cast<Instruction>(V);
6871 if (!I) return false;
6872
6873 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6874
Chris Lattneref70bb82007-08-02 06:11:14 +00006875 // If this is an extension or truncate, we can often eliminate it.
6876 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6877 // If this is a cast from the destination type, we can trivially eliminate
6878 // it, and this will remove a cast overall.
6879 if (I->getOperand(0)->getType() == Ty) {
6880 // If the first operand is itself a cast, and is eliminable, do not count
6881 // this as an eliminable cast. We would prefer to eliminate those two
6882 // casts first.
6883 if (!isa<CastInst>(I->getOperand(0)))
6884 ++NumCastsRemoved;
6885 return true;
6886 }
6887 }
6888
6889 // We can't extend or shrink something that has multiple uses: doing so would
6890 // require duplicating the instruction in general, which isn't profitable.
6891 if (!I->hasOneUse()) return false;
6892
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006893 switch (I->getOpcode()) {
6894 case Instruction::Add:
6895 case Instruction::Sub:
6896 case Instruction::And:
6897 case Instruction::Or:
6898 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006899 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006900 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6901 NumCastsRemoved) &&
6902 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6903 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006904
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006905 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006906 // A multiply can be truncated by truncating its operands.
6907 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6908 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6909 NumCastsRemoved) &&
6910 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6911 NumCastsRemoved);
6912
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006913 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006914 // If we are truncating the result of this SHL, and if it's a shift of a
6915 // constant amount, we can always perform a SHL in a smaller type.
6916 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6917 uint32_t BitWidth = Ty->getBitWidth();
6918 if (BitWidth < OrigTy->getBitWidth() &&
6919 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006920 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6921 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006922 }
6923 break;
6924 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006925 // If this is a truncate of a logical shr, we can truncate it to a smaller
6926 // lshr iff we know that the bits we would otherwise be shifting in are
6927 // already zeros.
6928 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6929 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6930 uint32_t BitWidth = Ty->getBitWidth();
6931 if (BitWidth < OrigBitWidth &&
6932 MaskedValueIsZero(I->getOperand(0),
6933 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6934 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6936 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006937 }
6938 }
6939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006940 case Instruction::ZExt:
6941 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006942 case Instruction::Trunc:
6943 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006944 // can safely replace it. Note that replacing it does not reduce the number
6945 // of casts in the input.
6946 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006947 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006948
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 break;
6950 default:
6951 // TODO: Can handle more cases here.
6952 break;
6953 }
6954
6955 return false;
6956}
6957
6958/// EvaluateInDifferentType - Given an expression that
6959/// CanEvaluateInDifferentType returns true for, actually insert the code to
6960/// evaluate the expression.
6961Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6962 bool isSigned) {
6963 if (Constant *C = dyn_cast<Constant>(V))
6964 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6965
6966 // Otherwise, it must be an instruction.
6967 Instruction *I = cast<Instruction>(V);
6968 Instruction *Res = 0;
6969 switch (I->getOpcode()) {
6970 case Instruction::Add:
6971 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006972 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006973 case Instruction::And:
6974 case Instruction::Or:
6975 case Instruction::Xor:
6976 case Instruction::AShr:
6977 case Instruction::LShr:
6978 case Instruction::Shl: {
6979 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6980 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6981 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6982 LHS, RHS, I->getName());
6983 break;
6984 }
6985 case Instruction::Trunc:
6986 case Instruction::ZExt:
6987 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006988 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006989 // just return the source. There's no need to insert it because it is not
6990 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006991 if (I->getOperand(0)->getType() == Ty)
6992 return I->getOperand(0);
6993
Chris Lattneref70bb82007-08-02 06:11:14 +00006994 // Otherwise, must be the same type of case, so just reinsert a new one.
6995 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6996 Ty, I->getName());
6997 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006998 default:
6999 // TODO: Can handle more cases here.
7000 assert(0 && "Unreachable!");
7001 break;
7002 }
7003
7004 return InsertNewInstBefore(Res, *I);
7005}
7006
7007/// @brief Implement the transforms common to all CastInst visitors.
7008Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7009 Value *Src = CI.getOperand(0);
7010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007011 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7012 // eliminate it now.
7013 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7014 if (Instruction::CastOps opc =
7015 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7016 // The first cast (CSrc) is eliminable so we need to fix up or replace
7017 // the second cast (CI). CSrc will then have a good chance of being dead.
7018 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
7019 }
7020 }
7021
7022 // If we are casting a select then fold the cast into the select
7023 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7024 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7025 return NV;
7026
7027 // If we are casting a PHI then fold the cast into the PHI
7028 if (isa<PHINode>(Src))
7029 if (Instruction *NV = FoldOpIntoPhi(CI))
7030 return NV;
7031
7032 return 0;
7033}
7034
7035/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7036Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7037 Value *Src = CI.getOperand(0);
7038
7039 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7040 // If casting the result of a getelementptr instruction with no offset, turn
7041 // this into a cast of the original pointer!
7042 if (GEP->hasAllZeroIndices()) {
7043 // Changing the cast operand is usually not a good idea but it is safe
7044 // here because the pointer operand is being replaced with another
7045 // pointer operand so the opcode doesn't need to change.
7046 AddToWorkList(GEP);
7047 CI.setOperand(0, GEP->getOperand(0));
7048 return &CI;
7049 }
7050
7051 // If the GEP has a single use, and the base pointer is a bitcast, and the
7052 // GEP computes a constant offset, see if we can convert these three
7053 // instructions into fewer. This typically happens with unions and other
7054 // non-type-safe code.
7055 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7056 if (GEP->hasAllConstantIndices()) {
7057 // We are guaranteed to get a constant from EmitGEPOffset.
7058 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7059 int64_t Offset = OffsetV->getSExtValue();
7060
7061 // Get the base pointer input of the bitcast, and the type it points to.
7062 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7063 const Type *GEPIdxTy =
7064 cast<PointerType>(OrigBase->getType())->getElementType();
7065 if (GEPIdxTy->isSized()) {
7066 SmallVector<Value*, 8> NewIndices;
7067
7068 // Start with the index over the outer type. Note that the type size
7069 // might be zero (even if the offset isn't zero) if the indexed type
7070 // is something like [0 x {int, int}]
7071 const Type *IntPtrTy = TD->getIntPtrType();
7072 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007073 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007074 FirstIdx = Offset/TySize;
7075 Offset %= TySize;
7076
7077 // Handle silly modulus not returning values values [0..TySize).
7078 if (Offset < 0) {
7079 --FirstIdx;
7080 Offset += TySize;
7081 assert(Offset >= 0);
7082 }
7083 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7084 }
7085
7086 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7087
7088 // Index into the types. If we fail, set OrigBase to null.
7089 while (Offset) {
7090 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7091 const StructLayout *SL = TD->getStructLayout(STy);
7092 if (Offset < (int64_t)SL->getSizeInBytes()) {
7093 unsigned Elt = SL->getElementContainingOffset(Offset);
7094 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7095
7096 Offset -= SL->getElementOffset(Elt);
7097 GEPIdxTy = STy->getElementType(Elt);
7098 } else {
7099 // Otherwise, we can't index into this, bail out.
7100 Offset = 0;
7101 OrigBase = 0;
7102 }
7103 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7104 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007105 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007106 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7107 Offset %= EltSize;
7108 } else {
7109 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7110 }
7111 GEPIdxTy = STy->getElementType();
7112 } else {
7113 // Otherwise, we can't index into this, bail out.
7114 Offset = 0;
7115 OrigBase = 0;
7116 }
7117 }
7118 if (OrigBase) {
7119 // If we were able to index down into an element, create the GEP
7120 // and bitcast the result. This eliminates one bitcast, potentially
7121 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007122 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7123 NewIndices.begin(),
7124 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 InsertNewInstBefore(NGEP, CI);
7126 NGEP->takeName(GEP);
7127
7128 if (isa<BitCastInst>(CI))
7129 return new BitCastInst(NGEP, CI.getType());
7130 assert(isa<PtrToIntInst>(CI));
7131 return new PtrToIntInst(NGEP, CI.getType());
7132 }
7133 }
7134 }
7135 }
7136 }
7137
7138 return commonCastTransforms(CI);
7139}
7140
7141
7142
7143/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7144/// integer types. This function implements the common transforms for all those
7145/// cases.
7146/// @brief Implement the transforms common to CastInst with integer operands
7147Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7148 if (Instruction *Result = commonCastTransforms(CI))
7149 return Result;
7150
7151 Value *Src = CI.getOperand(0);
7152 const Type *SrcTy = Src->getType();
7153 const Type *DestTy = CI.getType();
7154 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7155 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7156
7157 // See if we can simplify any instructions used by the LHS whose sole
7158 // purpose is to compute bits we don't care about.
7159 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7160 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7161 KnownZero, KnownOne))
7162 return &CI;
7163
7164 // If the source isn't an instruction or has more than one use then we
7165 // can't do anything more.
7166 Instruction *SrcI = dyn_cast<Instruction>(Src);
7167 if (!SrcI || !Src->hasOneUse())
7168 return 0;
7169
7170 // Attempt to propagate the cast into the instruction for int->int casts.
7171 int NumCastsRemoved = 0;
7172 if (!isa<BitCastInst>(CI) &&
7173 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007174 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007175 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007176 // eliminates the cast, so it is always a win. If this is a zero-extension,
7177 // we need to do an AND to maintain the clear top-part of the computation,
7178 // so we require that the input have eliminated at least one cast. If this
7179 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007180 // require that two casts have been eliminated.
7181 bool DoXForm;
7182 switch (CI.getOpcode()) {
7183 default:
7184 // All the others use floating point so we shouldn't actually
7185 // get here because of the check above.
7186 assert(0 && "Unknown cast type");
7187 case Instruction::Trunc:
7188 DoXForm = true;
7189 break;
7190 case Instruction::ZExt:
7191 DoXForm = NumCastsRemoved >= 1;
7192 break;
7193 case Instruction::SExt:
7194 DoXForm = NumCastsRemoved >= 2;
7195 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007196 }
7197
7198 if (DoXForm) {
7199 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7200 CI.getOpcode() == Instruction::SExt);
7201 assert(Res->getType() == DestTy);
7202 switch (CI.getOpcode()) {
7203 default: assert(0 && "Unknown cast type!");
7204 case Instruction::Trunc:
7205 case Instruction::BitCast:
7206 // Just replace this cast with the result.
7207 return ReplaceInstUsesWith(CI, Res);
7208 case Instruction::ZExt: {
7209 // We need to emit an AND to clear the high bits.
7210 assert(SrcBitSize < DestBitSize && "Not a zext?");
7211 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7212 SrcBitSize));
7213 return BinaryOperator::createAnd(Res, C);
7214 }
7215 case Instruction::SExt:
7216 // We need to emit a cast to truncate, then a cast to sext.
7217 return CastInst::create(Instruction::SExt,
7218 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7219 CI), DestTy);
7220 }
7221 }
7222 }
7223
7224 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7225 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7226
7227 switch (SrcI->getOpcode()) {
7228 case Instruction::Add:
7229 case Instruction::Mul:
7230 case Instruction::And:
7231 case Instruction::Or:
7232 case Instruction::Xor:
7233 // If we are discarding information, rewrite.
7234 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7235 // Don't insert two casts if they cannot be eliminated. We allow
7236 // two casts to be inserted if the sizes are the same. This could
7237 // only be converting signedness, which is a noop.
7238 if (DestBitSize == SrcBitSize ||
7239 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7240 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7241 Instruction::CastOps opcode = CI.getOpcode();
7242 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7243 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7244 return BinaryOperator::create(
7245 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7246 }
7247 }
7248
7249 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7250 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7251 SrcI->getOpcode() == Instruction::Xor &&
7252 Op1 == ConstantInt::getTrue() &&
7253 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7254 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7255 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7256 }
7257 break;
7258 case Instruction::SDiv:
7259 case Instruction::UDiv:
7260 case Instruction::SRem:
7261 case Instruction::URem:
7262 // If we are just changing the sign, rewrite.
7263 if (DestBitSize == SrcBitSize) {
7264 // Don't insert two casts if they cannot be eliminated. We allow
7265 // two casts to be inserted if the sizes are the same. This could
7266 // only be converting signedness, which is a noop.
7267 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7268 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7269 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7270 Op0, DestTy, SrcI);
7271 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7272 Op1, DestTy, SrcI);
7273 return BinaryOperator::create(
7274 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7275 }
7276 }
7277 break;
7278
7279 case Instruction::Shl:
7280 // Allow changing the sign of the source operand. Do not allow
7281 // changing the size of the shift, UNLESS the shift amount is a
7282 // constant. We must not change variable sized shifts to a smaller
7283 // size, because it is undefined to shift more bits out than exist
7284 // in the value.
7285 if (DestBitSize == SrcBitSize ||
7286 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7287 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7288 Instruction::BitCast : Instruction::Trunc);
7289 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7290 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7291 return BinaryOperator::createShl(Op0c, Op1c);
7292 }
7293 break;
7294 case Instruction::AShr:
7295 // If this is a signed shr, and if all bits shifted in are about to be
7296 // truncated off, turn it into an unsigned shr to allow greater
7297 // simplifications.
7298 if (DestBitSize < SrcBitSize &&
7299 isa<ConstantInt>(Op1)) {
7300 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7301 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7302 // Insert the new logical shift right.
7303 return BinaryOperator::createLShr(Op0, Op1);
7304 }
7305 }
7306 break;
7307 }
7308 return 0;
7309}
7310
7311Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7312 if (Instruction *Result = commonIntCastTransforms(CI))
7313 return Result;
7314
7315 Value *Src = CI.getOperand(0);
7316 const Type *Ty = CI.getType();
7317 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7318 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7319
7320 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7321 switch (SrcI->getOpcode()) {
7322 default: break;
7323 case Instruction::LShr:
7324 // We can shrink lshr to something smaller if we know the bits shifted in
7325 // are already zeros.
7326 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7327 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7328
7329 // Get a mask for the bits shifting in.
7330 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7331 Value* SrcIOp0 = SrcI->getOperand(0);
7332 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7333 if (ShAmt >= DestBitWidth) // All zeros.
7334 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7335
7336 // Okay, we can shrink this. Truncate the input, then return a new
7337 // shift.
7338 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7339 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7340 Ty, CI);
7341 return BinaryOperator::createLShr(V1, V2);
7342 }
7343 } else { // This is a variable shr.
7344
7345 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7346 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7347 // loop-invariant and CSE'd.
7348 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7349 Value *One = ConstantInt::get(SrcI->getType(), 1);
7350
7351 Value *V = InsertNewInstBefore(
7352 BinaryOperator::createShl(One, SrcI->getOperand(1),
7353 "tmp"), CI);
7354 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7355 SrcI->getOperand(0),
7356 "tmp"), CI);
7357 Value *Zero = Constant::getNullValue(V->getType());
7358 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7359 }
7360 }
7361 break;
7362 }
7363 }
7364
7365 return 0;
7366}
7367
Evan Chenge3779cf2008-03-24 00:21:34 +00007368/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7369/// in order to eliminate the icmp.
7370Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7371 bool DoXform) {
7372 // If we are just checking for a icmp eq of a single bit and zext'ing it
7373 // to an integer, then shift the bit to the appropriate place and then
7374 // cast to integer to avoid the comparison.
7375 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7376 const APInt &Op1CV = Op1C->getValue();
7377
7378 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7379 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7380 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7381 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7382 if (!DoXform) return ICI;
7383
7384 Value *In = ICI->getOperand(0);
7385 Value *Sh = ConstantInt::get(In->getType(),
7386 In->getType()->getPrimitiveSizeInBits()-1);
7387 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7388 In->getName()+".lobit"),
7389 CI);
7390 if (In->getType() != CI.getType())
7391 In = CastInst::createIntegerCast(In, CI.getType(),
7392 false/*ZExt*/, "tmp", &CI);
7393
7394 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7395 Constant *One = ConstantInt::get(In->getType(), 1);
7396 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7397 In->getName()+".not"),
7398 CI);
7399 }
7400
7401 return ReplaceInstUsesWith(CI, In);
7402 }
7403
7404
7405
7406 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7407 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7408 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7409 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7410 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7411 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7412 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7413 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7414 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7415 // This only works for EQ and NE
7416 ICI->isEquality()) {
7417 // If Op1C some other power of two, convert:
7418 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7419 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7420 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7421 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7422
7423 APInt KnownZeroMask(~KnownZero);
7424 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7425 if (!DoXform) return ICI;
7426
7427 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7428 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7429 // (X&4) == 2 --> false
7430 // (X&4) != 2 --> true
7431 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7432 Res = ConstantExpr::getZExt(Res, CI.getType());
7433 return ReplaceInstUsesWith(CI, Res);
7434 }
7435
7436 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7437 Value *In = ICI->getOperand(0);
7438 if (ShiftAmt) {
7439 // Perform a logical shr by shiftamt.
7440 // Insert the shift to put the result in the low bit.
7441 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7442 ConstantInt::get(In->getType(), ShiftAmt),
7443 In->getName()+".lobit"), CI);
7444 }
7445
7446 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7447 Constant *One = ConstantInt::get(In->getType(), 1);
7448 In = BinaryOperator::createXor(In, One, "tmp");
7449 InsertNewInstBefore(cast<Instruction>(In), CI);
7450 }
7451
7452 if (CI.getType() == In->getType())
7453 return ReplaceInstUsesWith(CI, In);
7454 else
7455 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7456 }
7457 }
7458 }
7459
7460 return 0;
7461}
7462
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007463Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7464 // If one of the common conversion will work ..
7465 if (Instruction *Result = commonIntCastTransforms(CI))
7466 return Result;
7467
7468 Value *Src = CI.getOperand(0);
7469
7470 // If this is a cast of a cast
7471 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7472 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7473 // types and if the sizes are just right we can convert this into a logical
7474 // 'and' which will be much cheaper than the pair of casts.
7475 if (isa<TruncInst>(CSrc)) {
7476 // Get the sizes of the types involved
7477 Value *A = CSrc->getOperand(0);
7478 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7479 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7480 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7481 // If we're actually extending zero bits and the trunc is a no-op
7482 if (MidSize < DstSize && SrcSize == DstSize) {
7483 // Replace both of the casts with an And of the type mask.
7484 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7485 Constant *AndConst = ConstantInt::get(AndValue);
7486 Instruction *And =
7487 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7488 // Unfortunately, if the type changed, we need to cast it back.
7489 if (And->getType() != CI.getType()) {
7490 And->setName(CSrc->getName()+".mask");
7491 InsertNewInstBefore(And, CI);
7492 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7493 }
7494 return And;
7495 }
7496 }
7497 }
7498
Evan Chenge3779cf2008-03-24 00:21:34 +00007499 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7500 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007501
Evan Chenge3779cf2008-03-24 00:21:34 +00007502 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7503 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7504 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7505 // of the (zext icmp) will be transformed.
7506 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7507 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7508 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7509 (transformZExtICmp(LHS, CI, false) ||
7510 transformZExtICmp(RHS, CI, false))) {
7511 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7512 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7513 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007514 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007515 }
7516
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007517 return 0;
7518}
7519
7520Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7521 if (Instruction *I = commonIntCastTransforms(CI))
7522 return I;
7523
7524 Value *Src = CI.getOperand(0);
7525
7526 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7527 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7529 // If we are just checking for a icmp eq of a single bit and zext'ing it
7530 // to an integer, then shift the bit to the appropriate place and then
7531 // cast to integer to avoid the comparison.
7532 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7533 const APInt &Op1CV = Op1C->getValue();
7534
7535 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7536 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7537 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7538 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7539 Value *In = ICI->getOperand(0);
7540 Value *Sh = ConstantInt::get(In->getType(),
7541 In->getType()->getPrimitiveSizeInBits()-1);
7542 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7543 In->getName()+".lobit"),
7544 CI);
7545 if (In->getType() != CI.getType())
7546 In = CastInst::createIntegerCast(In, CI.getType(),
7547 true/*SExt*/, "tmp", &CI);
7548
7549 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7550 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7551 In->getName()+".not"), CI);
7552
7553 return ReplaceInstUsesWith(CI, In);
7554 }
7555 }
7556 }
7557
7558 return 0;
7559}
7560
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007561/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7562/// in the specified FP type without changing its value.
7563static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7564 const fltSemantics &Sem) {
7565 APFloat F = CFP->getValueAPF();
7566 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7567 return ConstantFP::get(FPTy, F);
7568 return 0;
7569}
7570
7571/// LookThroughFPExtensions - If this is an fp extension instruction, look
7572/// through it until we get the source value.
7573static Value *LookThroughFPExtensions(Value *V) {
7574 if (Instruction *I = dyn_cast<Instruction>(V))
7575 if (I->getOpcode() == Instruction::FPExt)
7576 return LookThroughFPExtensions(I->getOperand(0));
7577
7578 // If this value is a constant, return the constant in the smallest FP type
7579 // that can accurately represent it. This allows us to turn
7580 // (float)((double)X+2.0) into x+2.0f.
7581 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7582 if (CFP->getType() == Type::PPC_FP128Ty)
7583 return V; // No constant folding of this.
7584 // See if the value can be truncated to float and then reextended.
7585 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7586 return V;
7587 if (CFP->getType() == Type::DoubleTy)
7588 return V; // Won't shrink.
7589 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7590 return V;
7591 // Don't try to shrink to various long double types.
7592 }
7593
7594 return V;
7595}
7596
7597Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7598 if (Instruction *I = commonCastTransforms(CI))
7599 return I;
7600
7601 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7602 // smaller than the destination type, we can eliminate the truncate by doing
7603 // the add as the smaller type. This applies to add/sub/mul/div as well as
7604 // many builtins (sqrt, etc).
7605 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7606 if (OpI && OpI->hasOneUse()) {
7607 switch (OpI->getOpcode()) {
7608 default: break;
7609 case Instruction::Add:
7610 case Instruction::Sub:
7611 case Instruction::Mul:
7612 case Instruction::FDiv:
7613 case Instruction::FRem:
7614 const Type *SrcTy = OpI->getType();
7615 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7616 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7617 if (LHSTrunc->getType() != SrcTy &&
7618 RHSTrunc->getType() != SrcTy) {
7619 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7620 // If the source types were both smaller than the destination type of
7621 // the cast, do this xform.
7622 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7623 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7624 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7625 CI.getType(), CI);
7626 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7627 CI.getType(), CI);
7628 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7629 }
7630 }
7631 break;
7632 }
7633 }
7634 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007635}
7636
7637Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7638 return commonCastTransforms(CI);
7639}
7640
7641Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7642 return commonCastTransforms(CI);
7643}
7644
7645Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7646 return commonCastTransforms(CI);
7647}
7648
7649Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7650 return commonCastTransforms(CI);
7651}
7652
7653Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7654 return commonCastTransforms(CI);
7655}
7656
7657Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7658 return commonPointerCastTransforms(CI);
7659}
7660
Chris Lattner7c1626482008-01-08 07:23:51 +00007661Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7662 if (Instruction *I = commonCastTransforms(CI))
7663 return I;
7664
7665 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7666 if (!DestPointee->isSized()) return 0;
7667
7668 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7669 ConstantInt *Cst;
7670 Value *X;
7671 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7672 m_ConstantInt(Cst)))) {
7673 // If the source and destination operands have the same type, see if this
7674 // is a single-index GEP.
7675 if (X->getType() == CI.getType()) {
7676 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007677 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007678
7679 // Convert the constant to intptr type.
7680 APInt Offset = Cst->getValue();
7681 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7682
7683 // If Offset is evenly divisible by Size, we can do this xform.
7684 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7685 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007686 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007687 }
7688 }
7689 // TODO: Could handle other cases, e.g. where add is indexing into field of
7690 // struct etc.
7691 } else if (CI.getOperand(0)->hasOneUse() &&
7692 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7693 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7694 // "inttoptr+GEP" instead of "add+intptr".
7695
7696 // Get the size of the pointee type.
7697 uint64_t Size = TD->getABITypeSize(DestPointee);
7698
7699 // Convert the constant to intptr type.
7700 APInt Offset = Cst->getValue();
7701 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7702
7703 // If Offset is evenly divisible by Size, we can do this xform.
7704 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7705 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7706
7707 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7708 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007709 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007710 }
7711 }
7712 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007713}
7714
7715Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7716 // If the operands are integer typed then apply the integer transforms,
7717 // otherwise just apply the common ones.
7718 Value *Src = CI.getOperand(0);
7719 const Type *SrcTy = Src->getType();
7720 const Type *DestTy = CI.getType();
7721
7722 if (SrcTy->isInteger() && DestTy->isInteger()) {
7723 if (Instruction *Result = commonIntCastTransforms(CI))
7724 return Result;
7725 } else if (isa<PointerType>(SrcTy)) {
7726 if (Instruction *I = commonPointerCastTransforms(CI))
7727 return I;
7728 } else {
7729 if (Instruction *Result = commonCastTransforms(CI))
7730 return Result;
7731 }
7732
7733
7734 // Get rid of casts from one type to the same type. These are useless and can
7735 // be replaced by the operand.
7736 if (DestTy == Src->getType())
7737 return ReplaceInstUsesWith(CI, Src);
7738
7739 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7740 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7741 const Type *DstElTy = DstPTy->getElementType();
7742 const Type *SrcElTy = SrcPTy->getElementType();
7743
Nate Begemandf5b3612008-03-31 00:22:16 +00007744 // If the address spaces don't match, don't eliminate the bitcast, which is
7745 // required for changing types.
7746 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7747 return 0;
7748
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007749 // If we are casting a malloc or alloca to a pointer to a type of the same
7750 // size, rewrite the allocation instruction to allocate the "right" type.
7751 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7752 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7753 return V;
7754
7755 // If the source and destination are pointers, and this cast is equivalent
7756 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7757 // This can enhance SROA and other transforms that want type-safe pointers.
7758 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7759 unsigned NumZeros = 0;
7760 while (SrcElTy != DstElTy &&
7761 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7762 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7763 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7764 ++NumZeros;
7765 }
7766
7767 // If we found a path from the src to dest, create the getelementptr now.
7768 if (SrcElTy == DstElTy) {
7769 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007770 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7771 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007772 }
7773 }
7774
7775 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7776 if (SVI->hasOneUse()) {
7777 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7778 // a bitconvert to a vector with the same # elts.
7779 if (isa<VectorType>(DestTy) &&
7780 cast<VectorType>(DestTy)->getNumElements() ==
7781 SVI->getType()->getNumElements()) {
7782 CastInst *Tmp;
7783 // If either of the operands is a cast from CI.getType(), then
7784 // evaluating the shuffle in the casted destination's type will allow
7785 // us to eliminate at least one cast.
7786 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7787 Tmp->getOperand(0)->getType() == DestTy) ||
7788 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7789 Tmp->getOperand(0)->getType() == DestTy)) {
7790 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7791 SVI->getOperand(0), DestTy, &CI);
7792 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7793 SVI->getOperand(1), DestTy, &CI);
7794 // Return a new shuffle vector. Use the same element ID's, as we
7795 // know the vector types match #elts.
7796 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7797 }
7798 }
7799 }
7800 }
7801 return 0;
7802}
7803
7804/// GetSelectFoldableOperands - We want to turn code that looks like this:
7805/// %C = or %A, %B
7806/// %D = select %cond, %C, %A
7807/// into:
7808/// %C = select %cond, %B, 0
7809/// %D = or %A, %C
7810///
7811/// Assuming that the specified instruction is an operand to the select, return
7812/// a bitmask indicating which operands of this instruction are foldable if they
7813/// equal the other incoming value of the select.
7814///
7815static unsigned GetSelectFoldableOperands(Instruction *I) {
7816 switch (I->getOpcode()) {
7817 case Instruction::Add:
7818 case Instruction::Mul:
7819 case Instruction::And:
7820 case Instruction::Or:
7821 case Instruction::Xor:
7822 return 3; // Can fold through either operand.
7823 case Instruction::Sub: // Can only fold on the amount subtracted.
7824 case Instruction::Shl: // Can only fold on the shift amount.
7825 case Instruction::LShr:
7826 case Instruction::AShr:
7827 return 1;
7828 default:
7829 return 0; // Cannot fold
7830 }
7831}
7832
7833/// GetSelectFoldableConstant - For the same transformation as the previous
7834/// function, return the identity constant that goes into the select.
7835static Constant *GetSelectFoldableConstant(Instruction *I) {
7836 switch (I->getOpcode()) {
7837 default: assert(0 && "This cannot happen!"); abort();
7838 case Instruction::Add:
7839 case Instruction::Sub:
7840 case Instruction::Or:
7841 case Instruction::Xor:
7842 case Instruction::Shl:
7843 case Instruction::LShr:
7844 case Instruction::AShr:
7845 return Constant::getNullValue(I->getType());
7846 case Instruction::And:
7847 return Constant::getAllOnesValue(I->getType());
7848 case Instruction::Mul:
7849 return ConstantInt::get(I->getType(), 1);
7850 }
7851}
7852
7853/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7854/// have the same opcode and only one use each. Try to simplify this.
7855Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7856 Instruction *FI) {
7857 if (TI->getNumOperands() == 1) {
7858 // If this is a non-volatile load or a cast from the same type,
7859 // merge.
7860 if (TI->isCast()) {
7861 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7862 return 0;
7863 } else {
7864 return 0; // unknown unary op.
7865 }
7866
7867 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007868 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7869 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007870 InsertNewInstBefore(NewSI, SI);
7871 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7872 TI->getType());
7873 }
7874
7875 // Only handle binary operators here.
7876 if (!isa<BinaryOperator>(TI))
7877 return 0;
7878
7879 // Figure out if the operations have any operands in common.
7880 Value *MatchOp, *OtherOpT, *OtherOpF;
7881 bool MatchIsOpZero;
7882 if (TI->getOperand(0) == FI->getOperand(0)) {
7883 MatchOp = TI->getOperand(0);
7884 OtherOpT = TI->getOperand(1);
7885 OtherOpF = FI->getOperand(1);
7886 MatchIsOpZero = true;
7887 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7888 MatchOp = TI->getOperand(1);
7889 OtherOpT = TI->getOperand(0);
7890 OtherOpF = FI->getOperand(0);
7891 MatchIsOpZero = false;
7892 } else if (!TI->isCommutative()) {
7893 return 0;
7894 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7895 MatchOp = TI->getOperand(0);
7896 OtherOpT = TI->getOperand(1);
7897 OtherOpF = FI->getOperand(0);
7898 MatchIsOpZero = true;
7899 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7900 MatchOp = TI->getOperand(1);
7901 OtherOpT = TI->getOperand(0);
7902 OtherOpF = FI->getOperand(1);
7903 MatchIsOpZero = true;
7904 } else {
7905 return 0;
7906 }
7907
7908 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007909 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7910 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 InsertNewInstBefore(NewSI, SI);
7912
7913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7914 if (MatchIsOpZero)
7915 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7916 else
7917 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7918 }
7919 assert(0 && "Shouldn't get here");
7920 return 0;
7921}
7922
7923Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7924 Value *CondVal = SI.getCondition();
7925 Value *TrueVal = SI.getTrueValue();
7926 Value *FalseVal = SI.getFalseValue();
7927
7928 // select true, X, Y -> X
7929 // select false, X, Y -> Y
7930 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7931 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7932
7933 // select C, X, X -> X
7934 if (TrueVal == FalseVal)
7935 return ReplaceInstUsesWith(SI, TrueVal);
7936
7937 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7938 return ReplaceInstUsesWith(SI, FalseVal);
7939 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7940 return ReplaceInstUsesWith(SI, TrueVal);
7941 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7942 if (isa<Constant>(TrueVal))
7943 return ReplaceInstUsesWith(SI, TrueVal);
7944 else
7945 return ReplaceInstUsesWith(SI, FalseVal);
7946 }
7947
7948 if (SI.getType() == Type::Int1Ty) {
7949 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7950 if (C->getZExtValue()) {
7951 // Change: A = select B, true, C --> A = or B, C
7952 return BinaryOperator::createOr(CondVal, FalseVal);
7953 } else {
7954 // Change: A = select B, false, C --> A = and !B, C
7955 Value *NotCond =
7956 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7957 "not."+CondVal->getName()), SI);
7958 return BinaryOperator::createAnd(NotCond, FalseVal);
7959 }
7960 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7961 if (C->getZExtValue() == false) {
7962 // Change: A = select B, C, false --> A = and B, C
7963 return BinaryOperator::createAnd(CondVal, TrueVal);
7964 } else {
7965 // Change: A = select B, C, true --> A = or !B, C
7966 Value *NotCond =
7967 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7968 "not."+CondVal->getName()), SI);
7969 return BinaryOperator::createOr(NotCond, TrueVal);
7970 }
7971 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007972
7973 // select a, b, a -> a&b
7974 // select a, a, b -> a|b
7975 if (CondVal == TrueVal)
7976 return BinaryOperator::createOr(CondVal, FalseVal);
7977 else if (CondVal == FalseVal)
7978 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007979 }
7980
7981 // Selecting between two integer constants?
7982 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7983 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7984 // select C, 1, 0 -> zext C to int
7985 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7986 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7987 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7988 // select C, 0, 1 -> zext !C to int
7989 Value *NotCond =
7990 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7991 "not."+CondVal->getName()), SI);
7992 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7993 }
7994
7995 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7996
7997 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7998
7999 // (x <s 0) ? -1 : 0 -> ashr x, 31
8000 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8001 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8002 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8003 // The comparison constant and the result are not neccessarily the
8004 // same width. Make an all-ones value by inserting a AShr.
8005 Value *X = IC->getOperand(0);
8006 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8007 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8008 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8009 ShAmt, "ones");
8010 InsertNewInstBefore(SRA, SI);
8011
8012 // Finally, convert to the type of the select RHS. We figure out
8013 // if this requires a SExt, Trunc or BitCast based on the sizes.
8014 Instruction::CastOps opc = Instruction::BitCast;
8015 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8016 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8017 if (SRASize < SISize)
8018 opc = Instruction::SExt;
8019 else if (SRASize > SISize)
8020 opc = Instruction::Trunc;
8021 return CastInst::create(opc, SRA, SI.getType());
8022 }
8023 }
8024
8025
8026 // If one of the constants is zero (we know they can't both be) and we
8027 // have an icmp instruction with zero, and we have an 'and' with the
8028 // non-constant value, eliminate this whole mess. This corresponds to
8029 // cases like this: ((X & 27) ? 27 : 0)
8030 if (TrueValC->isZero() || FalseValC->isZero())
8031 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8032 cast<Constant>(IC->getOperand(1))->isNullValue())
8033 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8034 if (ICA->getOpcode() == Instruction::And &&
8035 isa<ConstantInt>(ICA->getOperand(1)) &&
8036 (ICA->getOperand(1) == TrueValC ||
8037 ICA->getOperand(1) == FalseValC) &&
8038 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8039 // Okay, now we know that everything is set up, we just don't
8040 // know whether we have a icmp_ne or icmp_eq and whether the
8041 // true or false val is the zero.
8042 bool ShouldNotVal = !TrueValC->isZero();
8043 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8044 Value *V = ICA;
8045 if (ShouldNotVal)
8046 V = InsertNewInstBefore(BinaryOperator::create(
8047 Instruction::Xor, V, ICA->getOperand(1)), SI);
8048 return ReplaceInstUsesWith(SI, V);
8049 }
8050 }
8051 }
8052
8053 // See if we are selecting two values based on a comparison of the two values.
8054 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8055 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8056 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008057 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8058 // This is not safe in general for floating point:
8059 // consider X== -0, Y== +0.
8060 // It becomes safe if either operand is a nonzero constant.
8061 ConstantFP *CFPt, *CFPf;
8062 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8063 !CFPt->getValueAPF().isZero()) ||
8064 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8065 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008066 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008067 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008068 // Transform (X != Y) ? X : Y -> X
8069 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8070 return ReplaceInstUsesWith(SI, TrueVal);
8071 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8072
8073 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8074 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008075 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8076 // This is not safe in general for floating point:
8077 // consider X== -0, Y== +0.
8078 // It becomes safe if either operand is a nonzero constant.
8079 ConstantFP *CFPt, *CFPf;
8080 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8081 !CFPt->getValueAPF().isZero()) ||
8082 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8083 !CFPf->getValueAPF().isZero()))
8084 return ReplaceInstUsesWith(SI, FalseVal);
8085 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008086 // Transform (X != Y) ? Y : X -> Y
8087 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8088 return ReplaceInstUsesWith(SI, TrueVal);
8089 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8090 }
8091 }
8092
8093 // See if we are selecting two values based on a comparison of the two values.
8094 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8095 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8096 // Transform (X == Y) ? X : Y -> Y
8097 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8098 return ReplaceInstUsesWith(SI, FalseVal);
8099 // Transform (X != Y) ? X : Y -> X
8100 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8101 return ReplaceInstUsesWith(SI, TrueVal);
8102 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8103
8104 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8105 // Transform (X == Y) ? Y : X -> X
8106 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8107 return ReplaceInstUsesWith(SI, FalseVal);
8108 // Transform (X != Y) ? Y : X -> Y
8109 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8110 return ReplaceInstUsesWith(SI, TrueVal);
8111 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8112 }
8113 }
8114
8115 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8116 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8117 if (TI->hasOneUse() && FI->hasOneUse()) {
8118 Instruction *AddOp = 0, *SubOp = 0;
8119
8120 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8121 if (TI->getOpcode() == FI->getOpcode())
8122 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8123 return IV;
8124
8125 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8126 // even legal for FP.
8127 if (TI->getOpcode() == Instruction::Sub &&
8128 FI->getOpcode() == Instruction::Add) {
8129 AddOp = FI; SubOp = TI;
8130 } else if (FI->getOpcode() == Instruction::Sub &&
8131 TI->getOpcode() == Instruction::Add) {
8132 AddOp = TI; SubOp = FI;
8133 }
8134
8135 if (AddOp) {
8136 Value *OtherAddOp = 0;
8137 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8138 OtherAddOp = AddOp->getOperand(1);
8139 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8140 OtherAddOp = AddOp->getOperand(0);
8141 }
8142
8143 if (OtherAddOp) {
8144 // So at this point we know we have (Y -> OtherAddOp):
8145 // select C, (add X, Y), (sub X, Z)
8146 Value *NegVal; // Compute -Z
8147 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8148 NegVal = ConstantExpr::getNeg(C);
8149 } else {
8150 NegVal = InsertNewInstBefore(
8151 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
8152 }
8153
8154 Value *NewTrueOp = OtherAddOp;
8155 Value *NewFalseOp = NegVal;
8156 if (AddOp != TI)
8157 std::swap(NewTrueOp, NewFalseOp);
8158 Instruction *NewSel =
Gabor Greifd6da1d02008-04-06 20:25:17 +00008159 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008160
8161 NewSel = InsertNewInstBefore(NewSel, SI);
8162 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
8163 }
8164 }
8165 }
8166
8167 // See if we can fold the select into one of our operands.
8168 if (SI.getType()->isInteger()) {
8169 // See the comment above GetSelectFoldableOperands for a description of the
8170 // transformation we are doing here.
8171 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8172 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8173 !isa<Constant>(FalseVal))
8174 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8175 unsigned OpToFold = 0;
8176 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8177 OpToFold = 1;
8178 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8179 OpToFold = 2;
8180 }
8181
8182 if (OpToFold) {
8183 Constant *C = GetSelectFoldableConstant(TVI);
8184 Instruction *NewSel =
Gabor Greifd6da1d02008-04-06 20:25:17 +00008185 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008186 InsertNewInstBefore(NewSel, SI);
8187 NewSel->takeName(TVI);
8188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8189 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
8190 else {
8191 assert(0 && "Unknown instruction!!");
8192 }
8193 }
8194 }
8195
8196 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8197 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8198 !isa<Constant>(TrueVal))
8199 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8200 unsigned OpToFold = 0;
8201 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8202 OpToFold = 1;
8203 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8204 OpToFold = 2;
8205 }
8206
8207 if (OpToFold) {
8208 Constant *C = GetSelectFoldableConstant(FVI);
8209 Instruction *NewSel =
Gabor Greifd6da1d02008-04-06 20:25:17 +00008210 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008211 InsertNewInstBefore(NewSel, SI);
8212 NewSel->takeName(FVI);
8213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8214 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
8215 else
8216 assert(0 && "Unknown instruction!!");
8217 }
8218 }
8219 }
8220
8221 if (BinaryOperator::isNot(CondVal)) {
8222 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8223 SI.setOperand(1, FalseVal);
8224 SI.setOperand(2, TrueVal);
8225 return &SI;
8226 }
8227
8228 return 0;
8229}
8230
Dan Gohman2d648bb2008-04-10 18:43:06 +00008231/// EnforceKnownAlignment - If the specified pointer points to an object that
8232/// we control, modify the object's alignment to PrefAlign. This isn't
8233/// often possible though. If alignment is important, a more reliable approach
8234/// is to simply align all global variables and allocation instructions to
8235/// their preferred alignment from the beginning.
8236///
8237static unsigned EnforceKnownAlignment(Value *V,
8238 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008239
Dan Gohman2d648bb2008-04-10 18:43:06 +00008240 User *U = dyn_cast<User>(V);
8241 if (!U) return Align;
8242
8243 switch (getOpcode(U)) {
8244 default: break;
8245 case Instruction::BitCast:
8246 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8247 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248 // If all indexes are zero, it is just the alignment of the base pointer.
8249 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008250 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8251 if (!isa<Constant>(U->getOperand(i)) ||
8252 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008253 AllZeroOperands = false;
8254 break;
8255 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008256
8257 if (AllZeroOperands) {
8258 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008259 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008260 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008261 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008262 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008263 }
8264
8265 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8266 // If there is a large requested alignment and we can, bump up the alignment
8267 // of the global.
8268 if (!GV->isDeclaration()) {
8269 GV->setAlignment(PrefAlign);
8270 Align = PrefAlign;
8271 }
8272 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8273 // If there is a requested alignment and if this is an alloca, round up. We
8274 // don't do this for malloc, because some systems can't respect the request.
8275 if (isa<AllocaInst>(AI)) {
8276 AI->setAlignment(PrefAlign);
8277 Align = PrefAlign;
8278 }
8279 }
8280
8281 return Align;
8282}
8283
8284/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8285/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8286/// and it is more than the alignment of the ultimate object, see if we can
8287/// increase the alignment of the ultimate object, making this check succeed.
8288unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8289 unsigned PrefAlign) {
8290 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8291 sizeof(PrefAlign) * CHAR_BIT;
8292 APInt Mask = APInt::getAllOnesValue(BitWidth);
8293 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8294 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8295 unsigned TrailZ = KnownZero.countTrailingOnes();
8296 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8297
8298 if (PrefAlign > Align)
8299 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8300
8301 // We don't need to make any adjustment.
8302 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008303}
8304
Chris Lattner00ae5132008-01-13 23:50:23 +00008305Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008306 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8307 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008308 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8309 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8310
8311 if (CopyAlign < MinAlign) {
8312 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8313 return MI;
8314 }
8315
8316 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8317 // load/store.
8318 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8319 if (MemOpLength == 0) return 0;
8320
Chris Lattnerc669fb62008-01-14 00:28:35 +00008321 // Source and destination pointer types are always "i8*" for intrinsic. See
8322 // if the size is something we can handle with a single primitive load/store.
8323 // A single load+store correctly handles overlapping memory in the memmove
8324 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008325 unsigned Size = MemOpLength->getZExtValue();
8326 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008327 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008328
Chris Lattnerc669fb62008-01-14 00:28:35 +00008329 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008330 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008331
8332 // Memcpy forces the use of i8* for the source and destination. That means
8333 // that if you're using memcpy to move one double around, you'll get a cast
8334 // from double* to i8*. We'd much rather use a double load+store rather than
8335 // an i64 load+store, here because this improves the odds that the source or
8336 // dest address will be promotable. See if we can find a better type than the
8337 // integer datatype.
8338 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8339 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8340 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8341 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8342 // down through these levels if so.
8343 while (!SrcETy->isFirstClassType()) {
8344 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8345 if (STy->getNumElements() == 1)
8346 SrcETy = STy->getElementType(0);
8347 else
8348 break;
8349 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8350 if (ATy->getNumElements() == 1)
8351 SrcETy = ATy->getElementType();
8352 else
8353 break;
8354 } else
8355 break;
8356 }
8357
8358 if (SrcETy->isFirstClassType())
8359 NewPtrTy = PointerType::getUnqual(SrcETy);
8360 }
8361 }
8362
8363
Chris Lattner00ae5132008-01-13 23:50:23 +00008364 // If the memcpy/memmove provides better alignment info than we can
8365 // infer, use it.
8366 SrcAlign = std::max(SrcAlign, CopyAlign);
8367 DstAlign = std::max(DstAlign, CopyAlign);
8368
8369 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8370 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008371 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8372 InsertNewInstBefore(L, *MI);
8373 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8374
8375 // Set the size of the copy to 0, it will be deleted on the next iteration.
8376 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8377 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008378}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008379
8380/// visitCallInst - CallInst simplification. This mostly only handles folding
8381/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8382/// the heavy lifting.
8383///
8384Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8385 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8386 if (!II) return visitCallSite(&CI);
8387
8388 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8389 // visitCallSite.
8390 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8391 bool Changed = false;
8392
8393 // memmove/cpy/set of zero bytes is a noop.
8394 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8395 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8396
8397 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8398 if (CI->getZExtValue() == 1) {
8399 // Replace the instruction with just byte operations. We would
8400 // transform other cases to loads/stores, but we don't know if
8401 // alignment is sufficient.
8402 }
8403 }
8404
8405 // If we have a memmove and the source operation is a constant global,
8406 // then the source and dest pointers can't alias, so we can change this
8407 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008408 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8410 if (GVSrc->isConstant()) {
8411 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008412 Intrinsic::ID MemCpyID;
8413 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8414 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008415 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008416 MemCpyID = Intrinsic::memcpy_i64;
8417 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008418 Changed = true;
8419 }
8420 }
8421
8422 // If we can determine a pointer alignment that is bigger than currently
8423 // set, update the alignment.
8424 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008425 if (Instruction *I = SimplifyMemTransfer(MI))
8426 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 } else if (isa<MemSetInst>(MI)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008428 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008429 if (MI->getAlignment()->getZExtValue() < Alignment) {
8430 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8431 Changed = true;
8432 }
8433 }
8434
8435 if (Changed) return II;
8436 } else {
8437 switch (II->getIntrinsicID()) {
8438 default: break;
8439 case Intrinsic::ppc_altivec_lvx:
8440 case Intrinsic::ppc_altivec_lvxl:
8441 case Intrinsic::x86_sse_loadu_ps:
8442 case Intrinsic::x86_sse2_loadu_pd:
8443 case Intrinsic::x86_sse2_loadu_dq:
8444 // Turn PPC lvx -> load if the pointer is known aligned.
8445 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008446 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008447 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8448 PointerType::getUnqual(II->getType()),
8449 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008450 return new LoadInst(Ptr);
8451 }
8452 break;
8453 case Intrinsic::ppc_altivec_stvx:
8454 case Intrinsic::ppc_altivec_stvxl:
8455 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008456 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008457 const Type *OpPtrTy =
8458 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008459 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008460 return new StoreInst(II->getOperand(1), Ptr);
8461 }
8462 break;
8463 case Intrinsic::x86_sse_storeu_ps:
8464 case Intrinsic::x86_sse2_storeu_pd:
8465 case Intrinsic::x86_sse2_storeu_dq:
8466 case Intrinsic::x86_sse2_storel_dq:
8467 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008468 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008469 const Type *OpPtrTy =
8470 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008471 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008472 return new StoreInst(II->getOperand(2), Ptr);
8473 }
8474 break;
8475
8476 case Intrinsic::x86_sse_cvttss2si: {
8477 // These intrinsics only demands the 0th element of its input vector. If
8478 // we can simplify the input based on that, do so now.
8479 uint64_t UndefElts;
8480 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8481 UndefElts)) {
8482 II->setOperand(1, V);
8483 return II;
8484 }
8485 break;
8486 }
8487
8488 case Intrinsic::ppc_altivec_vperm:
8489 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8490 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8491 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8492
8493 // Check that all of the elements are integer constants or undefs.
8494 bool AllEltsOk = true;
8495 for (unsigned i = 0; i != 16; ++i) {
8496 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8497 !isa<UndefValue>(Mask->getOperand(i))) {
8498 AllEltsOk = false;
8499 break;
8500 }
8501 }
8502
8503 if (AllEltsOk) {
8504 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008505 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8506 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008507 Value *Result = UndefValue::get(Op0->getType());
8508
8509 // Only extract each element once.
8510 Value *ExtractedElts[32];
8511 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8512
8513 for (unsigned i = 0; i != 16; ++i) {
8514 if (isa<UndefValue>(Mask->getOperand(i)))
8515 continue;
8516 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8517 Idx &= 31; // Match the hardware behavior.
8518
8519 if (ExtractedElts[Idx] == 0) {
8520 Instruction *Elt =
8521 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8522 InsertNewInstBefore(Elt, CI);
8523 ExtractedElts[Idx] = Elt;
8524 }
8525
8526 // Insert this value into the result vector.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008527 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008528 InsertNewInstBefore(cast<Instruction>(Result), CI);
8529 }
8530 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8531 }
8532 }
8533 break;
8534
8535 case Intrinsic::stackrestore: {
8536 // If the save is right next to the restore, remove the restore. This can
8537 // happen when variable allocas are DCE'd.
8538 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8539 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8540 BasicBlock::iterator BI = SS;
8541 if (&*++BI == II)
8542 return EraseInstFromFunction(CI);
8543 }
8544 }
8545
Chris Lattner416d91c2008-02-18 06:12:38 +00008546 // Scan down this block to see if there is another stack restore in the
8547 // same block without an intervening call/alloca.
8548 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008549 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008550 bool CannotRemove = false;
8551 for (++BI; &*BI != TI; ++BI) {
8552 if (isa<AllocaInst>(BI)) {
8553 CannotRemove = true;
8554 break;
8555 }
8556 if (isa<CallInst>(BI)) {
8557 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008558 CannotRemove = true;
8559 break;
8560 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008561 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008562 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008563 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008564 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008565
8566 // If the stack restore is in a return/unwind block and if there are no
8567 // allocas or calls between the restore and the return, nuke the restore.
8568 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8569 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008570 break;
8571 }
8572 }
8573 }
8574
8575 return visitCallSite(II);
8576}
8577
8578// InvokeInst simplification
8579//
8580Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8581 return visitCallSite(&II);
8582}
8583
8584// visitCallSite - Improvements for call and invoke instructions.
8585//
8586Instruction *InstCombiner::visitCallSite(CallSite CS) {
8587 bool Changed = false;
8588
8589 // If the callee is a constexpr cast of a function, attempt to move the cast
8590 // to the arguments of the call/invoke.
8591 if (transformConstExprCastCall(CS)) return 0;
8592
8593 Value *Callee = CS.getCalledValue();
8594
8595 if (Function *CalleeF = dyn_cast<Function>(Callee))
8596 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8597 Instruction *OldCall = CS.getInstruction();
8598 // If the call and callee calling conventions don't match, this call must
8599 // be unreachable, as the call is undefined.
8600 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008601 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8602 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008603 if (!OldCall->use_empty())
8604 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8605 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8606 return EraseInstFromFunction(*OldCall);
8607 return 0;
8608 }
8609
8610 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8611 // This instruction is not reachable, just remove it. We insert a store to
8612 // undef so that we know that this code is not reachable, despite the fact
8613 // that we can't modify the CFG here.
8614 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008615 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008616 CS.getInstruction());
8617
8618 if (!CS.getInstruction()->use_empty())
8619 CS.getInstruction()->
8620 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8621
8622 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8623 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008624 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8625 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008626 }
8627 return EraseInstFromFunction(*CS.getInstruction());
8628 }
8629
Duncan Sands74833f22007-09-17 10:26:40 +00008630 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8631 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8632 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8633 return transformCallThroughTrampoline(CS);
8634
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008635 const PointerType *PTy = cast<PointerType>(Callee->getType());
8636 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8637 if (FTy->isVarArg()) {
8638 // See if we can optimize any arguments passed through the varargs area of
8639 // the call.
8640 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8641 E = CS.arg_end(); I != E; ++I)
8642 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8643 // If this cast does not effect the value passed through the varargs
8644 // area, we can eliminate the use of the cast.
8645 Value *Op = CI->getOperand(0);
8646 if (CI->isLosslessCast()) {
8647 *I = Op;
8648 Changed = true;
8649 }
8650 }
8651 }
8652
Duncan Sands2937e352007-12-19 21:13:37 +00008653 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008654 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008655 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008656 Changed = true;
8657 }
8658
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659 return Changed ? CS.getInstruction() : 0;
8660}
8661
8662// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8663// attempt to move the cast to the arguments of the call/invoke.
8664//
8665bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8666 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8667 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8668 if (CE->getOpcode() != Instruction::BitCast ||
8669 !isa<Function>(CE->getOperand(0)))
8670 return false;
8671 Function *Callee = cast<Function>(CE->getOperand(0));
8672 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008673 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008674
8675 // Okay, this is a cast from a function to a different type. Unless doing so
8676 // would cause a type conversion of one of our arguments, change this call to
8677 // be a direct call with arguments casted to the appropriate types.
8678 //
8679 const FunctionType *FT = Callee->getFunctionType();
8680 const Type *OldRetTy = Caller->getType();
8681
Devang Pateld091d322008-03-11 18:04:06 +00008682 if (isa<StructType>(FT->getReturnType()))
8683 return false; // TODO: Handle multiple return values.
8684
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008685 // Check to see if we are changing the return type...
8686 if (OldRetTy != FT->getReturnType()) {
8687 if (Callee->isDeclaration() && !Caller->use_empty() &&
8688 // Conversion is ok if changing from pointer to int of same size.
8689 !(isa<PointerType>(FT->getReturnType()) &&
8690 TD->getIntPtrType() == OldRetTy))
8691 return false; // Cannot transform this return value.
8692
Duncan Sands5c489582008-01-06 10:12:28 +00008693 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008694 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008695 FT->getReturnType() != Type::VoidTy &&
8696 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008697 return false; // Cannot transform this return value.
8698
Chris Lattner1c8733e2008-03-12 17:45:29 +00008699 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8700 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008701 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8702 return false; // Attribute not compatible with transformed value.
8703 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008704
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008705 // If the callsite is an invoke instruction, and the return value is used by
8706 // a PHI node in a successor, we cannot change the return type of the call
8707 // because there is no place to put the cast instruction (without breaking
8708 // the critical edge). Bail out in this case.
8709 if (!Caller->use_empty())
8710 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8711 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8712 UI != E; ++UI)
8713 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8714 if (PN->getParent() == II->getNormalDest() ||
8715 PN->getParent() == II->getUnwindDest())
8716 return false;
8717 }
8718
8719 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8720 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8721
8722 CallSite::arg_iterator AI = CS.arg_begin();
8723 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8724 const Type *ParamTy = FT->getParamType(i);
8725 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008726
8727 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008728 return false; // Cannot transform this parameter value.
8729
Chris Lattner1c8733e2008-03-12 17:45:29 +00008730 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8731 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008733 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008734 // Some conversions are safe even if we do not have a body.
8735 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008736 bool isConvertible = ActTy == ParamTy ||
8737 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8738 (ParamTy->isInteger() && ActTy->isInteger() &&
8739 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8740 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8741 && c->getValue().isStrictlyPositive());
8742 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008743 }
8744
8745 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8746 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00008747 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008748
Chris Lattner1c8733e2008-03-12 17:45:29 +00008749 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8750 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00008751 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008752 // won't be dropping them. Check that these extra arguments have attributes
8753 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008754 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8755 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00008756 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008757 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00008758 if (PAttrs & ParamAttr::VarArgsIncompatible)
8759 return false;
8760 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008761
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008762 // Okay, we decided that this is a safe thing to do: go ahead and start
8763 // inserting cast instructions as necessary...
8764 std::vector<Value*> Args;
8765 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008766 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00008767 attrVec.reserve(NumCommonArgs);
8768
8769 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008770 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00008771
8772 // If the return value is not being used, the type may not be compatible
8773 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008774 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008775
8776 // Add the new return attributes.
8777 if (RAttrs)
8778 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008779
8780 AI = CS.arg_begin();
8781 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8782 const Type *ParamTy = FT->getParamType(i);
8783 if ((*AI)->getType() == ParamTy) {
8784 Args.push_back(*AI);
8785 } else {
8786 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8787 false, ParamTy, false);
8788 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8789 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8790 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008791
8792 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008793 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00008794 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008795 }
8796
8797 // If the function takes more arguments than the call was taking, add them
8798 // now...
8799 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8800 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8801
8802 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008803 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008804 if (!FT->isVarArg()) {
8805 cerr << "WARNING: While resolving call to function '"
8806 << Callee->getName() << "' arguments were dropped!\n";
8807 } else {
8808 // Add all of the arguments in their promoted form to the arg list...
8809 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8810 const Type *PTy = getPromotedType((*AI)->getType());
8811 if (PTy != (*AI)->getType()) {
8812 // Must promote to pass through va_arg area!
8813 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8814 PTy, false);
8815 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8816 InsertNewInstBefore(Cast, *Caller);
8817 Args.push_back(Cast);
8818 } else {
8819 Args.push_back(*AI);
8820 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008821
Duncan Sands4ced1f82008-01-13 08:02:44 +00008822 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008823 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00008824 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8825 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008826 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008827 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008828
8829 if (FT->getReturnType() == Type::VoidTy)
8830 Caller->setName(""); // Void type should not have a name.
8831
Chris Lattner1c8733e2008-03-12 17:45:29 +00008832 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00008833
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008834 Instruction *NC;
8835 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008836 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8837 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008838 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008839 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008840 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008841 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8842 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008843 CallInst *CI = cast<CallInst>(Caller);
8844 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008845 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008846 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008847 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008848 }
8849
8850 // Insert a cast of the return type as necessary.
8851 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008852 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008854 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008855 OldRetTy, false);
8856 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008857
8858 // If this is an invoke instruction, we should insert it after the first
8859 // non-phi, instruction in the normal successor block.
8860 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8861 BasicBlock::iterator I = II->getNormalDest()->begin();
8862 while (isa<PHINode>(I)) ++I;
8863 InsertNewInstBefore(NC, *I);
8864 } else {
8865 // Otherwise, it's a call, just insert cast right after the call instr
8866 InsertNewInstBefore(NC, *Caller);
8867 }
8868 AddUsersToWorkList(*Caller);
8869 } else {
8870 NV = UndefValue::get(Caller->getType());
8871 }
8872 }
8873
8874 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8875 Caller->replaceAllUsesWith(NV);
8876 Caller->eraseFromParent();
8877 RemoveFromWorkList(Caller);
8878 return true;
8879}
8880
Duncan Sands74833f22007-09-17 10:26:40 +00008881// transformCallThroughTrampoline - Turn a call to a function created by the
8882// init_trampoline intrinsic into a direct call to the underlying function.
8883//
8884Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8885 Value *Callee = CS.getCalledValue();
8886 const PointerType *PTy = cast<PointerType>(Callee->getType());
8887 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00008888 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00008889
8890 // If the call already has the 'nest' attribute somewhere then give up -
8891 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008892 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00008893 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008894
8895 IntrinsicInst *Tramp =
8896 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8897
8898 Function *NestF =
8899 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8900 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8901 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8902
Chris Lattner1c8733e2008-03-12 17:45:29 +00008903 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8904 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008905 unsigned NestIdx = 1;
8906 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00008907 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00008908
8909 // Look for a parameter marked with the 'nest' attribute.
8910 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8911 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00008912 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00008913 // Record the parameter type and any other attributes.
8914 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008915 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00008916 break;
8917 }
8918
8919 if (NestTy) {
8920 Instruction *Caller = CS.getInstruction();
8921 std::vector<Value*> NewArgs;
8922 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8923
Chris Lattner1c8733e2008-03-12 17:45:29 +00008924 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8925 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00008926
Duncan Sands74833f22007-09-17 10:26:40 +00008927 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008928 // mean appending it. Likewise for attributes.
8929
8930 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008931 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8932 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00008933
Duncan Sands74833f22007-09-17 10:26:40 +00008934 {
8935 unsigned Idx = 1;
8936 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8937 do {
8938 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008939 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008940 Value *NestVal = Tramp->getOperand(3);
8941 if (NestVal->getType() != NestTy)
8942 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8943 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008944 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008945 }
8946
8947 if (I == E)
8948 break;
8949
Duncan Sands48b81112008-01-14 19:52:09 +00008950 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008951 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008952 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00008953 NewAttrs.push_back
8954 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008955
8956 ++Idx, ++I;
8957 } while (1);
8958 }
8959
8960 // The trampoline may have been bitcast to a bogus type (FTy).
8961 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008962 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008963
Duncan Sands74833f22007-09-17 10:26:40 +00008964 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008965 NewTypes.reserve(FTy->getNumParams()+1);
8966
Duncan Sands74833f22007-09-17 10:26:40 +00008967 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008968 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008969 {
8970 unsigned Idx = 1;
8971 FunctionType::param_iterator I = FTy->param_begin(),
8972 E = FTy->param_end();
8973
8974 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008975 if (Idx == NestIdx)
8976 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008977 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008978
8979 if (I == E)
8980 break;
8981
Duncan Sands48b81112008-01-14 19:52:09 +00008982 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008983 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008984
8985 ++Idx, ++I;
8986 } while (1);
8987 }
8988
8989 // Replace the trampoline call with a direct call. Let the generic
8990 // code sort out any function type mismatches.
8991 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008992 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008993 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8994 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00008995 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00008996
8997 Instruction *NewCaller;
8998 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008999 NewCaller = InvokeInst::Create(NewCallee,
9000 II->getNormalDest(), II->getUnwindDest(),
9001 NewArgs.begin(), NewArgs.end(),
9002 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009003 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009004 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009005 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009006 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9007 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009008 if (cast<CallInst>(Caller)->isTailCall())
9009 cast<CallInst>(NewCaller)->setTailCall();
9010 cast<CallInst>(NewCaller)->
9011 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009012 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009013 }
9014 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9015 Caller->replaceAllUsesWith(NewCaller);
9016 Caller->eraseFromParent();
9017 RemoveFromWorkList(Caller);
9018 return 0;
9019 }
9020 }
9021
9022 // Replace the trampoline call with a direct call. Since there is no 'nest'
9023 // parameter, there is no need to adjust the argument list. Let the generic
9024 // code sort out any function type mismatches.
9025 Constant *NewCallee =
9026 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9027 CS.setCalledFunction(NewCallee);
9028 return CS.getInstruction();
9029}
9030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009031/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9032/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9033/// and a single binop.
9034Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9035 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9036 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9037 isa<CmpInst>(FirstInst));
9038 unsigned Opc = FirstInst->getOpcode();
9039 Value *LHSVal = FirstInst->getOperand(0);
9040 Value *RHSVal = FirstInst->getOperand(1);
9041
9042 const Type *LHSType = LHSVal->getType();
9043 const Type *RHSType = RHSVal->getType();
9044
9045 // Scan to see if all operands are the same opcode, all have one use, and all
9046 // kill their operands (i.e. the operands have one use).
9047 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9048 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9049 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9050 // Verify type of the LHS matches so we don't fold cmp's of different
9051 // types or GEP's with different index types.
9052 I->getOperand(0)->getType() != LHSType ||
9053 I->getOperand(1)->getType() != RHSType)
9054 return 0;
9055
9056 // If they are CmpInst instructions, check their predicates
9057 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9058 if (cast<CmpInst>(I)->getPredicate() !=
9059 cast<CmpInst>(FirstInst)->getPredicate())
9060 return 0;
9061
9062 // Keep track of which operand needs a phi node.
9063 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9064 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9065 }
9066
9067 // Otherwise, this is safe to transform, determine if it is profitable.
9068
9069 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9070 // Indexes are often folded into load/store instructions, so we don't want to
9071 // hide them behind a phi.
9072 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9073 return 0;
9074
9075 Value *InLHS = FirstInst->getOperand(0);
9076 Value *InRHS = FirstInst->getOperand(1);
9077 PHINode *NewLHS = 0, *NewRHS = 0;
9078 if (LHSVal == 0) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009079 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009080 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9081 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9082 InsertNewInstBefore(NewLHS, PN);
9083 LHSVal = NewLHS;
9084 }
9085
9086 if (RHSVal == 0) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009087 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009088 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9089 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9090 InsertNewInstBefore(NewRHS, PN);
9091 RHSVal = NewRHS;
9092 }
9093
9094 // Add all operands to the new PHIs.
9095 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9096 if (NewLHS) {
9097 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9098 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9099 }
9100 if (NewRHS) {
9101 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9102 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9103 }
9104 }
9105
9106 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9107 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
9108 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9109 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9110 RHSVal);
9111 else {
9112 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009113 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009114 }
9115}
9116
9117/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9118/// of the block that defines it. This means that it must be obvious the value
9119/// of the load is not changed from the point of the load to the end of the
9120/// block it is in.
9121///
9122/// Finally, it is safe, but not profitable, to sink a load targetting a
9123/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9124/// to a register.
9125static bool isSafeToSinkLoad(LoadInst *L) {
9126 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9127
9128 for (++BBI; BBI != E; ++BBI)
9129 if (BBI->mayWriteToMemory())
9130 return false;
9131
9132 // Check for non-address taken alloca. If not address-taken already, it isn't
9133 // profitable to do this xform.
9134 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9135 bool isAddressTaken = false;
9136 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9137 UI != E; ++UI) {
9138 if (isa<LoadInst>(UI)) continue;
9139 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9140 // If storing TO the alloca, then the address isn't taken.
9141 if (SI->getOperand(1) == AI) continue;
9142 }
9143 isAddressTaken = true;
9144 break;
9145 }
9146
9147 if (!isAddressTaken)
9148 return false;
9149 }
9150
9151 return true;
9152}
9153
9154
9155// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9156// operator and they all are only used by the PHI, PHI together their
9157// inputs, and do the operation once, to the result of the PHI.
9158Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9159 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9160
9161 // Scan the instruction, looking for input operations that can be folded away.
9162 // If all input operands to the phi are the same instruction (e.g. a cast from
9163 // the same type or "+42") we can pull the operation through the PHI, reducing
9164 // code size and simplifying code.
9165 Constant *ConstantOp = 0;
9166 const Type *CastSrcTy = 0;
9167 bool isVolatile = false;
9168 if (isa<CastInst>(FirstInst)) {
9169 CastSrcTy = FirstInst->getOperand(0)->getType();
9170 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9171 // Can fold binop, compare or shift here if the RHS is a constant,
9172 // otherwise call FoldPHIArgBinOpIntoPHI.
9173 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9174 if (ConstantOp == 0)
9175 return FoldPHIArgBinOpIntoPHI(PN);
9176 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9177 isVolatile = LI->isVolatile();
9178 // We can't sink the load if the loaded value could be modified between the
9179 // load and the PHI.
9180 if (LI->getParent() != PN.getIncomingBlock(0) ||
9181 !isSafeToSinkLoad(LI))
9182 return 0;
9183 } else if (isa<GetElementPtrInst>(FirstInst)) {
9184 if (FirstInst->getNumOperands() == 2)
9185 return FoldPHIArgBinOpIntoPHI(PN);
9186 // Can't handle general GEPs yet.
9187 return 0;
9188 } else {
9189 return 0; // Cannot fold this operation.
9190 }
9191
9192 // Check to see if all arguments are the same operation.
9193 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9194 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9195 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9196 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9197 return 0;
9198 if (CastSrcTy) {
9199 if (I->getOperand(0)->getType() != CastSrcTy)
9200 return 0; // Cast operation must match.
9201 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9202 // We can't sink the load if the loaded value could be modified between
9203 // the load and the PHI.
9204 if (LI->isVolatile() != isVolatile ||
9205 LI->getParent() != PN.getIncomingBlock(i) ||
9206 !isSafeToSinkLoad(LI))
9207 return 0;
9208 } else if (I->getOperand(1) != ConstantOp) {
9209 return 0;
9210 }
9211 }
9212
9213 // Okay, they are all the same operation. Create a new PHI node of the
9214 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009215 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9216 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009217 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9218
9219 Value *InVal = FirstInst->getOperand(0);
9220 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9221
9222 // Add all operands to the new PHI.
9223 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9224 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9225 if (NewInVal != InVal)
9226 InVal = 0;
9227 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9228 }
9229
9230 Value *PhiVal;
9231 if (InVal) {
9232 // The new PHI unions all of the same values together. This is really
9233 // common, so we handle it intelligently here for compile-time speed.
9234 PhiVal = InVal;
9235 delete NewPN;
9236 } else {
9237 InsertNewInstBefore(NewPN, PN);
9238 PhiVal = NewPN;
9239 }
9240
9241 // Insert and return the new operation.
9242 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9243 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
9244 else if (isa<LoadInst>(FirstInst))
9245 return new LoadInst(PhiVal, "", isVolatile);
9246 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9247 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
9248 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9249 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9250 PhiVal, ConstantOp);
9251 else
9252 assert(0 && "Unknown operation");
9253 return 0;
9254}
9255
9256/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9257/// that is dead.
9258static bool DeadPHICycle(PHINode *PN,
9259 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9260 if (PN->use_empty()) return true;
9261 if (!PN->hasOneUse()) return false;
9262
9263 // Remember this node, and if we find the cycle, return.
9264 if (!PotentiallyDeadPHIs.insert(PN))
9265 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009266
9267 // Don't scan crazily complex things.
9268 if (PotentiallyDeadPHIs.size() == 16)
9269 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009270
9271 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9272 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9273
9274 return false;
9275}
9276
Chris Lattner27b695d2007-11-06 21:52:06 +00009277/// PHIsEqualValue - Return true if this phi node is always equal to
9278/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9279/// z = some value; x = phi (y, z); y = phi (x, z)
9280static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9281 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9282 // See if we already saw this PHI node.
9283 if (!ValueEqualPHIs.insert(PN))
9284 return true;
9285
9286 // Don't scan crazily complex things.
9287 if (ValueEqualPHIs.size() == 16)
9288 return false;
9289
9290 // Scan the operands to see if they are either phi nodes or are equal to
9291 // the value.
9292 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9293 Value *Op = PN->getIncomingValue(i);
9294 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9295 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9296 return false;
9297 } else if (Op != NonPhiInVal)
9298 return false;
9299 }
9300
9301 return true;
9302}
9303
9304
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009305// PHINode simplification
9306//
9307Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9308 // If LCSSA is around, don't mess with Phi nodes
9309 if (MustPreserveLCSSA) return 0;
9310
9311 if (Value *V = PN.hasConstantValue())
9312 return ReplaceInstUsesWith(PN, V);
9313
9314 // If all PHI operands are the same operation, pull them through the PHI,
9315 // reducing code size.
9316 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9317 PN.getIncomingValue(0)->hasOneUse())
9318 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9319 return Result;
9320
9321 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9322 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9323 // PHI)... break the cycle.
9324 if (PN.hasOneUse()) {
9325 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9326 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9327 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9328 PotentiallyDeadPHIs.insert(&PN);
9329 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9330 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9331 }
9332
9333 // If this phi has a single use, and if that use just computes a value for
9334 // the next iteration of a loop, delete the phi. This occurs with unused
9335 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9336 // common case here is good because the only other things that catch this
9337 // are induction variable analysis (sometimes) and ADCE, which is only run
9338 // late.
9339 if (PHIUser->hasOneUse() &&
9340 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9341 PHIUser->use_back() == &PN) {
9342 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9343 }
9344 }
9345
Chris Lattner27b695d2007-11-06 21:52:06 +00009346 // We sometimes end up with phi cycles that non-obviously end up being the
9347 // same value, for example:
9348 // z = some value; x = phi (y, z); y = phi (x, z)
9349 // where the phi nodes don't necessarily need to be in the same block. Do a
9350 // quick check to see if the PHI node only contains a single non-phi value, if
9351 // so, scan to see if the phi cycle is actually equal to that value.
9352 {
9353 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9354 // Scan for the first non-phi operand.
9355 while (InValNo != NumOperandVals &&
9356 isa<PHINode>(PN.getIncomingValue(InValNo)))
9357 ++InValNo;
9358
9359 if (InValNo != NumOperandVals) {
9360 Value *NonPhiInVal = PN.getOperand(InValNo);
9361
9362 // Scan the rest of the operands to see if there are any conflicts, if so
9363 // there is no need to recursively scan other phis.
9364 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9365 Value *OpVal = PN.getIncomingValue(InValNo);
9366 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9367 break;
9368 }
9369
9370 // If we scanned over all operands, then we have one unique value plus
9371 // phi values. Scan PHI nodes to see if they all merge in each other or
9372 // the value.
9373 if (InValNo == NumOperandVals) {
9374 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9375 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9376 return ReplaceInstUsesWith(PN, NonPhiInVal);
9377 }
9378 }
9379 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009380 return 0;
9381}
9382
9383static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9384 Instruction *InsertPoint,
9385 InstCombiner *IC) {
9386 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9387 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9388 // We must cast correctly to the pointer type. Ensure that we
9389 // sign extend the integer value if it is smaller as this is
9390 // used for address computation.
9391 Instruction::CastOps opcode =
9392 (VTySize < PtrSize ? Instruction::SExt :
9393 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9394 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9395}
9396
9397
9398Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9399 Value *PtrOp = GEP.getOperand(0);
9400 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9401 // If so, eliminate the noop.
9402 if (GEP.getNumOperands() == 1)
9403 return ReplaceInstUsesWith(GEP, PtrOp);
9404
9405 if (isa<UndefValue>(GEP.getOperand(0)))
9406 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9407
9408 bool HasZeroPointerIndex = false;
9409 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9410 HasZeroPointerIndex = C->isNullValue();
9411
9412 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9413 return ReplaceInstUsesWith(GEP, PtrOp);
9414
9415 // Eliminate unneeded casts for indices.
9416 bool MadeChange = false;
9417
9418 gep_type_iterator GTI = gep_type_begin(GEP);
9419 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9420 if (isa<SequentialType>(*GTI)) {
9421 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9422 if (CI->getOpcode() == Instruction::ZExt ||
9423 CI->getOpcode() == Instruction::SExt) {
9424 const Type *SrcTy = CI->getOperand(0)->getType();
9425 // We can eliminate a cast from i32 to i64 iff the target
9426 // is a 32-bit pointer target.
9427 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9428 MadeChange = true;
9429 GEP.setOperand(i, CI->getOperand(0));
9430 }
9431 }
9432 }
9433 // If we are using a wider index than needed for this platform, shrink it
9434 // to what we need. If the incoming value needs a cast instruction,
9435 // insert it. This explicit cast can make subsequent optimizations more
9436 // obvious.
9437 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009438 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009439 if (Constant *C = dyn_cast<Constant>(Op)) {
9440 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9441 MadeChange = true;
9442 } else {
9443 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9444 GEP);
9445 GEP.setOperand(i, Op);
9446 MadeChange = true;
9447 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009448 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 }
9450 }
9451 if (MadeChange) return &GEP;
9452
9453 // If this GEP instruction doesn't move the pointer, and if the input operand
9454 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9455 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009456 if (GEP.hasAllZeroIndices()) {
9457 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9458 // If the bitcast is of an allocation, and the allocation will be
9459 // converted to match the type of the cast, don't touch this.
9460 if (isa<AllocationInst>(BCI->getOperand(0))) {
9461 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009462 if (Instruction *I = visitBitCast(*BCI)) {
9463 if (I != BCI) {
9464 I->takeName(BCI);
9465 BCI->getParent()->getInstList().insert(BCI, I);
9466 ReplaceInstUsesWith(*BCI, I);
9467 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009468 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009469 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009470 }
9471 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9472 }
9473 }
9474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009475 // Combine Indices - If the source pointer to this getelementptr instruction
9476 // is a getelementptr instruction, combine the indices of the two
9477 // getelementptr instructions into a single instruction.
9478 //
9479 SmallVector<Value*, 8> SrcGEPOperands;
9480 if (User *Src = dyn_castGetElementPtr(PtrOp))
9481 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9482
9483 if (!SrcGEPOperands.empty()) {
9484 // Note that if our source is a gep chain itself that we wait for that
9485 // chain to be resolved before we perform this transformation. This
9486 // avoids us creating a TON of code in some cases.
9487 //
9488 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9489 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9490 return 0; // Wait until our source is folded to completion.
9491
9492 SmallVector<Value*, 8> Indices;
9493
9494 // Find out whether the last index in the source GEP is a sequential idx.
9495 bool EndsWithSequential = false;
9496 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9497 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9498 EndsWithSequential = !isa<StructType>(*I);
9499
9500 // Can we combine the two pointer arithmetics offsets?
9501 if (EndsWithSequential) {
9502 // Replace: gep (gep %P, long B), long A, ...
9503 // With: T = long A+B; gep %P, T, ...
9504 //
9505 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9506 if (SO1 == Constant::getNullValue(SO1->getType())) {
9507 Sum = GO1;
9508 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9509 Sum = SO1;
9510 } else {
9511 // If they aren't the same type, convert both to an integer of the
9512 // target's pointer size.
9513 if (SO1->getType() != GO1->getType()) {
9514 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9515 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9516 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9517 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9518 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009519 unsigned PS = TD->getPointerSizeInBits();
9520 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009521 // Convert GO1 to SO1's type.
9522 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9523
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009524 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009525 // Convert SO1 to GO1's type.
9526 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9527 } else {
9528 const Type *PT = TD->getIntPtrType();
9529 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9530 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9531 }
9532 }
9533 }
9534 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9535 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9536 else {
9537 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9538 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9539 }
9540 }
9541
9542 // Recycle the GEP we already have if possible.
9543 if (SrcGEPOperands.size() == 2) {
9544 GEP.setOperand(0, SrcGEPOperands[0]);
9545 GEP.setOperand(1, Sum);
9546 return &GEP;
9547 } else {
9548 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9549 SrcGEPOperands.end()-1);
9550 Indices.push_back(Sum);
9551 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9552 }
9553 } else if (isa<Constant>(*GEP.idx_begin()) &&
9554 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9555 SrcGEPOperands.size() != 1) {
9556 // Otherwise we can do the fold if the first index of the GEP is a zero
9557 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9558 SrcGEPOperands.end());
9559 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9560 }
9561
9562 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009563 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9564 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009565
9566 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9567 // GEP of global variable. If all of the indices for this GEP are
9568 // constants, we can promote this to a constexpr instead of an instruction.
9569
9570 // Scan for nonconstants...
9571 SmallVector<Constant*, 8> Indices;
9572 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9573 for (; I != E && isa<Constant>(*I); ++I)
9574 Indices.push_back(cast<Constant>(*I));
9575
9576 if (I == E) { // If they are all constants...
9577 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9578 &Indices[0],Indices.size());
9579
9580 // Replace all uses of the GEP with the new constexpr...
9581 return ReplaceInstUsesWith(GEP, CE);
9582 }
9583 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9584 if (!isa<PointerType>(X->getType())) {
9585 // Not interesting. Source pointer must be a cast from pointer.
9586 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009587 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9588 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009589 //
9590 // This occurs when the program declares an array extern like "int X[];"
9591 //
9592 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9593 const PointerType *XTy = cast<PointerType>(X->getType());
9594 if (const ArrayType *XATy =
9595 dyn_cast<ArrayType>(XTy->getElementType()))
9596 if (const ArrayType *CATy =
9597 dyn_cast<ArrayType>(CPTy->getElementType()))
9598 if (CATy->getElementType() == XATy->getElementType()) {
9599 // At this point, we know that the cast source type is a pointer
9600 // to an array of the same type as the destination pointer
9601 // array. Because the array type is never stepped over (there
9602 // is a leading zero) we can fold the cast into this GEP.
9603 GEP.setOperand(0, X);
9604 return &GEP;
9605 }
9606 } else if (GEP.getNumOperands() == 2) {
9607 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009608 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9609 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9611 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9612 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009613 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9614 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009615 Value *Idx[2];
9616 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9617 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009618 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009619 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009620 // V and GEP are both pointer types --> BitCast
9621 return new BitCastInst(V, GEP.getType());
9622 }
9623
9624 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009625 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009626 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009627 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009629 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009630 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009631 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009632
9633 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9634 // allow either a mul, shift, or constant here.
9635 Value *NewIdx = 0;
9636 ConstantInt *Scale = 0;
9637 if (ArrayEltSize == 1) {
9638 NewIdx = GEP.getOperand(1);
9639 Scale = ConstantInt::get(NewIdx->getType(), 1);
9640 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9641 NewIdx = ConstantInt::get(CI->getType(), 1);
9642 Scale = CI;
9643 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9644 if (Inst->getOpcode() == Instruction::Shl &&
9645 isa<ConstantInt>(Inst->getOperand(1))) {
9646 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9647 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9648 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9649 NewIdx = Inst->getOperand(0);
9650 } else if (Inst->getOpcode() == Instruction::Mul &&
9651 isa<ConstantInt>(Inst->getOperand(1))) {
9652 Scale = cast<ConstantInt>(Inst->getOperand(1));
9653 NewIdx = Inst->getOperand(0);
9654 }
9655 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009656
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009657 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009658 // out, perform the transformation. Note, we don't know whether Scale is
9659 // signed or not. We'll use unsigned version of division/modulo
9660 // operation after making sure Scale doesn't have the sign bit set.
9661 if (Scale && Scale->getSExtValue() >= 0LL &&
9662 Scale->getZExtValue() % ArrayEltSize == 0) {
9663 Scale = ConstantInt::get(Scale->getType(),
9664 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009665 if (Scale->getZExtValue() != 1) {
9666 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009667 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009668 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9669 NewIdx = InsertNewInstBefore(Sc, GEP);
9670 }
9671
9672 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009673 Value *Idx[2];
9674 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9675 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009676 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +00009677 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009678 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9679 // The NewGEP must be pointer typed, so must the old one -> BitCast
9680 return new BitCastInst(NewGEP, GEP.getType());
9681 }
9682 }
9683 }
9684 }
9685
9686 return 0;
9687}
9688
9689Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9690 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009691 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009692 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9693 const Type *NewTy =
9694 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9695 AllocationInst *New = 0;
9696
9697 // Create and insert the replacement instruction...
9698 if (isa<MallocInst>(AI))
9699 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9700 else {
9701 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9702 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9703 }
9704
9705 InsertNewInstBefore(New, AI);
9706
9707 // Scan to the end of the allocation instructions, to skip over a block of
9708 // allocas if possible...
9709 //
9710 BasicBlock::iterator It = New;
9711 while (isa<AllocationInst>(*It)) ++It;
9712
9713 // Now that I is pointing to the first non-allocation-inst in the block,
9714 // insert our getelementptr instruction...
9715 //
9716 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009717 Value *Idx[2];
9718 Idx[0] = NullIdx;
9719 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +00009720 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9721 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722
9723 // Now make everything use the getelementptr instead of the original
9724 // allocation.
9725 return ReplaceInstUsesWith(AI, V);
9726 } else if (isa<UndefValue>(AI.getArraySize())) {
9727 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9728 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009729 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009730
9731 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9732 // Note that we only do this for alloca's, because malloc should allocate and
9733 // return a unique pointer, even for a zero byte allocation.
9734 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009735 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009736 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9737
9738 return 0;
9739}
9740
9741Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9742 Value *Op = FI.getOperand(0);
9743
9744 // free undef -> unreachable.
9745 if (isa<UndefValue>(Op)) {
9746 // Insert a new store to null because we cannot modify the CFG here.
9747 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009748 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009749 return EraseInstFromFunction(FI);
9750 }
9751
9752 // If we have 'free null' delete the instruction. This can happen in stl code
9753 // when lots of inlining happens.
9754 if (isa<ConstantPointerNull>(Op))
9755 return EraseInstFromFunction(FI);
9756
9757 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9758 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9759 FI.setOperand(0, CI->getOperand(0));
9760 return &FI;
9761 }
9762
9763 // Change free (gep X, 0,0,0,0) into free(X)
9764 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9765 if (GEPI->hasAllZeroIndices()) {
9766 AddToWorkList(GEPI);
9767 FI.setOperand(0, GEPI->getOperand(0));
9768 return &FI;
9769 }
9770 }
9771
9772 // Change free(malloc) into nothing, if the malloc has a single use.
9773 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9774 if (MI->hasOneUse()) {
9775 EraseInstFromFunction(FI);
9776 return EraseInstFromFunction(*MI);
9777 }
9778
9779 return 0;
9780}
9781
9782
9783/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009784static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00009785 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009786 User *CI = cast<User>(LI.getOperand(0));
9787 Value *CastOp = CI->getOperand(0);
9788
Devang Patela0f8ea82007-10-18 19:52:32 +00009789 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9790 // Instead of loading constant c string, use corresponding integer value
9791 // directly if string length is small enough.
9792 const std::string &Str = CE->getOperand(0)->getStringValue();
9793 if (!Str.empty()) {
9794 unsigned len = Str.length();
9795 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9796 unsigned numBits = Ty->getPrimitiveSizeInBits();
9797 // Replace LI with immediate integer store.
9798 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00009799 APInt StrVal(numBits, 0);
9800 APInt SingleChar(numBits, 0);
9801 if (TD->isLittleEndian()) {
9802 for (signed i = len-1; i >= 0; i--) {
9803 SingleChar = (uint64_t) Str[i];
9804 StrVal = (StrVal << 8) | SingleChar;
9805 }
9806 } else {
9807 for (unsigned i = 0; i < len; i++) {
9808 SingleChar = (uint64_t) Str[i];
9809 StrVal = (StrVal << 8) | SingleChar;
9810 }
9811 // Append NULL at the end.
9812 SingleChar = 0;
9813 StrVal = (StrVal << 8) | SingleChar;
9814 }
9815 Value *NL = ConstantInt::get(StrVal);
9816 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +00009817 }
9818 }
9819 }
9820
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009821 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9822 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9823 const Type *SrcPTy = SrcTy->getElementType();
9824
9825 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9826 isa<VectorType>(DestPTy)) {
9827 // If the source is an array, the code below will not succeed. Check to
9828 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9829 // constants.
9830 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9831 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9832 if (ASrcTy->getNumElements() != 0) {
9833 Value *Idxs[2];
9834 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9835 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9836 SrcTy = cast<PointerType>(CastOp->getType());
9837 SrcPTy = SrcTy->getElementType();
9838 }
9839
9840 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9841 isa<VectorType>(SrcPTy)) &&
9842 // Do not allow turning this into a load of an integer, which is then
9843 // casted to a pointer, this pessimizes pointer analysis a lot.
9844 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9845 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9846 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9847
9848 // Okay, we are casting from one integer or pointer type to another of
9849 // the same size. Instead of casting the pointer before the load, cast
9850 // the result of the loaded value.
9851 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9852 CI->getName(),
9853 LI.isVolatile()),LI);
9854 // Now cast the result of the load.
9855 return new BitCastInst(NewLoad, LI.getType());
9856 }
9857 }
9858 }
9859 return 0;
9860}
9861
9862/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9863/// from this value cannot trap. If it is not obviously safe to load from the
9864/// specified pointer, we do a quick local scan of the basic block containing
9865/// ScanFrom, to determine if the address is already accessed.
9866static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009867 // If it is an alloca it is always safe to load from.
9868 if (isa<AllocaInst>(V)) return true;
9869
Duncan Sandse40a94a2007-09-19 10:25:38 +00009870 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009871 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009872 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009873 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009874
9875 // Otherwise, be a little bit agressive by scanning the local block where we
9876 // want to check to see if the pointer is already being loaded or stored
9877 // from/to. If so, the previous load or store would have already trapped,
9878 // so there is no harm doing an extra load (also, CSE will later eliminate
9879 // the load entirely).
9880 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9881
9882 while (BBI != E) {
9883 --BBI;
9884
9885 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9886 if (LI->getOperand(0) == V) return true;
9887 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9888 if (SI->getOperand(1) == V) return true;
9889
9890 }
9891 return false;
9892}
9893
Chris Lattner0270a112007-08-11 18:48:48 +00009894/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9895/// until we find the underlying object a pointer is referring to or something
9896/// we don't understand. Note that the returned pointer may be offset from the
9897/// input, because we ignore GEP indices.
9898static Value *GetUnderlyingObject(Value *Ptr) {
9899 while (1) {
9900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9901 if (CE->getOpcode() == Instruction::BitCast ||
9902 CE->getOpcode() == Instruction::GetElementPtr)
9903 Ptr = CE->getOperand(0);
9904 else
9905 return Ptr;
9906 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9907 Ptr = BCI->getOperand(0);
9908 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9909 Ptr = GEP->getOperand(0);
9910 } else {
9911 return Ptr;
9912 }
9913 }
9914}
9915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009916Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9917 Value *Op = LI.getOperand(0);
9918
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009919 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009920 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
9921 if (KnownAlign >
9922 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
9923 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009924 LI.setAlignment(KnownAlign);
9925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009926 // load (cast X) --> cast (load X) iff safe
9927 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009928 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009929 return Res;
9930
9931 // None of the following transforms are legal for volatile loads.
9932 if (LI.isVolatile()) return 0;
9933
9934 if (&LI.getParent()->front() != &LI) {
9935 BasicBlock::iterator BBI = &LI; --BBI;
9936 // If the instruction immediately before this is a store to the same
9937 // address, do a simple form of store->load forwarding.
9938 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9939 if (SI->getOperand(1) == LI.getOperand(0))
9940 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9941 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9942 if (LIB->getOperand(0) == LI.getOperand(0))
9943 return ReplaceInstUsesWith(LI, LIB);
9944 }
9945
Christopher Lamb2c175392007-12-29 07:56:53 +00009946 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9947 const Value *GEPI0 = GEPI->getOperand(0);
9948 // TODO: Consider a target hook for valid address spaces for this xform.
9949 if (isa<ConstantPointerNull>(GEPI0) &&
9950 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009951 // Insert a new store to null instruction before the load to indicate
9952 // that this code is not reachable. We do this instead of inserting
9953 // an unreachable instruction directly because we cannot modify the
9954 // CFG.
9955 new StoreInst(UndefValue::get(LI.getType()),
9956 Constant::getNullValue(Op->getType()), &LI);
9957 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9958 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009959 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960
9961 if (Constant *C = dyn_cast<Constant>(Op)) {
9962 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009963 // TODO: Consider a target hook for valid address spaces for this xform.
9964 if (isa<UndefValue>(C) || (C->isNullValue() &&
9965 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009966 // Insert a new store to null instruction before the load to indicate that
9967 // this code is not reachable. We do this instead of inserting an
9968 // unreachable instruction directly because we cannot modify the CFG.
9969 new StoreInst(UndefValue::get(LI.getType()),
9970 Constant::getNullValue(Op->getType()), &LI);
9971 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9972 }
9973
9974 // Instcombine load (constant global) into the value loaded.
9975 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9976 if (GV->isConstant() && !GV->isDeclaration())
9977 return ReplaceInstUsesWith(LI, GV->getInitializer());
9978
9979 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009981 if (CE->getOpcode() == Instruction::GetElementPtr) {
9982 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9983 if (GV->isConstant() && !GV->isDeclaration())
9984 if (Constant *V =
9985 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9986 return ReplaceInstUsesWith(LI, V);
9987 if (CE->getOperand(0)->isNullValue()) {
9988 // Insert a new store to null instruction before the load to indicate
9989 // that this code is not reachable. We do this instead of inserting
9990 // an unreachable instruction directly because we cannot modify the
9991 // CFG.
9992 new StoreInst(UndefValue::get(LI.getType()),
9993 Constant::getNullValue(Op->getType()), &LI);
9994 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9995 }
9996
9997 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009998 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009999 return Res;
10000 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010001 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010002 }
Chris Lattner0270a112007-08-11 18:48:48 +000010003
10004 // If this load comes from anywhere in a constant global, and if the global
10005 // is all undef or zero, we know what it loads.
10006 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10007 if (GV->isConstant() && GV->hasInitializer()) {
10008 if (GV->getInitializer()->isNullValue())
10009 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10010 else if (isa<UndefValue>(GV->getInitializer()))
10011 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10012 }
10013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010014
10015 if (Op->hasOneUse()) {
10016 // Change select and PHI nodes to select values instead of addresses: this
10017 // helps alias analysis out a lot, allows many others simplifications, and
10018 // exposes redundancy in the code.
10019 //
10020 // Note that we cannot do the transformation unless we know that the
10021 // introduced loads cannot trap! Something like this is valid as long as
10022 // the condition is always false: load (select bool %C, int* null, int* %G),
10023 // but it would not be valid if we transformed it to load from null
10024 // unconditionally.
10025 //
10026 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10027 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10028 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10029 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10030 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10031 SI->getOperand(1)->getName()+".val"), LI);
10032 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10033 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010034 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010035 }
10036
10037 // load (select (cond, null, P)) -> load P
10038 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10039 if (C->isNullValue()) {
10040 LI.setOperand(0, SI->getOperand(2));
10041 return &LI;
10042 }
10043
10044 // load (select (cond, P, null)) -> load P
10045 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10046 if (C->isNullValue()) {
10047 LI.setOperand(0, SI->getOperand(1));
10048 return &LI;
10049 }
10050 }
10051 }
10052 return 0;
10053}
10054
10055/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10056/// when possible.
10057static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10058 User *CI = cast<User>(SI.getOperand(1));
10059 Value *CastOp = CI->getOperand(0);
10060
10061 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10062 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10063 const Type *SrcPTy = SrcTy->getElementType();
10064
10065 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10066 // If the source is an array, the code below will not succeed. Check to
10067 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10068 // constants.
10069 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10070 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10071 if (ASrcTy->getNumElements() != 0) {
10072 Value* Idxs[2];
10073 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10074 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10075 SrcTy = cast<PointerType>(CastOp->getType());
10076 SrcPTy = SrcTy->getElementType();
10077 }
10078
10079 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10080 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10081 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10082
10083 // Okay, we are casting from one integer or pointer type to another of
10084 // the same size. Instead of casting the pointer before
10085 // the store, cast the value to be stored.
10086 Value *NewCast;
10087 Value *SIOp0 = SI.getOperand(0);
10088 Instruction::CastOps opcode = Instruction::BitCast;
10089 const Type* CastSrcTy = SIOp0->getType();
10090 const Type* CastDstTy = SrcPTy;
10091 if (isa<PointerType>(CastDstTy)) {
10092 if (CastSrcTy->isInteger())
10093 opcode = Instruction::IntToPtr;
10094 } else if (isa<IntegerType>(CastDstTy)) {
10095 if (isa<PointerType>(SIOp0->getType()))
10096 opcode = Instruction::PtrToInt;
10097 }
10098 if (Constant *C = dyn_cast<Constant>(SIOp0))
10099 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10100 else
10101 NewCast = IC.InsertNewInstBefore(
10102 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10103 SI);
10104 return new StoreInst(NewCast, CastOp);
10105 }
10106 }
10107 }
10108 return 0;
10109}
10110
10111Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10112 Value *Val = SI.getOperand(0);
10113 Value *Ptr = SI.getOperand(1);
10114
10115 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10116 EraseInstFromFunction(SI);
10117 ++NumCombined;
10118 return 0;
10119 }
10120
10121 // If the RHS is an alloca with a single use, zapify the store, making the
10122 // alloca dead.
10123 if (Ptr->hasOneUse()) {
10124 if (isa<AllocaInst>(Ptr)) {
10125 EraseInstFromFunction(SI);
10126 ++NumCombined;
10127 return 0;
10128 }
10129
10130 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10131 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10132 GEP->getOperand(0)->hasOneUse()) {
10133 EraseInstFromFunction(SI);
10134 ++NumCombined;
10135 return 0;
10136 }
10137 }
10138
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010139 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010140 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10141 if (KnownAlign >
10142 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10143 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010144 SI.setAlignment(KnownAlign);
10145
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146 // Do really simple DSE, to catch cases where there are several consequtive
10147 // stores to the same location, separated by a few arithmetic operations. This
10148 // situation often occurs with bitfield accesses.
10149 BasicBlock::iterator BBI = &SI;
10150 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10151 --ScanInsts) {
10152 --BBI;
10153
10154 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10155 // Prev store isn't volatile, and stores to the same location?
10156 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10157 ++NumDeadStore;
10158 ++BBI;
10159 EraseInstFromFunction(*PrevSI);
10160 continue;
10161 }
10162 break;
10163 }
10164
10165 // If this is a load, we have to stop. However, if the loaded value is from
10166 // the pointer we're loading and is producing the pointer we're storing,
10167 // then *this* store is dead (X = load P; store X -> P).
10168 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010169 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010170 EraseInstFromFunction(SI);
10171 ++NumCombined;
10172 return 0;
10173 }
10174 // Otherwise, this is a load from some other location. Stores before it
10175 // may not be dead.
10176 break;
10177 }
10178
10179 // Don't skip over loads or things that can modify memory.
10180 if (BBI->mayWriteToMemory())
10181 break;
10182 }
10183
10184
10185 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10186
10187 // store X, null -> turns into 'unreachable' in SimplifyCFG
10188 if (isa<ConstantPointerNull>(Ptr)) {
10189 if (!isa<UndefValue>(Val)) {
10190 SI.setOperand(0, UndefValue::get(Val->getType()));
10191 if (Instruction *U = dyn_cast<Instruction>(Val))
10192 AddToWorkList(U); // Dropped a use.
10193 ++NumCombined;
10194 }
10195 return 0; // Do not modify these!
10196 }
10197
10198 // store undef, Ptr -> noop
10199 if (isa<UndefValue>(Val)) {
10200 EraseInstFromFunction(SI);
10201 ++NumCombined;
10202 return 0;
10203 }
10204
10205 // If the pointer destination is a cast, see if we can fold the cast into the
10206 // source instead.
10207 if (isa<CastInst>(Ptr))
10208 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10209 return Res;
10210 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10211 if (CE->isCast())
10212 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10213 return Res;
10214
10215
10216 // If this store is the last instruction in the basic block, and if the block
10217 // ends with an unconditional branch, try to move it to the successor block.
10218 BBI = &SI; ++BBI;
10219 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10220 if (BI->isUnconditional())
10221 if (SimplifyStoreAtEndOfBlock(SI))
10222 return 0; // xform done!
10223
10224 return 0;
10225}
10226
10227/// SimplifyStoreAtEndOfBlock - Turn things like:
10228/// if () { *P = v1; } else { *P = v2 }
10229/// into a phi node with a store in the successor.
10230///
10231/// Simplify things like:
10232/// *P = v1; if () { *P = v2; }
10233/// into a phi node with a store in the successor.
10234///
10235bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10236 BasicBlock *StoreBB = SI.getParent();
10237
10238 // Check to see if the successor block has exactly two incoming edges. If
10239 // so, see if the other predecessor contains a store to the same location.
10240 // if so, insert a PHI node (if needed) and move the stores down.
10241 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10242
10243 // Determine whether Dest has exactly two predecessors and, if so, compute
10244 // the other predecessor.
10245 pred_iterator PI = pred_begin(DestBB);
10246 BasicBlock *OtherBB = 0;
10247 if (*PI != StoreBB)
10248 OtherBB = *PI;
10249 ++PI;
10250 if (PI == pred_end(DestBB))
10251 return false;
10252
10253 if (*PI != StoreBB) {
10254 if (OtherBB)
10255 return false;
10256 OtherBB = *PI;
10257 }
10258 if (++PI != pred_end(DestBB))
10259 return false;
10260
10261
10262 // Verify that the other block ends in a branch and is not otherwise empty.
10263 BasicBlock::iterator BBI = OtherBB->getTerminator();
10264 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10265 if (!OtherBr || BBI == OtherBB->begin())
10266 return false;
10267
10268 // If the other block ends in an unconditional branch, check for the 'if then
10269 // else' case. there is an instruction before the branch.
10270 StoreInst *OtherStore = 0;
10271 if (OtherBr->isUnconditional()) {
10272 // If this isn't a store, or isn't a store to the same location, bail out.
10273 --BBI;
10274 OtherStore = dyn_cast<StoreInst>(BBI);
10275 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10276 return false;
10277 } else {
10278 // Otherwise, the other block ended with a conditional branch. If one of the
10279 // destinations is StoreBB, then we have the if/then case.
10280 if (OtherBr->getSuccessor(0) != StoreBB &&
10281 OtherBr->getSuccessor(1) != StoreBB)
10282 return false;
10283
10284 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10285 // if/then triangle. See if there is a store to the same ptr as SI that
10286 // lives in OtherBB.
10287 for (;; --BBI) {
10288 // Check to see if we find the matching store.
10289 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10290 if (OtherStore->getOperand(1) != SI.getOperand(1))
10291 return false;
10292 break;
10293 }
10294 // If we find something that may be using the stored value, or if we run
10295 // out of instructions, we can't do the xform.
10296 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10297 BBI == OtherBB->begin())
10298 return false;
10299 }
10300
10301 // In order to eliminate the store in OtherBr, we have to
10302 // make sure nothing reads the stored value in StoreBB.
10303 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10304 // FIXME: This should really be AA driven.
10305 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10306 return false;
10307 }
10308 }
10309
10310 // Insert a PHI node now if we need it.
10311 Value *MergedVal = OtherStore->getOperand(0);
10312 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010313 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010314 PN->reserveOperandSpace(2);
10315 PN->addIncoming(SI.getOperand(0), SI.getParent());
10316 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10317 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10318 }
10319
10320 // Advance to a place where it is safe to insert the new store and
10321 // insert it.
10322 BBI = DestBB->begin();
10323 while (isa<PHINode>(BBI)) ++BBI;
10324 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10325 OtherStore->isVolatile()), *BBI);
10326
10327 // Nuke the old stores.
10328 EraseInstFromFunction(SI);
10329 EraseInstFromFunction(*OtherStore);
10330 ++NumCombined;
10331 return true;
10332}
10333
10334
10335Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10336 // Change br (not X), label True, label False to: br X, label False, True
10337 Value *X = 0;
10338 BasicBlock *TrueDest;
10339 BasicBlock *FalseDest;
10340 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10341 !isa<Constant>(X)) {
10342 // Swap Destinations and condition...
10343 BI.setCondition(X);
10344 BI.setSuccessor(0, FalseDest);
10345 BI.setSuccessor(1, TrueDest);
10346 return &BI;
10347 }
10348
10349 // Cannonicalize fcmp_one -> fcmp_oeq
10350 FCmpInst::Predicate FPred; Value *Y;
10351 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10352 TrueDest, FalseDest)))
10353 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10354 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10355 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10356 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10357 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10358 NewSCC->takeName(I);
10359 // Swap Destinations and condition...
10360 BI.setCondition(NewSCC);
10361 BI.setSuccessor(0, FalseDest);
10362 BI.setSuccessor(1, TrueDest);
10363 RemoveFromWorkList(I);
10364 I->eraseFromParent();
10365 AddToWorkList(NewSCC);
10366 return &BI;
10367 }
10368
10369 // Cannonicalize icmp_ne -> icmp_eq
10370 ICmpInst::Predicate IPred;
10371 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10372 TrueDest, FalseDest)))
10373 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10374 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10375 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10376 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10377 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10378 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10379 NewSCC->takeName(I);
10380 // Swap Destinations and condition...
10381 BI.setCondition(NewSCC);
10382 BI.setSuccessor(0, FalseDest);
10383 BI.setSuccessor(1, TrueDest);
10384 RemoveFromWorkList(I);
10385 I->eraseFromParent();;
10386 AddToWorkList(NewSCC);
10387 return &BI;
10388 }
10389
10390 return 0;
10391}
10392
10393Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10394 Value *Cond = SI.getCondition();
10395 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10396 if (I->getOpcode() == Instruction::Add)
10397 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10398 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10399 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10400 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10401 AddRHS));
10402 SI.setOperand(0, I->getOperand(0));
10403 AddToWorkList(I);
10404 return &SI;
10405 }
10406 }
10407 return 0;
10408}
10409
10410/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10411/// is to leave as a vector operation.
10412static bool CheapToScalarize(Value *V, bool isConstant) {
10413 if (isa<ConstantAggregateZero>(V))
10414 return true;
10415 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10416 if (isConstant) return true;
10417 // If all elts are the same, we can extract.
10418 Constant *Op0 = C->getOperand(0);
10419 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10420 if (C->getOperand(i) != Op0)
10421 return false;
10422 return true;
10423 }
10424 Instruction *I = dyn_cast<Instruction>(V);
10425 if (!I) return false;
10426
10427 // Insert element gets simplified to the inserted element or is deleted if
10428 // this is constant idx extract element and its a constant idx insertelt.
10429 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10430 isa<ConstantInt>(I->getOperand(2)))
10431 return true;
10432 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10433 return true;
10434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10435 if (BO->hasOneUse() &&
10436 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10437 CheapToScalarize(BO->getOperand(1), isConstant)))
10438 return true;
10439 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10440 if (CI->hasOneUse() &&
10441 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10442 CheapToScalarize(CI->getOperand(1), isConstant)))
10443 return true;
10444
10445 return false;
10446}
10447
10448/// Read and decode a shufflevector mask.
10449///
10450/// It turns undef elements into values that are larger than the number of
10451/// elements in the input.
10452static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10453 unsigned NElts = SVI->getType()->getNumElements();
10454 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10455 return std::vector<unsigned>(NElts, 0);
10456 if (isa<UndefValue>(SVI->getOperand(2)))
10457 return std::vector<unsigned>(NElts, 2*NElts);
10458
10459 std::vector<unsigned> Result;
10460 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10461 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10462 if (isa<UndefValue>(CP->getOperand(i)))
10463 Result.push_back(NElts*2); // undef -> 8
10464 else
10465 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10466 return Result;
10467}
10468
10469/// FindScalarElement - Given a vector and an element number, see if the scalar
10470/// value is already around as a register, for example if it were inserted then
10471/// extracted from the vector.
10472static Value *FindScalarElement(Value *V, unsigned EltNo) {
10473 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10474 const VectorType *PTy = cast<VectorType>(V->getType());
10475 unsigned Width = PTy->getNumElements();
10476 if (EltNo >= Width) // Out of range access.
10477 return UndefValue::get(PTy->getElementType());
10478
10479 if (isa<UndefValue>(V))
10480 return UndefValue::get(PTy->getElementType());
10481 else if (isa<ConstantAggregateZero>(V))
10482 return Constant::getNullValue(PTy->getElementType());
10483 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10484 return CP->getOperand(EltNo);
10485 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10486 // If this is an insert to a variable element, we don't know what it is.
10487 if (!isa<ConstantInt>(III->getOperand(2)))
10488 return 0;
10489 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10490
10491 // If this is an insert to the element we are looking for, return the
10492 // inserted value.
10493 if (EltNo == IIElt)
10494 return III->getOperand(1);
10495
10496 // Otherwise, the insertelement doesn't modify the value, recurse on its
10497 // vector input.
10498 return FindScalarElement(III->getOperand(0), EltNo);
10499 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10500 unsigned InEl = getShuffleMask(SVI)[EltNo];
10501 if (InEl < Width)
10502 return FindScalarElement(SVI->getOperand(0), InEl);
10503 else if (InEl < Width*2)
10504 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10505 else
10506 return UndefValue::get(PTy->getElementType());
10507 }
10508
10509 // Otherwise, we don't know.
10510 return 0;
10511}
10512
10513Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10514
10515 // If vector val is undef, replace extract with scalar undef.
10516 if (isa<UndefValue>(EI.getOperand(0)))
10517 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10518
10519 // If vector val is constant 0, replace extract with scalar 0.
10520 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10521 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10522
10523 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10524 // If vector val is constant with uniform operands, replace EI
10525 // with that operand
10526 Constant *op0 = C->getOperand(0);
10527 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10528 if (C->getOperand(i) != op0) {
10529 op0 = 0;
10530 break;
10531 }
10532 if (op0)
10533 return ReplaceInstUsesWith(EI, op0);
10534 }
10535
10536 // If extracting a specified index from the vector, see if we can recursively
10537 // find a previously computed scalar that was inserted into the vector.
10538 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10539 unsigned IndexVal = IdxC->getZExtValue();
10540 unsigned VectorWidth =
10541 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10542
10543 // If this is extracting an invalid index, turn this into undef, to avoid
10544 // crashing the code below.
10545 if (IndexVal >= VectorWidth)
10546 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10547
10548 // This instruction only demands the single element from the input vector.
10549 // If the input vector has a single use, simplify it based on this use
10550 // property.
10551 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10552 uint64_t UndefElts;
10553 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10554 1 << IndexVal,
10555 UndefElts)) {
10556 EI.setOperand(0, V);
10557 return &EI;
10558 }
10559 }
10560
10561 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10562 return ReplaceInstUsesWith(EI, Elt);
10563
10564 // If the this extractelement is directly using a bitcast from a vector of
10565 // the same number of elements, see if we can find the source element from
10566 // it. In this case, we will end up needing to bitcast the scalars.
10567 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10568 if (const VectorType *VT =
10569 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10570 if (VT->getNumElements() == VectorWidth)
10571 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10572 return new BitCastInst(Elt, EI.getType());
10573 }
10574 }
10575
10576 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10577 if (I->hasOneUse()) {
10578 // Push extractelement into predecessor operation if legal and
10579 // profitable to do so
10580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10581 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10582 if (CheapToScalarize(BO, isConstantElt)) {
10583 ExtractElementInst *newEI0 =
10584 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10585 EI.getName()+".lhs");
10586 ExtractElementInst *newEI1 =
10587 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10588 EI.getName()+".rhs");
10589 InsertNewInstBefore(newEI0, EI);
10590 InsertNewInstBefore(newEI1, EI);
10591 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10592 }
10593 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010594 unsigned AS =
10595 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010596 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10597 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010598 GetElementPtrInst *GEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010599 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010600 InsertNewInstBefore(GEP, EI);
10601 return new LoadInst(GEP);
10602 }
10603 }
10604 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10605 // Extracting the inserted element?
10606 if (IE->getOperand(2) == EI.getOperand(1))
10607 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10608 // If the inserted and extracted elements are constants, they must not
10609 // be the same value, extract from the pre-inserted value instead.
10610 if (isa<Constant>(IE->getOperand(2)) &&
10611 isa<Constant>(EI.getOperand(1))) {
10612 AddUsesToWorkList(EI);
10613 EI.setOperand(0, IE->getOperand(0));
10614 return &EI;
10615 }
10616 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10617 // If this is extracting an element from a shufflevector, figure out where
10618 // it came from and extract from the appropriate input element instead.
10619 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10620 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10621 Value *Src;
10622 if (SrcIdx < SVI->getType()->getNumElements())
10623 Src = SVI->getOperand(0);
10624 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10625 SrcIdx -= SVI->getType()->getNumElements();
10626 Src = SVI->getOperand(1);
10627 } else {
10628 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10629 }
10630 return new ExtractElementInst(Src, SrcIdx);
10631 }
10632 }
10633 }
10634 return 0;
10635}
10636
10637/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10638/// elements from either LHS or RHS, return the shuffle mask and true.
10639/// Otherwise, return false.
10640static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10641 std::vector<Constant*> &Mask) {
10642 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10643 "Invalid CollectSingleShuffleElements");
10644 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10645
10646 if (isa<UndefValue>(V)) {
10647 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10648 return true;
10649 } else if (V == LHS) {
10650 for (unsigned i = 0; i != NumElts; ++i)
10651 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10652 return true;
10653 } else if (V == RHS) {
10654 for (unsigned i = 0; i != NumElts; ++i)
10655 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10656 return true;
10657 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10658 // If this is an insert of an extract from some other vector, include it.
10659 Value *VecOp = IEI->getOperand(0);
10660 Value *ScalarOp = IEI->getOperand(1);
10661 Value *IdxOp = IEI->getOperand(2);
10662
10663 if (!isa<ConstantInt>(IdxOp))
10664 return false;
10665 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10666
10667 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10668 // Okay, we can handle this if the vector we are insertinting into is
10669 // transitively ok.
10670 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10671 // If so, update the mask to reflect the inserted undef.
10672 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10673 return true;
10674 }
10675 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10676 if (isa<ConstantInt>(EI->getOperand(1)) &&
10677 EI->getOperand(0)->getType() == V->getType()) {
10678 unsigned ExtractedIdx =
10679 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10680
10681 // This must be extracting from either LHS or RHS.
10682 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10683 // Okay, we can handle this if the vector we are insertinting into is
10684 // transitively ok.
10685 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10686 // If so, update the mask to reflect the inserted value.
10687 if (EI->getOperand(0) == LHS) {
10688 Mask[InsertedIdx & (NumElts-1)] =
10689 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10690 } else {
10691 assert(EI->getOperand(0) == RHS);
10692 Mask[InsertedIdx & (NumElts-1)] =
10693 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10694
10695 }
10696 return true;
10697 }
10698 }
10699 }
10700 }
10701 }
10702 // TODO: Handle shufflevector here!
10703
10704 return false;
10705}
10706
10707/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10708/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10709/// that computes V and the LHS value of the shuffle.
10710static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10711 Value *&RHS) {
10712 assert(isa<VectorType>(V->getType()) &&
10713 (RHS == 0 || V->getType() == RHS->getType()) &&
10714 "Invalid shuffle!");
10715 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10716
10717 if (isa<UndefValue>(V)) {
10718 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10719 return V;
10720 } else if (isa<ConstantAggregateZero>(V)) {
10721 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10722 return V;
10723 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10724 // If this is an insert of an extract from some other vector, include it.
10725 Value *VecOp = IEI->getOperand(0);
10726 Value *ScalarOp = IEI->getOperand(1);
10727 Value *IdxOp = IEI->getOperand(2);
10728
10729 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10730 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10731 EI->getOperand(0)->getType() == V->getType()) {
10732 unsigned ExtractedIdx =
10733 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10734 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10735
10736 // Either the extracted from or inserted into vector must be RHSVec,
10737 // otherwise we'd end up with a shuffle of three inputs.
10738 if (EI->getOperand(0) == RHS || RHS == 0) {
10739 RHS = EI->getOperand(0);
10740 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10741 Mask[InsertedIdx & (NumElts-1)] =
10742 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10743 return V;
10744 }
10745
10746 if (VecOp == RHS) {
10747 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10748 // Everything but the extracted element is replaced with the RHS.
10749 for (unsigned i = 0; i != NumElts; ++i) {
10750 if (i != InsertedIdx)
10751 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10752 }
10753 return V;
10754 }
10755
10756 // If this insertelement is a chain that comes from exactly these two
10757 // vectors, return the vector and the effective shuffle.
10758 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10759 return EI->getOperand(0);
10760
10761 }
10762 }
10763 }
10764 // TODO: Handle shufflevector here!
10765
10766 // Otherwise, can't do anything fancy. Return an identity vector.
10767 for (unsigned i = 0; i != NumElts; ++i)
10768 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10769 return V;
10770}
10771
10772Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10773 Value *VecOp = IE.getOperand(0);
10774 Value *ScalarOp = IE.getOperand(1);
10775 Value *IdxOp = IE.getOperand(2);
10776
10777 // Inserting an undef or into an undefined place, remove this.
10778 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10779 ReplaceInstUsesWith(IE, VecOp);
10780
10781 // If the inserted element was extracted from some other vector, and if the
10782 // indexes are constant, try to turn this into a shufflevector operation.
10783 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10784 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10785 EI->getOperand(0)->getType() == IE.getType()) {
10786 unsigned NumVectorElts = IE.getType()->getNumElements();
10787 unsigned ExtractedIdx =
10788 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10789 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10790
10791 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10792 return ReplaceInstUsesWith(IE, VecOp);
10793
10794 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10795 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10796
10797 // If we are extracting a value from a vector, then inserting it right
10798 // back into the same place, just use the input vector.
10799 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10800 return ReplaceInstUsesWith(IE, VecOp);
10801
10802 // We could theoretically do this for ANY input. However, doing so could
10803 // turn chains of insertelement instructions into a chain of shufflevector
10804 // instructions, and right now we do not merge shufflevectors. As such,
10805 // only do this in a situation where it is clear that there is benefit.
10806 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10807 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10808 // the values of VecOp, except then one read from EIOp0.
10809 // Build a new shuffle mask.
10810 std::vector<Constant*> Mask;
10811 if (isa<UndefValue>(VecOp))
10812 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10813 else {
10814 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10815 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10816 NumVectorElts));
10817 }
10818 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10819 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10820 ConstantVector::get(Mask));
10821 }
10822
10823 // If this insertelement isn't used by some other insertelement, turn it
10824 // (and any insertelements it points to), into one big shuffle.
10825 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10826 std::vector<Constant*> Mask;
10827 Value *RHS = 0;
10828 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10829 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10830 // We now have a shuffle of LHS, RHS, Mask.
10831 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10832 }
10833 }
10834 }
10835
10836 return 0;
10837}
10838
10839
10840Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10841 Value *LHS = SVI.getOperand(0);
10842 Value *RHS = SVI.getOperand(1);
10843 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10844
10845 bool MadeChange = false;
10846
10847 // Undefined shuffle mask -> undefined value.
10848 if (isa<UndefValue>(SVI.getOperand(2)))
10849 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10850
10851 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10852 // the undef, change them to undefs.
10853 if (isa<UndefValue>(SVI.getOperand(1))) {
10854 // Scan to see if there are any references to the RHS. If so, replace them
10855 // with undef element refs and set MadeChange to true.
10856 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10857 if (Mask[i] >= e && Mask[i] != 2*e) {
10858 Mask[i] = 2*e;
10859 MadeChange = true;
10860 }
10861 }
10862
10863 if (MadeChange) {
10864 // Remap any references to RHS to use LHS.
10865 std::vector<Constant*> Elts;
10866 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10867 if (Mask[i] == 2*e)
10868 Elts.push_back(UndefValue::get(Type::Int32Ty));
10869 else
10870 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10871 }
10872 SVI.setOperand(2, ConstantVector::get(Elts));
10873 }
10874 }
10875
10876 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10877 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10878 if (LHS == RHS || isa<UndefValue>(LHS)) {
10879 if (isa<UndefValue>(LHS) && LHS == RHS) {
10880 // shuffle(undef,undef,mask) -> undef.
10881 return ReplaceInstUsesWith(SVI, LHS);
10882 }
10883
10884 // Remap any references to RHS to use LHS.
10885 std::vector<Constant*> Elts;
10886 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10887 if (Mask[i] >= 2*e)
10888 Elts.push_back(UndefValue::get(Type::Int32Ty));
10889 else {
10890 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10891 (Mask[i] < e && isa<UndefValue>(LHS)))
10892 Mask[i] = 2*e; // Turn into undef.
10893 else
10894 Mask[i] &= (e-1); // Force to LHS.
10895 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10896 }
10897 }
10898 SVI.setOperand(0, SVI.getOperand(1));
10899 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10900 SVI.setOperand(2, ConstantVector::get(Elts));
10901 LHS = SVI.getOperand(0);
10902 RHS = SVI.getOperand(1);
10903 MadeChange = true;
10904 }
10905
10906 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10907 bool isLHSID = true, isRHSID = true;
10908
10909 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10910 if (Mask[i] >= e*2) continue; // Ignore undef values.
10911 // Is this an identity shuffle of the LHS value?
10912 isLHSID &= (Mask[i] == i);
10913
10914 // Is this an identity shuffle of the RHS value?
10915 isRHSID &= (Mask[i]-e == i);
10916 }
10917
10918 // Eliminate identity shuffles.
10919 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10920 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10921
10922 // If the LHS is a shufflevector itself, see if we can combine it with this
10923 // one without producing an unusual shuffle. Here we are really conservative:
10924 // we are absolutely afraid of producing a shuffle mask not in the input
10925 // program, because the code gen may not be smart enough to turn a merged
10926 // shuffle into two specific shuffles: it may produce worse code. As such,
10927 // we only merge two shuffles if the result is one of the two input shuffle
10928 // masks. In this case, merging the shuffles just removes one instruction,
10929 // which we know is safe. This is good for things like turning:
10930 // (splat(splat)) -> splat.
10931 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10932 if (isa<UndefValue>(RHS)) {
10933 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10934
10935 std::vector<unsigned> NewMask;
10936 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10937 if (Mask[i] >= 2*e)
10938 NewMask.push_back(2*e);
10939 else
10940 NewMask.push_back(LHSMask[Mask[i]]);
10941
10942 // If the result mask is equal to the src shuffle or this shuffle mask, do
10943 // the replacement.
10944 if (NewMask == LHSMask || NewMask == Mask) {
10945 std::vector<Constant*> Elts;
10946 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10947 if (NewMask[i] >= e*2) {
10948 Elts.push_back(UndefValue::get(Type::Int32Ty));
10949 } else {
10950 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10951 }
10952 }
10953 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10954 LHSSVI->getOperand(1),
10955 ConstantVector::get(Elts));
10956 }
10957 }
10958 }
10959
10960 return MadeChange ? &SVI : 0;
10961}
10962
10963
10964
10965
10966/// TryToSinkInstruction - Try to move the specified instruction from its
10967/// current block into the beginning of DestBlock, which can only happen if it's
10968/// safe to move the instruction past all of the instructions between it and the
10969/// end of its block.
10970static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10971 assert(I->hasOneUse() && "Invariants didn't hold!");
10972
10973 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10974 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10975
10976 // Do not sink alloca instructions out of the entry block.
10977 if (isa<AllocaInst>(I) && I->getParent() ==
10978 &DestBlock->getParent()->getEntryBlock())
10979 return false;
10980
10981 // We can only sink load instructions if there is nothing between the load and
10982 // the end of block that could change the value.
10983 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10984 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10985 Scan != E; ++Scan)
10986 if (Scan->mayWriteToMemory())
10987 return false;
10988 }
10989
10990 BasicBlock::iterator InsertPos = DestBlock->begin();
10991 while (isa<PHINode>(InsertPos)) ++InsertPos;
10992
10993 I->moveBefore(InsertPos);
10994 ++NumSunkInst;
10995 return true;
10996}
10997
10998
10999/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11000/// all reachable code to the worklist.
11001///
11002/// This has a couple of tricks to make the code faster and more powerful. In
11003/// particular, we constant fold and DCE instructions as we go, to avoid adding
11004/// them to the worklist (this significantly speeds up instcombine on code where
11005/// many instructions are dead or constant). Additionally, if we find a branch
11006/// whose condition is a known constant, we only visit the reachable successors.
11007///
11008static void AddReachableCodeToWorklist(BasicBlock *BB,
11009 SmallPtrSet<BasicBlock*, 64> &Visited,
11010 InstCombiner &IC,
11011 const TargetData *TD) {
11012 std::vector<BasicBlock*> Worklist;
11013 Worklist.push_back(BB);
11014
11015 while (!Worklist.empty()) {
11016 BB = Worklist.back();
11017 Worklist.pop_back();
11018
11019 // We have now visited this block! If we've already been here, ignore it.
11020 if (!Visited.insert(BB)) continue;
11021
11022 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11023 Instruction *Inst = BBI++;
11024
11025 // DCE instruction if trivially dead.
11026 if (isInstructionTriviallyDead(Inst)) {
11027 ++NumDeadInst;
11028 DOUT << "IC: DCE: " << *Inst;
11029 Inst->eraseFromParent();
11030 continue;
11031 }
11032
11033 // ConstantProp instruction if trivially constant.
11034 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11035 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11036 Inst->replaceAllUsesWith(C);
11037 ++NumConstProp;
11038 Inst->eraseFromParent();
11039 continue;
11040 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011041
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011042 IC.AddToWorkList(Inst);
11043 }
11044
11045 // Recursively visit successors. If this is a branch or switch on a
11046 // constant, only visit the reachable successor.
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011047 if (BB->getUnwindDest())
11048 Worklist.push_back(BB->getUnwindDest());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011049 TerminatorInst *TI = BB->getTerminator();
11050 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11051 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11052 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011053 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11054 if (ReachableBB != BB->getUnwindDest())
11055 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011056 continue;
11057 }
11058 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11059 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11060 // See if this is an explicit destination.
11061 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11062 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011063 BasicBlock *ReachableBB = SI->getSuccessor(i);
11064 if (ReachableBB != BB->getUnwindDest())
11065 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011066 continue;
11067 }
11068
11069 // Otherwise it is the default destination.
11070 Worklist.push_back(SI->getSuccessor(0));
11071 continue;
11072 }
11073 }
11074
11075 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11076 Worklist.push_back(TI->getSuccessor(i));
11077 }
11078}
11079
11080bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11081 bool Changed = false;
11082 TD = &getAnalysis<TargetData>();
11083
11084 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11085 << F.getNameStr() << "\n");
11086
11087 {
11088 // Do a depth-first traversal of the function, populate the worklist with
11089 // the reachable instructions. Ignore blocks that are not reachable. Keep
11090 // track of which blocks we visit.
11091 SmallPtrSet<BasicBlock*, 64> Visited;
11092 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11093
11094 // Do a quick scan over the function. If we find any blocks that are
11095 // unreachable, remove any instructions inside of them. This prevents
11096 // the instcombine code from having to deal with some bad special cases.
11097 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11098 if (!Visited.count(BB)) {
11099 Instruction *Term = BB->getTerminator();
11100 while (Term != BB->begin()) { // Remove instrs bottom-up
11101 BasicBlock::iterator I = Term; --I;
11102
11103 DOUT << "IC: DCE: " << *I;
11104 ++NumDeadInst;
11105
11106 if (!I->use_empty())
11107 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11108 I->eraseFromParent();
11109 }
11110 }
11111 }
11112
11113 while (!Worklist.empty()) {
11114 Instruction *I = RemoveOneFromWorkList();
11115 if (I == 0) continue; // skip null values.
11116
11117 // Check to see if we can DCE the instruction.
11118 if (isInstructionTriviallyDead(I)) {
11119 // Add operands to the worklist.
11120 if (I->getNumOperands() < 4)
11121 AddUsesToWorkList(*I);
11122 ++NumDeadInst;
11123
11124 DOUT << "IC: DCE: " << *I;
11125
11126 I->eraseFromParent();
11127 RemoveFromWorkList(I);
11128 continue;
11129 }
11130
11131 // Instruction isn't dead, see if we can constant propagate it.
11132 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11133 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11134
11135 // Add operands to the worklist.
11136 AddUsesToWorkList(*I);
11137 ReplaceInstUsesWith(*I, C);
11138
11139 ++NumConstProp;
11140 I->eraseFromParent();
11141 RemoveFromWorkList(I);
11142 continue;
11143 }
11144
11145 // See if we can trivially sink this instruction to a successor basic block.
11146 if (I->hasOneUse()) {
11147 BasicBlock *BB = I->getParent();
11148 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11149 if (UserParent != BB) {
11150 bool UserIsSuccessor = false;
11151 // See if the user is one of our successors.
11152 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11153 if (*SI == UserParent) {
11154 UserIsSuccessor = true;
11155 break;
11156 }
11157
11158 // If the user is one of our immediate successors, and if that successor
11159 // only has us as a predecessors (we'd have to split the critical edge
11160 // otherwise), we can keep going.
11161 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11162 next(pred_begin(UserParent)) == pred_end(UserParent))
11163 // Okay, the CFG is simple enough, try to sink this instruction.
11164 Changed |= TryToSinkInstruction(I, UserParent);
11165 }
11166 }
11167
11168 // Now that we have an instruction, try combining it to simplify it...
11169#ifndef NDEBUG
11170 std::string OrigI;
11171#endif
11172 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11173 if (Instruction *Result = visit(*I)) {
11174 ++NumCombined;
11175 // Should we replace the old instruction with a new one?
11176 if (Result != I) {
11177 DOUT << "IC: Old = " << *I
11178 << " New = " << *Result;
11179
11180 // Everything uses the new instruction now.
11181 I->replaceAllUsesWith(Result);
11182
11183 // Push the new instruction and any users onto the worklist.
11184 AddToWorkList(Result);
11185 AddUsersToWorkList(*Result);
11186
11187 // Move the name to the new instruction first.
11188 Result->takeName(I);
11189
11190 // Insert the new instruction into the basic block...
11191 BasicBlock *InstParent = I->getParent();
11192 BasicBlock::iterator InsertPos = I;
11193
11194 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11195 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11196 ++InsertPos;
11197
11198 InstParent->getInstList().insert(InsertPos, Result);
11199
11200 // Make sure that we reprocess all operands now that we reduced their
11201 // use counts.
11202 AddUsesToWorkList(*I);
11203
11204 // Instructions can end up on the worklist more than once. Make sure
11205 // we do not process an instruction that has been deleted.
11206 RemoveFromWorkList(I);
11207
11208 // Erase the old instruction.
11209 InstParent->getInstList().erase(I);
11210 } else {
11211#ifndef NDEBUG
11212 DOUT << "IC: Mod = " << OrigI
11213 << " New = " << *I;
11214#endif
11215
11216 // If the instruction was modified, it's possible that it is now dead.
11217 // if so, remove it.
11218 if (isInstructionTriviallyDead(I)) {
11219 // Make sure we process all operands now that we are reducing their
11220 // use counts.
11221 AddUsesToWorkList(*I);
11222
11223 // Instructions may end up in the worklist more than once. Erase all
11224 // occurrences of this instruction.
11225 RemoveFromWorkList(I);
11226 I->eraseFromParent();
11227 } else {
11228 AddToWorkList(I);
11229 AddUsersToWorkList(*I);
11230 }
11231 }
11232 Changed = true;
11233 }
11234 }
11235
11236 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011237
11238 // Do an explicit clear, this shrinks the map if needed.
11239 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011240 return Changed;
11241}
11242
11243
11244bool InstCombiner::runOnFunction(Function &F) {
11245 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11246
11247 bool EverMadeChange = false;
11248
11249 // Iterate while there is work to do.
11250 unsigned Iteration = 0;
11251 while (DoOneIteration(F, Iteration++))
11252 EverMadeChange = true;
11253 return EverMadeChange;
11254}
11255
11256FunctionPass *llvm::createInstructionCombiningPass() {
11257 return new InstCombiner();
11258}
11259