blob: 9b423a40db1109cfb61cff385652376c925a3719 [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);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 public:
241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
249 AddToWorkList(New);
250 return New;
251 }
252
253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
258 if (V->getType() == Ty) return V;
259
260 if (Constant *CV = dyn_cast<Constant>(V))
261 return ConstantExpr::getCast(opc, CV, Ty);
262
263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264 AddToWorkList(C);
265 return C;
266 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272
273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
280 AddUsersToWorkList(I); // Add all modified instrs to worklist
281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
288 return &I;
289 }
290 }
291
292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
303 AddToWorkList(I);
304 if (Instruction *I = dyn_cast<Instruction>(New))
305 AddToWorkList(I);
306 return true;
307 }
308
309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
316 RemoveFromWorkList(&I);
317 I.eraseFromParent();
318 return 0; // Don't do anything with FI
319 }
320
321 private:
322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
328 Instruction *InsertBefore);
329
330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
332 bool SimplifyCommutative(BinaryOperator &I);
333
334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
361
362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
363 bool isSub, Instruction &I);
364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
365 bool isSigned, bool Inside, Instruction &IB);
366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
367 Instruction *MatchBSwap(BinaryOperator &I);
368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
373 };
374
375 char InstCombiner::ID = 0;
376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
377}
378
379// getComplexity: Assign a complexity or rank value to LLVM Values...
380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
384 return 3;
385 return 4;
386 }
387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
389}
390
391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
394 return V->hasOneUse() || isa<Constant>(V);
395}
396
397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
403 }
404 return Ty;
405}
406
407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
413 if (CE->getOpcode() == Instruction::BitCast)
414 return CE->getOperand(0);
415 return 0;
416}
417
418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
430
431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
434
435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
447 // If this is another cast that can be eliminated, it isn't codegen either.
448 if (const CastInst *CI = dyn_cast<CastInst>(V))
449 if (isEliminableCastPair(CI, opcode, Ty, TD))
450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
463 return ConstantExpr::getCast(opcode, C, DestTy);
464
465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
466}
467
468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
470//
471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
477//
478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
482
483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
505 AddToWorkList(New);
506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
509 }
510 }
511 return Changed;
512}
513
514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
527//
528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
530 return BinaryOperator::getNegArgument(V);
531
532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
535 return 0;
536}
537
538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
540 return BinaryOperator::getNotArgument(V);
541
542 // Constants can be considered to be not'ed values...
543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
544 return ConstantInt::get(~C->getValue());
545 return 0;
546}
547
548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
552//
553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
554 if (V->hasOneUse() && V->getType()->isInteger())
555 if (Instruction *I = dyn_cast<Instruction>(V)) {
556 if (I->getOpcode() == Instruction::Mul)
557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
558 return I->getOperand(0);
559 if (I->getOpcode() == Instruction::Shl)
560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
561 // The multiplier is really 1 << CST.
562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
565 return I->getOperand(0);
566 }
567 }
568 return 0;
569}
570
571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
581/// AddOne - Add one to a ConstantInt
582static ConstantInt *AddOne(ConstantInt *C) {
583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
585}
586/// SubOne - Subtract one from a ConstantInt
587static ConstantInt *SubOne(ConstantInt *C) {
588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
606}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000607/// MultiplyOverflows - True if the multiply can not be expressed in an int
608/// this size.
609static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
610 uint32_t W = C1->getBitWidth();
611 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
612 if (sign) {
613 LHSExt.sext(W * 2);
614 RHSExt.sext(W * 2);
615 } else {
616 LHSExt.zext(W * 2);
617 RHSExt.zext(W * 2);
618 }
619
620 APInt MulExt = LHSExt * RHSExt;
621
622 if (sign) {
623 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
624 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
625 return MulExt.slt(Min) || MulExt.sgt(Max);
626 } else
627 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
628}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629
630/// ComputeMaskedBits - Determine which of the bits specified in Mask are
631/// known to be either zero or one and return them in the KnownZero/KnownOne
632/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
633/// processing.
634/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
635/// we cannot optimize based on the assumption that it is zero without changing
636/// it to be an explicit zero. If we don't change it to zero, other code could
637/// optimized based on the contradictory assumption that it is non-zero.
638/// Because instcombine aggressively folds operations with undef args anyway,
639/// this won't lose us code quality.
640static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
641 APInt& KnownOne, unsigned Depth = 0) {
642 assert(V && "No Value?");
643 assert(Depth <= 6 && "Limit Search Depth");
644 uint32_t BitWidth = Mask.getBitWidth();
645 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
646 KnownZero.getBitWidth() == BitWidth &&
647 KnownOne.getBitWidth() == BitWidth &&
648 "V, Mask, KnownOne and KnownZero should have same BitWidth");
649 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650 // We know all of the bits for a constant!
651 KnownOne = CI->getValue() & Mask;
652 KnownZero = ~KnownOne & Mask;
653 return;
654 }
655
656 if (Depth == 6 || Mask == 0)
657 return; // Limit search depth.
658
659 Instruction *I = dyn_cast<Instruction>(V);
660 if (!I) return;
661
662 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
663 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
664
665 switch (I->getOpcode()) {
666 case Instruction::And: {
667 // If either the LHS or the RHS are Zero, the result is zero.
668 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
669 APInt Mask2(Mask & ~KnownZero);
670 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Output known-1 bits are only known if set in both the LHS & RHS.
675 KnownOne &= KnownOne2;
676 // Output known-0 are known to be clear if zero in either the LHS | RHS.
677 KnownZero |= KnownZero2;
678 return;
679 }
680 case Instruction::Or: {
681 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
682 APInt Mask2(Mask & ~KnownOne);
683 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
686
687 // Output known-0 bits are only known if clear in both the LHS & RHS.
688 KnownZero &= KnownZero2;
689 // Output known-1 are known to be set if set in either the LHS | RHS.
690 KnownOne |= KnownOne2;
691 return;
692 }
693 case Instruction::Xor: {
694 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
698
699 // Output known-0 bits are known if clear or set in both the LHS & RHS.
700 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
701 // Output known-1 are known to be set if set in only one of the LHS, RHS.
702 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
703 KnownZero = KnownZeroOut;
704 return;
705 }
706 case Instruction::Select:
707 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
708 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
710 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
711
712 // Only known if known in both the LHS and RHS.
713 KnownOne &= KnownOne2;
714 KnownZero &= KnownZero2;
715 return;
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::FPToUI:
719 case Instruction::FPToSI:
720 case Instruction::SIToFP:
721 case Instruction::PtrToInt:
722 case Instruction::UIToFP:
723 case Instruction::IntToPtr:
724 return; // Can't work with floating point or pointers
725 case Instruction::Trunc: {
726 // All these have integer operands
727 uint32_t SrcBitWidth =
728 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
729 APInt MaskIn(Mask);
730 MaskIn.zext(SrcBitWidth);
731 KnownZero.zext(SrcBitWidth);
732 KnownOne.zext(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
734 KnownZero.trunc(BitWidth);
735 KnownOne.trunc(BitWidth);
736 return;
737 }
738 case Instruction::BitCast: {
739 const Type *SrcTy = I->getOperand(0)->getType();
740 if (SrcTy->isInteger()) {
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
742 return;
743 }
744 break;
745 }
746 case Instruction::ZExt: {
747 // Compute the bits in the result that are not present in the input.
748 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
749 uint32_t SrcBitWidth = SrcTy->getBitWidth();
750
751 APInt MaskIn(Mask);
752 MaskIn.trunc(SrcBitWidth);
753 KnownZero.trunc(SrcBitWidth);
754 KnownOne.trunc(SrcBitWidth);
755 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 // The top bits are known to be zero.
758 KnownZero.zext(BitWidth);
759 KnownOne.zext(BitWidth);
760 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
761 return;
762 }
763 case Instruction::SExt: {
764 // Compute the bits in the result that are not present in the input.
765 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
766 uint32_t SrcBitWidth = SrcTy->getBitWidth();
767
768 APInt MaskIn(Mask);
769 MaskIn.trunc(SrcBitWidth);
770 KnownZero.trunc(SrcBitWidth);
771 KnownOne.trunc(SrcBitWidth);
772 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
774 KnownZero.zext(BitWidth);
775 KnownOne.zext(BitWidth);
776
777 // If the sign bit of the input is known set or clear, then we know the
778 // top bits of the result.
779 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
780 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
781 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
782 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
783 return;
784 }
785 case Instruction::Shl:
786 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
787 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
788 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
789 APInt Mask2(Mask.lshr(ShiftAmt));
790 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
792 KnownZero <<= ShiftAmt;
793 KnownOne <<= ShiftAmt;
794 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
795 return;
796 }
797 break;
798 case Instruction::LShr:
799 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
800 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
801 // Compute the new bits that are at the top now.
802 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
803
804 // Unsigned shift right.
805 APInt Mask2(Mask.shl(ShiftAmt));
806 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
807 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
808 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
809 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
810 // high bits known zero.
811 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
812 return;
813 }
814 break;
815 case Instruction::AShr:
816 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
817 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
818 // Compute the new bits that are at the top now.
819 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
820
821 // Signed shift right.
822 APInt Mask2(Mask.shl(ShiftAmt));
823 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
824 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
825 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
826 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
827
828 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
829 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
830 KnownZero |= HighBits;
831 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
832 KnownOne |= HighBits;
833 return;
834 }
835 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000836 case Instruction::SRem:
837 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
838 APInt RA = Rem->getValue();
839 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
840 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
841 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
842 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
843
844 // The sign of a remainder is equal to the sign of the first
845 // operand (zero being positive).
846 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
847 KnownZero2 |= ~LowBits;
848 else if (KnownOne2[BitWidth-1])
849 KnownOne2 |= ~LowBits;
850
851 KnownZero |= KnownZero2 & Mask;
852 KnownOne |= KnownOne2 & Mask;
853
854 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
855 }
856 }
857 break;
858 case Instruction::URem:
859 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
860 APInt RA = Rem->getValue();
861 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
862 APInt LowBits = (RA - 1) | RA;
863 APInt Mask2 = LowBits & Mask;
864 KnownZero |= ~LowBits & Mask;
865 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
866 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
867 }
868 } else {
869 // Since the result is less than or equal to RHS, any leading zero bits
870 // in RHS must also exist in the result.
871 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
872 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2, Depth+1);
873
874 uint32_t Leaders = KnownZero2.countLeadingOnes();
875 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
876 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
877 }
878 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879 }
880}
881
882/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
883/// this predicate to simplify operations downstream. Mask is known to be zero
884/// for bits that V cannot have.
885static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
886 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
887 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
888 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
889 return (KnownZero & Mask) == Mask;
890}
891
892/// ShrinkDemandedConstant - Check to see if the specified operand of the
893/// specified instruction is a constant integer. If so, check to see if there
894/// are any bits set in the constant that are not demanded. If so, shrink the
895/// constant and return true.
896static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
897 APInt Demanded) {
898 assert(I && "No instruction?");
899 assert(OpNo < I->getNumOperands() && "Operand index too large");
900
901 // If the operand is not a constant integer, nothing to do.
902 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
903 if (!OpC) return false;
904
905 // If there are no bits set that aren't demanded, nothing to do.
906 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
907 if ((~Demanded & OpC->getValue()) == 0)
908 return false;
909
910 // This instruction is producing bits that are not demanded. Shrink the RHS.
911 Demanded &= OpC->getValue();
912 I->setOperand(OpNo, ConstantInt::get(Demanded));
913 return true;
914}
915
916// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
917// set of known zero and one bits, compute the maximum and minimum values that
918// could have the specified known zero and known one bits, returning them in
919// min/max.
920static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
921 const APInt& KnownZero,
922 const APInt& KnownOne,
923 APInt& Min, APInt& Max) {
924 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
925 assert(KnownZero.getBitWidth() == BitWidth &&
926 KnownOne.getBitWidth() == BitWidth &&
927 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
928 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
929 APInt UnknownBits = ~(KnownZero|KnownOne);
930
931 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
932 // bit if it is unknown.
933 Min = KnownOne;
934 Max = KnownOne|UnknownBits;
935
936 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
937 Min.set(BitWidth-1);
938 Max.clear(BitWidth-1);
939 }
940}
941
942// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
943// a set of known zero and one bits, compute the maximum and minimum values that
944// could have the specified known zero and known one bits, returning them in
945// min/max.
946static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000947 const APInt &KnownZero,
948 const APInt &KnownOne,
949 APInt &Min, APInt &Max) {
950 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 assert(KnownZero.getBitWidth() == BitWidth &&
952 KnownOne.getBitWidth() == BitWidth &&
953 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
954 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
955 APInt UnknownBits = ~(KnownZero|KnownOne);
956
957 // The minimum value is when the unknown bits are all zeros.
958 Min = KnownOne;
959 // The maximum value is when the unknown bits are all ones.
960 Max = KnownOne|UnknownBits;
961}
962
963/// SimplifyDemandedBits - This function attempts to replace V with a simpler
964/// value based on the demanded bits. When this function is called, it is known
965/// that only the bits set in DemandedMask of the result of V are ever used
966/// downstream. Consequently, depending on the mask and V, it may be possible
967/// to replace V with a constant or one of its operands. In such cases, this
968/// function does the replacement and returns true. In all other cases, it
969/// returns false after analyzing the expression and setting KnownOne and known
970/// to be one in the expression. KnownZero contains all the bits that are known
971/// to be zero in the expression. These are provided to potentially allow the
972/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
973/// the expression. KnownOne and KnownZero always follow the invariant that
974/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
975/// the bits in KnownOne and KnownZero may only be accurate for those bits set
976/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
977/// and KnownOne must all be the same.
978bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
979 APInt& KnownZero, APInt& KnownOne,
980 unsigned Depth) {
981 assert(V != 0 && "Null pointer of Value???");
982 assert(Depth <= 6 && "Limit Search Depth");
983 uint32_t BitWidth = DemandedMask.getBitWidth();
984 const IntegerType *VTy = cast<IntegerType>(V->getType());
985 assert(VTy->getBitWidth() == BitWidth &&
986 KnownZero.getBitWidth() == BitWidth &&
987 KnownOne.getBitWidth() == BitWidth &&
988 "Value *V, DemandedMask, KnownZero and KnownOne \
989 must have same BitWidth");
990 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
991 // We know all of the bits for a constant!
992 KnownOne = CI->getValue() & DemandedMask;
993 KnownZero = ~KnownOne & DemandedMask;
994 return false;
995 }
996
997 KnownZero.clear();
998 KnownOne.clear();
999 if (!V->hasOneUse()) { // Other users may use these bits.
1000 if (Depth != 0) { // Not at the root.
1001 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1002 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1003 return false;
1004 }
1005 // If this is the root being simplified, allow it to have multiple uses,
1006 // just set the DemandedMask to all bits.
1007 DemandedMask = APInt::getAllOnesValue(BitWidth);
1008 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1009 if (V != UndefValue::get(VTy))
1010 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1011 return false;
1012 } else if (Depth == 6) { // Limit search depth.
1013 return false;
1014 }
1015
1016 Instruction *I = dyn_cast<Instruction>(V);
1017 if (!I) return false; // Only analyze instructions.
1018
1019 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1020 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1021 switch (I->getOpcode()) {
1022 default: break;
1023 case Instruction::And:
1024 // If either the LHS or the RHS are Zero, the result is zero.
1025 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1026 RHSKnownZero, RHSKnownOne, Depth+1))
1027 return true;
1028 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1029 "Bits known to be one AND zero?");
1030
1031 // If something is known zero on the RHS, the bits aren't demanded on the
1032 // LHS.
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1034 LHSKnownZero, LHSKnownOne, Depth+1))
1035 return true;
1036 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1037 "Bits known to be one AND zero?");
1038
1039 // If all of the demanded bits are known 1 on one side, return the other.
1040 // These bits cannot contribute to the result of the 'and'.
1041 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1042 (DemandedMask & ~LHSKnownZero))
1043 return UpdateValueUsesWith(I, I->getOperand(0));
1044 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1045 (DemandedMask & ~RHSKnownZero))
1046 return UpdateValueUsesWith(I, I->getOperand(1));
1047
1048 // If all of the demanded bits in the inputs are known zeros, return zero.
1049 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1050 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1051
1052 // If the RHS is a constant, see if we can simplify it.
1053 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1054 return UpdateValueUsesWith(I, I);
1055
1056 // Output known-1 bits are only known if set in both the LHS & RHS.
1057 RHSKnownOne &= LHSKnownOne;
1058 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1059 RHSKnownZero |= LHSKnownZero;
1060 break;
1061 case Instruction::Or:
1062 // If either the LHS or the RHS are One, the result is One.
1063 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1))
1065 return true;
1066 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1067 "Bits known to be one AND zero?");
1068 // If something is known one on the RHS, the bits aren't demanded on the
1069 // LHS.
1070 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1071 LHSKnownZero, LHSKnownOne, Depth+1))
1072 return true;
1073 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1074 "Bits known to be one AND zero?");
1075
1076 // If all of the demanded bits are known zero on one side, return the other.
1077 // These bits cannot contribute to the result of the 'or'.
1078 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1079 (DemandedMask & ~LHSKnownOne))
1080 return UpdateValueUsesWith(I, I->getOperand(0));
1081 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1082 (DemandedMask & ~RHSKnownOne))
1083 return UpdateValueUsesWith(I, I->getOperand(1));
1084
1085 // If all of the potentially set bits on one side are known to be set on
1086 // the other side, just use the 'other' side.
1087 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1088 (DemandedMask & (~RHSKnownZero)))
1089 return UpdateValueUsesWith(I, I->getOperand(0));
1090 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1091 (DemandedMask & (~LHSKnownZero)))
1092 return UpdateValueUsesWith(I, I->getOperand(1));
1093
1094 // If the RHS is a constant, see if we can simplify it.
1095 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1096 return UpdateValueUsesWith(I, I);
1097
1098 // Output known-0 bits are only known if clear in both the LHS & RHS.
1099 RHSKnownZero &= LHSKnownZero;
1100 // Output known-1 are known to be set if set in either the LHS | RHS.
1101 RHSKnownOne |= LHSKnownOne;
1102 break;
1103 case Instruction::Xor: {
1104 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1105 RHSKnownZero, RHSKnownOne, Depth+1))
1106 return true;
1107 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1108 "Bits known to be one AND zero?");
1109 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1110 LHSKnownZero, LHSKnownOne, Depth+1))
1111 return true;
1112 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1113 "Bits known to be one AND zero?");
1114
1115 // If all of the demanded bits are known zero on one side, return the other.
1116 // These bits cannot contribute to the result of the 'xor'.
1117 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1118 return UpdateValueUsesWith(I, I->getOperand(0));
1119 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1120 return UpdateValueUsesWith(I, I->getOperand(1));
1121
1122 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1123 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1124 (RHSKnownOne & LHSKnownOne);
1125 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1126 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1127 (RHSKnownOne & LHSKnownZero);
1128
1129 // If all of the demanded bits are known to be zero on one side or the
1130 // other, turn this into an *inclusive* or.
1131 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1132 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1133 Instruction *Or =
1134 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1135 I->getName());
1136 InsertNewInstBefore(Or, *I);
1137 return UpdateValueUsesWith(I, Or);
1138 }
1139
1140 // If all of the demanded bits on one side are known, and all of the set
1141 // bits on that side are also known to be set on the other side, turn this
1142 // into an AND, as we know the bits will be cleared.
1143 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1144 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1145 // all known
1146 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1147 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1148 Instruction *And =
1149 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1150 InsertNewInstBefore(And, *I);
1151 return UpdateValueUsesWith(I, And);
1152 }
1153 }
1154
1155 // If the RHS is a constant, see if we can simplify it.
1156 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1157 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1158 return UpdateValueUsesWith(I, I);
1159
1160 RHSKnownZero = KnownZeroOut;
1161 RHSKnownOne = KnownOneOut;
1162 break;
1163 }
1164 case Instruction::Select:
1165 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1166 RHSKnownZero, RHSKnownOne, Depth+1))
1167 return true;
1168 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1169 LHSKnownZero, LHSKnownOne, Depth+1))
1170 return true;
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1174 "Bits known to be one AND zero?");
1175
1176 // If the operands are constants, see if we can simplify them.
1177 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1178 return UpdateValueUsesWith(I, I);
1179 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1180 return UpdateValueUsesWith(I, I);
1181
1182 // Only known if known in both the LHS and RHS.
1183 RHSKnownOne &= LHSKnownOne;
1184 RHSKnownZero &= LHSKnownZero;
1185 break;
1186 case Instruction::Trunc: {
1187 uint32_t truncBf =
1188 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1189 DemandedMask.zext(truncBf);
1190 RHSKnownZero.zext(truncBf);
1191 RHSKnownOne.zext(truncBf);
1192 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1193 RHSKnownZero, RHSKnownOne, Depth+1))
1194 return true;
1195 DemandedMask.trunc(BitWidth);
1196 RHSKnownZero.trunc(BitWidth);
1197 RHSKnownOne.trunc(BitWidth);
1198 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1199 "Bits known to be one AND zero?");
1200 break;
1201 }
1202 case Instruction::BitCast:
1203 if (!I->getOperand(0)->getType()->isInteger())
1204 return false;
1205
1206 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1207 RHSKnownZero, RHSKnownOne, Depth+1))
1208 return true;
1209 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1210 "Bits known to be one AND zero?");
1211 break;
1212 case Instruction::ZExt: {
1213 // Compute the bits in the result that are not present in the input.
1214 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1215 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1216
1217 DemandedMask.trunc(SrcBitWidth);
1218 RHSKnownZero.trunc(SrcBitWidth);
1219 RHSKnownOne.trunc(SrcBitWidth);
1220 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1221 RHSKnownZero, RHSKnownOne, Depth+1))
1222 return true;
1223 DemandedMask.zext(BitWidth);
1224 RHSKnownZero.zext(BitWidth);
1225 RHSKnownOne.zext(BitWidth);
1226 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1227 "Bits known to be one AND zero?");
1228 // The top bits are known to be zero.
1229 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1230 break;
1231 }
1232 case Instruction::SExt: {
1233 // Compute the bits in the result that are not present in the input.
1234 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1235 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1236
1237 APInt InputDemandedBits = DemandedMask &
1238 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1239
1240 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1241 // If any of the sign extended bits are demanded, we know that the sign
1242 // bit is demanded.
1243 if ((NewBits & DemandedMask) != 0)
1244 InputDemandedBits.set(SrcBitWidth-1);
1245
1246 InputDemandedBits.trunc(SrcBitWidth);
1247 RHSKnownZero.trunc(SrcBitWidth);
1248 RHSKnownOne.trunc(SrcBitWidth);
1249 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1250 RHSKnownZero, RHSKnownOne, Depth+1))
1251 return true;
1252 InputDemandedBits.zext(BitWidth);
1253 RHSKnownZero.zext(BitWidth);
1254 RHSKnownOne.zext(BitWidth);
1255 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1256 "Bits known to be one AND zero?");
1257
1258 // If the sign bit of the input is known set or clear, then we know the
1259 // top bits of the result.
1260
1261 // If the input sign bit is known zero, or if the NewBits are not demanded
1262 // convert this into a zero extension.
1263 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1264 {
1265 // Convert to ZExt cast
1266 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1267 return UpdateValueUsesWith(I, NewCast);
1268 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1269 RHSKnownOne |= NewBits;
1270 }
1271 break;
1272 }
1273 case Instruction::Add: {
1274 // Figure out what the input bits are. If the top bits of the and result
1275 // are not demanded, then the add doesn't demand them from its input
1276 // either.
1277 uint32_t NLZ = DemandedMask.countLeadingZeros();
1278
1279 // If there is a constant on the RHS, there are a variety of xformations
1280 // we can do.
1281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1282 // If null, this should be simplified elsewhere. Some of the xforms here
1283 // won't work if the RHS is zero.
1284 if (RHS->isZero())
1285 break;
1286
1287 // If the top bit of the output is demanded, demand everything from the
1288 // input. Otherwise, we demand all the input bits except NLZ top bits.
1289 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1290
1291 // Find information about known zero/one bits in the input.
1292 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1293 LHSKnownZero, LHSKnownOne, Depth+1))
1294 return true;
1295
1296 // If the RHS of the add has bits set that can't affect the input, reduce
1297 // the constant.
1298 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1299 return UpdateValueUsesWith(I, I);
1300
1301 // Avoid excess work.
1302 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1303 break;
1304
1305 // Turn it into OR if input bits are zero.
1306 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1307 Instruction *Or =
1308 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1309 I->getName());
1310 InsertNewInstBefore(Or, *I);
1311 return UpdateValueUsesWith(I, Or);
1312 }
1313
1314 // We can say something about the output known-zero and known-one bits,
1315 // depending on potential carries from the input constant and the
1316 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1317 // bits set and the RHS constant is 0x01001, then we know we have a known
1318 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1319
1320 // To compute this, we first compute the potential carry bits. These are
1321 // the bits which may be modified. I'm not aware of a better way to do
1322 // this scan.
1323 const APInt& RHSVal = RHS->getValue();
1324 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1325
1326 // Now that we know which bits have carries, compute the known-1/0 sets.
1327
1328 // Bits are known one if they are known zero in one operand and one in the
1329 // other, and there is no input carry.
1330 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1331 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1332
1333 // Bits are known zero if they are known zero in both operands and there
1334 // is no input carry.
1335 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1336 } else {
1337 // If the high-bits of this ADD are not demanded, then it does not demand
1338 // the high bits of its LHS or RHS.
1339 if (DemandedMask[BitWidth-1] == 0) {
1340 // Right fill the mask of bits for this ADD to demand the most
1341 // significant bit and all those below it.
1342 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1343 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1344 LHSKnownZero, LHSKnownOne, Depth+1))
1345 return true;
1346 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1347 LHSKnownZero, LHSKnownOne, Depth+1))
1348 return true;
1349 }
1350 }
1351 break;
1352 }
1353 case Instruction::Sub:
1354 // If the high-bits of this SUB are not demanded, then it does not demand
1355 // the high bits of its LHS or RHS.
1356 if (DemandedMask[BitWidth-1] == 0) {
1357 // Right fill the mask of bits for this SUB to demand the most
1358 // significant bit and all those below it.
1359 uint32_t NLZ = DemandedMask.countLeadingZeros();
1360 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1361 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1362 LHSKnownZero, LHSKnownOne, Depth+1))
1363 return true;
1364 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1365 LHSKnownZero, LHSKnownOne, Depth+1))
1366 return true;
1367 }
1368 break;
1369 case Instruction::Shl:
1370 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1371 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1372 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1373 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1374 RHSKnownZero, RHSKnownOne, Depth+1))
1375 return true;
1376 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1377 "Bits known to be one AND zero?");
1378 RHSKnownZero <<= ShiftAmt;
1379 RHSKnownOne <<= ShiftAmt;
1380 // low bits known zero.
1381 if (ShiftAmt)
1382 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1383 }
1384 break;
1385 case Instruction::LShr:
1386 // For a logical shift right
1387 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1388 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1389
1390 // Unsigned shift right.
1391 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1392 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1393 RHSKnownZero, RHSKnownOne, Depth+1))
1394 return true;
1395 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1396 "Bits known to be one AND zero?");
1397 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1398 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1399 if (ShiftAmt) {
1400 // Compute the new bits that are at the top now.
1401 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1402 RHSKnownZero |= HighBits; // high bits known zero.
1403 }
1404 }
1405 break;
1406 case Instruction::AShr:
1407 // If this is an arithmetic shift right and only the low-bit is set, we can
1408 // always convert this into a logical shr, even if the shift amount is
1409 // variable. The low bit of the shift cannot be an input sign bit unless
1410 // the shift amount is >= the size of the datatype, which is undefined.
1411 if (DemandedMask == 1) {
1412 // Perform the logical shift right.
1413 Value *NewVal = BinaryOperator::createLShr(
1414 I->getOperand(0), I->getOperand(1), I->getName());
1415 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1416 return UpdateValueUsesWith(I, NewVal);
1417 }
1418
1419 // If the sign bit is the only bit demanded by this ashr, then there is no
1420 // need to do it, the shift doesn't change the high bit.
1421 if (DemandedMask.isSignBit())
1422 return UpdateValueUsesWith(I, I->getOperand(0));
1423
1424 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1425 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1426
1427 // Signed shift right.
1428 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1429 // If any of the "high bits" are demanded, we should set the sign bit as
1430 // demanded.
1431 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1432 DemandedMaskIn.set(BitWidth-1);
1433 if (SimplifyDemandedBits(I->getOperand(0),
1434 DemandedMaskIn,
1435 RHSKnownZero, RHSKnownOne, Depth+1))
1436 return true;
1437 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1438 "Bits known to be one AND zero?");
1439 // Compute the new bits that are at the top now.
1440 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1441 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1442 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1443
1444 // Handle the sign bits.
1445 APInt SignBit(APInt::getSignBit(BitWidth));
1446 // Adjust to where it is now in the mask.
1447 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1448
1449 // If the input sign bit is known to be zero, or if none of the top bits
1450 // are demanded, turn this into an unsigned shift right.
1451 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1452 (HighBits & ~DemandedMask) == HighBits) {
1453 // Perform the logical shift right.
1454 Value *NewVal = BinaryOperator::createLShr(
1455 I->getOperand(0), SA, I->getName());
1456 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1457 return UpdateValueUsesWith(I, NewVal);
1458 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1459 RHSKnownOne |= HighBits;
1460 }
1461 }
1462 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001463 case Instruction::SRem:
1464 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1465 APInt RA = Rem->getValue();
1466 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1467 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1468 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1469 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1470 LHSKnownZero, LHSKnownOne, Depth+1))
1471 return true;
1472
1473 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1474 LHSKnownZero |= ~LowBits;
1475 else if (LHSKnownOne[BitWidth-1])
1476 LHSKnownOne |= ~LowBits;
1477
1478 KnownZero |= LHSKnownZero & DemandedMask;
1479 KnownOne |= LHSKnownOne & DemandedMask;
1480
1481 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1482 }
1483 }
1484 break;
1485 case Instruction::URem:
1486 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1487 APInt RA = Rem->getValue();
1488 if (RA.isPowerOf2()) {
1489 APInt LowBits = (RA - 1) | RA;
1490 APInt Mask2 = LowBits & DemandedMask;
1491 KnownZero |= ~LowBits & DemandedMask;
1492 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1493 KnownZero, KnownOne, Depth+1))
1494 return true;
1495
1496 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1497 }
1498 } else {
1499 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1500 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1501 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1502 KnownZero2, KnownOne2, Depth+1))
1503 return true;
1504
1505 uint32_t Leaders = KnownZero2.countLeadingOnes();
1506 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1507 }
1508 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 }
1510
1511 // If the client is only demanding bits that we know, return the known
1512 // constant.
1513 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1514 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1515 return false;
1516}
1517
1518
1519/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1520/// 64 or fewer elements. DemandedElts contains the set of elements that are
1521/// actually used by the caller. This method analyzes which elements of the
1522/// operand are undef and returns that information in UndefElts.
1523///
1524/// If the information about demanded elements can be used to simplify the
1525/// operation, the operation is simplified, then the resultant value is
1526/// returned. This returns null if no change was made.
1527Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1528 uint64_t &UndefElts,
1529 unsigned Depth) {
1530 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1531 assert(VWidth <= 64 && "Vector too wide to analyze!");
1532 uint64_t EltMask = ~0ULL >> (64-VWidth);
1533 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1534 "Invalid DemandedElts!");
1535
1536 if (isa<UndefValue>(V)) {
1537 // If the entire vector is undefined, just return this info.
1538 UndefElts = EltMask;
1539 return 0;
1540 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1541 UndefElts = EltMask;
1542 return UndefValue::get(V->getType());
1543 }
1544
1545 UndefElts = 0;
1546 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1547 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1548 Constant *Undef = UndefValue::get(EltTy);
1549
1550 std::vector<Constant*> Elts;
1551 for (unsigned i = 0; i != VWidth; ++i)
1552 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1553 Elts.push_back(Undef);
1554 UndefElts |= (1ULL << i);
1555 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1556 Elts.push_back(Undef);
1557 UndefElts |= (1ULL << i);
1558 } else { // Otherwise, defined.
1559 Elts.push_back(CP->getOperand(i));
1560 }
1561
1562 // If we changed the constant, return it.
1563 Constant *NewCP = ConstantVector::get(Elts);
1564 return NewCP != CP ? NewCP : 0;
1565 } else if (isa<ConstantAggregateZero>(V)) {
1566 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1567 // set to undef.
1568 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1569 Constant *Zero = Constant::getNullValue(EltTy);
1570 Constant *Undef = UndefValue::get(EltTy);
1571 std::vector<Constant*> Elts;
1572 for (unsigned i = 0; i != VWidth; ++i)
1573 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1574 UndefElts = DemandedElts ^ EltMask;
1575 return ConstantVector::get(Elts);
1576 }
1577
1578 if (!V->hasOneUse()) { // Other users may use these bits.
1579 if (Depth != 0) { // Not at the root.
1580 // TODO: Just compute the UndefElts information recursively.
1581 return false;
1582 }
1583 return false;
1584 } else if (Depth == 10) { // Limit search depth.
1585 return false;
1586 }
1587
1588 Instruction *I = dyn_cast<Instruction>(V);
1589 if (!I) return false; // Only analyze instructions.
1590
1591 bool MadeChange = false;
1592 uint64_t UndefElts2;
1593 Value *TmpV;
1594 switch (I->getOpcode()) {
1595 default: break;
1596
1597 case Instruction::InsertElement: {
1598 // If this is a variable index, we don't know which element it overwrites.
1599 // demand exactly the same input as we produce.
1600 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1601 if (Idx == 0) {
1602 // Note that we can't propagate undef elt info, because we don't know
1603 // which elt is getting updated.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts2, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 break;
1608 }
1609
1610 // If this is inserting an element that isn't demanded, remove this
1611 // insertelement.
1612 unsigned IdxNo = Idx->getZExtValue();
1613 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1614 return AddSoonDeadInstToWorklist(*I, 0);
1615
1616 // Otherwise, the element inserted overwrites whatever was there, so the
1617 // input demanded set is simpler than the output set.
1618 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1619 DemandedElts & ~(1ULL << IdxNo),
1620 UndefElts, Depth+1);
1621 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1622
1623 // The inserted element is defined.
1624 UndefElts |= 1ULL << IdxNo;
1625 break;
1626 }
1627 case Instruction::BitCast: {
1628 // Vector->vector casts only.
1629 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630 if (!VTy) break;
1631 unsigned InVWidth = VTy->getNumElements();
1632 uint64_t InputDemandedElts = 0;
1633 unsigned Ratio;
1634
1635 if (VWidth == InVWidth) {
1636 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1637 // elements as are demanded of us.
1638 Ratio = 1;
1639 InputDemandedElts = DemandedElts;
1640 } else if (VWidth > InVWidth) {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the result than there are in the source,
1645 // then an input element is live if any of the corresponding output
1646 // elements are live.
1647 Ratio = VWidth/InVWidth;
1648 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1649 if (DemandedElts & (1ULL << OutIdx))
1650 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1651 }
1652 } else {
1653 // Untested so far.
1654 break;
1655
1656 // If there are more elements in the source than there are in the result,
1657 // then an input element is live if the corresponding output element is
1658 // live.
1659 Ratio = InVWidth/VWidth;
1660 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1661 if (DemandedElts & (1ULL << InIdx/Ratio))
1662 InputDemandedElts |= 1ULL << InIdx;
1663 }
1664
1665 // div/rem demand all inputs, because they don't want divide by zero.
1666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667 UndefElts2, Depth+1);
1668 if (TmpV) {
1669 I->setOperand(0, TmpV);
1670 MadeChange = true;
1671 }
1672
1673 UndefElts = UndefElts2;
1674 if (VWidth > InVWidth) {
1675 assert(0 && "Unimp");
1676 // If there are more elements in the result than there are in the source,
1677 // then an output element is undef if the corresponding input element is
1678 // undef.
1679 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1680 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1681 UndefElts |= 1ULL << OutIdx;
1682 } else if (VWidth < InVWidth) {
1683 assert(0 && "Unimp");
1684 // If there are more elements in the source than there are in the result,
1685 // then a result element is undef if all of the corresponding input
1686 // elements are undef.
1687 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1688 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1689 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1690 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1691 }
1692 break;
1693 }
1694 case Instruction::And:
1695 case Instruction::Or:
1696 case Instruction::Xor:
1697 case Instruction::Add:
1698 case Instruction::Sub:
1699 case Instruction::Mul:
1700 // div/rem demand all inputs, because they don't want divide by zero.
1701 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702 UndefElts, Depth+1);
1703 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707
1708 // Output elements are undefined if both are undefined. Consider things
1709 // like undef&0. The result is known zero, not undef.
1710 UndefElts &= UndefElts2;
1711 break;
1712
1713 case Instruction::Call: {
1714 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715 if (!II) break;
1716 switch (II->getIntrinsicID()) {
1717 default: break;
1718
1719 // Binary vector operations that work column-wise. A dest element is a
1720 // function of the corresponding input elements from the two inputs.
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse_min_ss:
1724 case Intrinsic::x86_sse_max_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 case Intrinsic::x86_sse2_min_sd:
1728 case Intrinsic::x86_sse2_max_sd:
1729 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730 UndefElts, Depth+1);
1731 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733 UndefElts2, Depth+1);
1734 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736 // If only the low elt is demanded and this is a scalarizable intrinsic,
1737 // scalarize it now.
1738 if (DemandedElts == 1) {
1739 switch (II->getIntrinsicID()) {
1740 default: break;
1741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse_mul_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
1744 case Intrinsic::x86_sse2_mul_sd:
1745 // TODO: Lower MIN/MAX/ABS/etc
1746 Value *LHS = II->getOperand(1);
1747 Value *RHS = II->getOperand(2);
1748 // Extract the element as scalars.
1749 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1750 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1751
1752 switch (II->getIntrinsicID()) {
1753 default: assert(0 && "Case stmts out of sync!");
1754 case Intrinsic::x86_sse_sub_ss:
1755 case Intrinsic::x86_sse2_sub_sd:
1756 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1757 II->getName()), *II);
1758 break;
1759 case Intrinsic::x86_sse_mul_ss:
1760 case Intrinsic::x86_sse2_mul_sd:
1761 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1762 II->getName()), *II);
1763 break;
1764 }
1765
1766 Instruction *New =
1767 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1768 II->getName());
1769 InsertNewInstBefore(New, *II);
1770 AddSoonDeadInstToWorklist(*II, 0);
1771 return New;
1772 }
1773 }
1774
1775 // Output elements are undefined if both are undefined. Consider things
1776 // like undef&0. The result is known zero, not undef.
1777 UndefElts &= UndefElts2;
1778 break;
1779 }
1780 break;
1781 }
1782 }
1783 return MadeChange ? I : 0;
1784}
1785
Nick Lewycky2de09a92007-09-06 02:40:25 +00001786/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00001788/// @brief Determine if the icmp Predicate is true when both operands are equal
1789static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1791 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1792 pred == ICmpInst::ICMP_SLE;
1793}
1794
Nick Lewycky2de09a92007-09-06 02:40:25 +00001795/// @returns true if the specified compare instruction is
1796/// true when both operands are equal...
1797/// @brief Determine if the ICmpInst returns true when both operands are equal
1798static bool isTrueWhenEqual(ICmpInst &ICI) {
1799 return isTrueWhenEqual(ICI.getPredicate());
1800}
1801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802/// AssociativeOpt - Perform an optimization on an associative operator. This
1803/// function is designed to check a chain of associative operators for a
1804/// potential to apply a certain optimization. Since the optimization may be
1805/// applicable if the expression was reassociated, this checks the chain, then
1806/// reassociates the expression as necessary to expose the optimization
1807/// opportunity. This makes use of a special Functor, which must define
1808/// 'shouldApply' and 'apply' methods.
1809///
1810template<typename Functor>
1811Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1812 unsigned Opcode = Root.getOpcode();
1813 Value *LHS = Root.getOperand(0);
1814
1815 // Quick check, see if the immediate LHS matches...
1816 if (F.shouldApply(LHS))
1817 return F.apply(Root);
1818
1819 // Otherwise, if the LHS is not of the same opcode as the root, return.
1820 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1821 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1822 // Should we apply this transform to the RHS?
1823 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1824
1825 // If not to the RHS, check to see if we should apply to the LHS...
1826 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1827 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1828 ShouldApply = true;
1829 }
1830
1831 // If the functor wants to apply the optimization to the RHS of LHSI,
1832 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1833 if (ShouldApply) {
1834 BasicBlock *BB = Root.getParent();
1835
1836 // Now all of the instructions are in the current basic block, go ahead
1837 // and perform the reassociation.
1838 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1839
1840 // First move the selected RHS to the LHS of the root...
1841 Root.setOperand(0, LHSI->getOperand(1));
1842
1843 // Make what used to be the LHS of the root be the user of the root...
1844 Value *ExtraOperand = TmpLHSI->getOperand(1);
1845 if (&Root == TmpLHSI) {
1846 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1847 return 0;
1848 }
1849 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1850 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1851 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1852 BasicBlock::iterator ARI = &Root; ++ARI;
1853 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1854 ARI = Root;
1855
1856 // Now propagate the ExtraOperand down the chain of instructions until we
1857 // get to LHSI.
1858 while (TmpLHSI != LHSI) {
1859 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1860 // Move the instruction to immediately before the chain we are
1861 // constructing to avoid breaking dominance properties.
1862 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1863 BB->getInstList().insert(ARI, NextLHSI);
1864 ARI = NextLHSI;
1865
1866 Value *NextOp = NextLHSI->getOperand(1);
1867 NextLHSI->setOperand(1, ExtraOperand);
1868 TmpLHSI = NextLHSI;
1869 ExtraOperand = NextOp;
1870 }
1871
1872 // Now that the instructions are reassociated, have the functor perform
1873 // the transformation...
1874 return F.apply(Root);
1875 }
1876
1877 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1878 }
1879 return 0;
1880}
1881
1882
1883// AddRHS - Implements: X + X --> X << 1
1884struct AddRHS {
1885 Value *RHS;
1886 AddRHS(Value *rhs) : RHS(rhs) {}
1887 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1888 Instruction *apply(BinaryOperator &Add) const {
1889 return BinaryOperator::createShl(Add.getOperand(0),
1890 ConstantInt::get(Add.getType(), 1));
1891 }
1892};
1893
1894// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1895// iff C1&C2 == 0
1896struct AddMaskingAnd {
1897 Constant *C2;
1898 AddMaskingAnd(Constant *c) : C2(c) {}
1899 bool shouldApply(Value *LHS) const {
1900 ConstantInt *C1;
1901 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1902 ConstantExpr::getAnd(C1, C2)->isNullValue();
1903 }
1904 Instruction *apply(BinaryOperator &Add) const {
1905 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1906 }
1907};
1908
1909static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1910 InstCombiner *IC) {
1911 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1912 if (Constant *SOC = dyn_cast<Constant>(SO))
1913 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1914
1915 return IC->InsertNewInstBefore(CastInst::create(
1916 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1917 }
1918
1919 // Figure out if the constant is the left or the right argument.
1920 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1921 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1922
1923 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1924 if (ConstIsRHS)
1925 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1926 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1927 }
1928
1929 Value *Op0 = SO, *Op1 = ConstOperand;
1930 if (!ConstIsRHS)
1931 std::swap(Op0, Op1);
1932 Instruction *New;
1933 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1934 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1935 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1936 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1937 SO->getName()+".cmp");
1938 else {
1939 assert(0 && "Unknown binary instruction type!");
1940 abort();
1941 }
1942 return IC->InsertNewInstBefore(New, I);
1943}
1944
1945// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1946// constant as the other operand, try to fold the binary operator into the
1947// select arguments. This also works for Cast instructions, which obviously do
1948// not have a second operand.
1949static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1950 InstCombiner *IC) {
1951 // Don't modify shared select instructions
1952 if (!SI->hasOneUse()) return 0;
1953 Value *TV = SI->getOperand(1);
1954 Value *FV = SI->getOperand(2);
1955
1956 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1957 // Bool selects with constant operands can be folded to logical ops.
1958 if (SI->getType() == Type::Int1Ty) return 0;
1959
1960 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1961 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1962
1963 return new SelectInst(SI->getCondition(), SelectTrueVal,
1964 SelectFalseVal);
1965 }
1966 return 0;
1967}
1968
1969
1970/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1971/// node as operand #0, see if we can fold the instruction into the PHI (which
1972/// is only possible if all operands to the PHI are constants).
1973Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1974 PHINode *PN = cast<PHINode>(I.getOperand(0));
1975 unsigned NumPHIValues = PN->getNumIncomingValues();
1976 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1977
1978 // Check to see if all of the operands of the PHI are constants. If there is
1979 // one non-constant value, remember the BB it is. If there is more than one
1980 // or if *it* is a PHI, bail out.
1981 BasicBlock *NonConstBB = 0;
1982 for (unsigned i = 0; i != NumPHIValues; ++i)
1983 if (!isa<Constant>(PN->getIncomingValue(i))) {
1984 if (NonConstBB) return 0; // More than one non-const value.
1985 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1986 NonConstBB = PN->getIncomingBlock(i);
1987
1988 // If the incoming non-constant value is in I's block, we have an infinite
1989 // loop.
1990 if (NonConstBB == I.getParent())
1991 return 0;
1992 }
1993
1994 // If there is exactly one non-constant value, we can insert a copy of the
1995 // operation in that block. However, if this is a critical edge, we would be
1996 // inserting the computation one some other paths (e.g. inside a loop). Only
1997 // do this if the pred block is unconditionally branching into the phi block.
1998 if (NonConstBB) {
1999 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2000 if (!BI || !BI->isUnconditional()) return 0;
2001 }
2002
2003 // Okay, we can do the transformation: create the new PHI node.
2004 PHINode *NewPN = new PHINode(I.getType(), "");
2005 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2006 InsertNewInstBefore(NewPN, *PN);
2007 NewPN->takeName(PN);
2008
2009 // Next, add all of the operands to the PHI.
2010 if (I.getNumOperands() == 2) {
2011 Constant *C = cast<Constant>(I.getOperand(1));
2012 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002013 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2015 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2016 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2017 else
2018 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2019 } else {
2020 assert(PN->getIncomingBlock(i) == NonConstBB);
2021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2022 InV = BinaryOperator::create(BO->getOpcode(),
2023 PN->getIncomingValue(i), C, "phitmp",
2024 NonConstBB->getTerminator());
2025 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2026 InV = CmpInst::create(CI->getOpcode(),
2027 CI->getPredicate(),
2028 PN->getIncomingValue(i), C, "phitmp",
2029 NonConstBB->getTerminator());
2030 else
2031 assert(0 && "Unknown binop!");
2032
2033 AddToWorkList(cast<Instruction>(InV));
2034 }
2035 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2036 }
2037 } else {
2038 CastInst *CI = cast<CastInst>(&I);
2039 const Type *RetTy = CI->getType();
2040 for (unsigned i = 0; i != NumPHIValues; ++i) {
2041 Value *InV;
2042 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2043 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2044 } else {
2045 assert(PN->getIncomingBlock(i) == NonConstBB);
2046 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2047 I.getType(), "phitmp",
2048 NonConstBB->getTerminator());
2049 AddToWorkList(cast<Instruction>(InV));
2050 }
2051 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2052 }
2053 }
2054 return ReplaceInstUsesWith(I, NewPN);
2055}
2056
Chris Lattner55476162008-01-29 06:52:45 +00002057
2058/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2059/// value is never equal to -0.0.
2060///
2061/// Note that this function will need to be revisited when we support nondefault
2062/// rounding modes!
2063///
2064static bool CannotBeNegativeZero(const Value *V) {
2065 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2066 return !CFP->getValueAPF().isNegZero();
2067
2068 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2069 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2070 if (I->getOpcode() == Instruction::Add &&
2071 isa<ConstantFP>(I->getOperand(1)) &&
2072 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2073 return true;
2074
2075 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2076 if (II->getIntrinsicID() == Intrinsic::sqrt)
2077 return CannotBeNegativeZero(II->getOperand(1));
2078
2079 if (const CallInst *CI = dyn_cast<CallInst>(I))
2080 if (const Function *F = CI->getCalledFunction()) {
2081 if (F->isDeclaration()) {
2082 switch (F->getNameLen()) {
2083 case 3: // abs(x) != -0.0
2084 if (!strcmp(F->getNameStart(), "abs")) return true;
2085 break;
2086 case 4: // abs[lf](x) != -0.0
2087 if (!strcmp(F->getNameStart(), "absf")) return true;
2088 if (!strcmp(F->getNameStart(), "absl")) return true;
2089 break;
2090 }
2091 }
2092 }
2093 }
2094
2095 return false;
2096}
2097
2098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2100 bool Changed = SimplifyCommutative(I);
2101 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2102
2103 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2104 // X + undef -> undef
2105 if (isa<UndefValue>(RHS))
2106 return ReplaceInstUsesWith(I, RHS);
2107
2108 // X + 0 --> X
2109 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2110 if (RHSC->isNullValue())
2111 return ReplaceInstUsesWith(I, LHS);
2112 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002113 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2114 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115 return ReplaceInstUsesWith(I, LHS);
2116 }
2117
2118 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2119 // X + (signbit) --> X ^ signbit
2120 const APInt& Val = CI->getValue();
2121 uint32_t BitWidth = Val.getBitWidth();
2122 if (Val == APInt::getSignBit(BitWidth))
2123 return BinaryOperator::createXor(LHS, RHS);
2124
2125 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2126 // (X & 254)+1 -> (X&254)|1
2127 if (!isa<VectorType>(I.getType())) {
2128 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2129 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2130 KnownZero, KnownOne))
2131 return &I;
2132 }
2133 }
2134
2135 if (isa<PHINode>(LHS))
2136 if (Instruction *NV = FoldOpIntoPhi(I))
2137 return NV;
2138
2139 ConstantInt *XorRHS = 0;
2140 Value *XorLHS = 0;
2141 if (isa<ConstantInt>(RHSC) &&
2142 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2143 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2144 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2145
2146 uint32_t Size = TySizeBits / 2;
2147 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2148 APInt CFF80Val(-C0080Val);
2149 do {
2150 if (TySizeBits > Size) {
2151 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2152 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2153 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2154 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2155 // This is a sign extend if the top bits are known zero.
2156 if (!MaskedValueIsZero(XorLHS,
2157 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2158 Size = 0; // Not a sign ext, but can't be any others either.
2159 break;
2160 }
2161 }
2162 Size >>= 1;
2163 C0080Val = APIntOps::lshr(C0080Val, Size);
2164 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2165 } while (Size >= 1);
2166
2167 // FIXME: This shouldn't be necessary. When the backends can handle types
2168 // with funny bit widths then this whole cascade of if statements should
2169 // be removed. It is just here to get the size of the "middle" type back
2170 // up to something that the back ends can handle.
2171 const Type *MiddleType = 0;
2172 switch (Size) {
2173 default: break;
2174 case 32: MiddleType = Type::Int32Ty; break;
2175 case 16: MiddleType = Type::Int16Ty; break;
2176 case 8: MiddleType = Type::Int8Ty; break;
2177 }
2178 if (MiddleType) {
2179 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2180 InsertNewInstBefore(NewTrunc, I);
2181 return new SExtInst(NewTrunc, I.getType(), I.getName());
2182 }
2183 }
2184 }
2185
2186 // X + X --> X << 1
2187 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2188 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2189
2190 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2191 if (RHSI->getOpcode() == Instruction::Sub)
2192 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2193 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2194 }
2195 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2196 if (LHSI->getOpcode() == Instruction::Sub)
2197 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2198 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2199 }
2200 }
2201
2202 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002203 // -A + -B --> -(A + B)
2204 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002205 if (LHS->getType()->isIntOrIntVector()) {
2206 if (Value *RHSV = dyn_castNegVal(RHS)) {
2207 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2208 InsertNewInstBefore(NewAdd, I);
2209 return BinaryOperator::createNeg(NewAdd);
2210 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002211 }
2212
2213 return BinaryOperator::createSub(RHS, LHSV);
2214 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215
2216 // A + -B --> A - B
2217 if (!isa<Constant>(RHS))
2218 if (Value *V = dyn_castNegVal(RHS))
2219 return BinaryOperator::createSub(LHS, V);
2220
2221
2222 ConstantInt *C2;
2223 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2224 if (X == RHS) // X*C + X --> X * (C+1)
2225 return BinaryOperator::createMul(RHS, AddOne(C2));
2226
2227 // X*C1 + X*C2 --> X * (C1+C2)
2228 ConstantInt *C1;
2229 if (X == dyn_castFoldableMul(RHS, C1))
2230 return BinaryOperator::createMul(X, Add(C1, C2));
2231 }
2232
2233 // X + X*C --> X * (C+1)
2234 if (dyn_castFoldableMul(RHS, C2) == LHS)
2235 return BinaryOperator::createMul(LHS, AddOne(C2));
2236
2237 // X + ~X --> -1 since ~X = -X-1
2238 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2239 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2240
2241
2242 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2243 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2244 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2245 return R;
2246
Nick Lewycky83598a72008-02-03 07:42:09 +00002247 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002248 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002249 Value *W, *X, *Y, *Z;
2250 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2251 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2252 if (W != Y) {
2253 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002254 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002255 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002256 std::swap(W, X);
2257 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002258 std::swap(Y, Z);
2259 std::swap(W, X);
2260 }
2261 }
2262
2263 if (W == Y) {
2264 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2265 LHS->getName()), I);
2266 return BinaryOperator::createMul(W, NewAdd);
2267 }
2268 }
2269 }
2270
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2272 Value *X = 0;
2273 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2274 return BinaryOperator::createSub(SubOne(CRHS), X);
2275
2276 // (X & FF00) + xx00 -> (X+xx00) & FF00
2277 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2278 Constant *Anded = And(CRHS, C2);
2279 if (Anded == CRHS) {
2280 // See if all bits from the first bit set in the Add RHS up are included
2281 // in the mask. First, get the rightmost bit.
2282 const APInt& AddRHSV = CRHS->getValue();
2283
2284 // Form a mask of all bits from the lowest bit added through the top.
2285 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2286
2287 // See if the and mask includes all of these bits.
2288 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2289
2290 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2291 // Okay, the xform is safe. Insert the new add pronto.
2292 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2293 LHS->getName()), I);
2294 return BinaryOperator::createAnd(NewAdd, C2);
2295 }
2296 }
2297 }
2298
2299 // Try to fold constant add into select arguments.
2300 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2301 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2302 return R;
2303 }
2304
2305 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002306 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 {
2308 CastInst *CI = dyn_cast<CastInst>(LHS);
2309 Value *Other = RHS;
2310 if (!CI) {
2311 CI = dyn_cast<CastInst>(RHS);
2312 Other = LHS;
2313 }
2314 if (CI && CI->getType()->isSized() &&
2315 (CI->getType()->getPrimitiveSizeInBits() ==
2316 TD->getIntPtrType()->getPrimitiveSizeInBits())
2317 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002318 unsigned AS =
2319 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002320 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2321 PointerType::get(Type::Int8Ty, AS), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2323 return new PtrToIntInst(I2, CI->getType());
2324 }
2325 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002326
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002327 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002328 {
2329 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2330 Value *Other = RHS;
2331 if (!SI) {
2332 SI = dyn_cast<SelectInst>(RHS);
2333 Other = LHS;
2334 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002335 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002336 Value *TV = SI->getTrueValue();
2337 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002338 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002339
2340 // Can we fold the add into the argument of the select?
2341 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002342 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2343 A == Other) // Fold the add into the true select value.
2344 return new SelectInst(SI->getCondition(), N, A);
2345 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2346 A == Other) // Fold the add into the false select value.
2347 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002348 }
2349 }
Chris Lattner55476162008-01-29 06:52:45 +00002350
2351 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2353 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2354 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355
2356 return Changed ? &I : 0;
2357}
2358
2359// isSignBit - Return true if the value represented by the constant only has the
2360// highest order bit set.
2361static bool isSignBit(ConstantInt *CI) {
2362 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2363 return CI->getValue() == APInt::getSignBit(NumBits);
2364}
2365
2366Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2367 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2368
2369 if (Op0 == Op1) // sub X, X -> 0
2370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2371
2372 // If this is a 'B = x-(-A)', change to B = x+A...
2373 if (Value *V = dyn_castNegVal(Op1))
2374 return BinaryOperator::createAdd(Op0, V);
2375
2376 if (isa<UndefValue>(Op0))
2377 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2378 if (isa<UndefValue>(Op1))
2379 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2380
2381 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2382 // Replace (-1 - A) with (~A)...
2383 if (C->isAllOnesValue())
2384 return BinaryOperator::createNot(Op1);
2385
2386 // C - ~X == X + (1+C)
2387 Value *X = 0;
2388 if (match(Op1, m_Not(m_Value(X))))
2389 return BinaryOperator::createAdd(X, AddOne(C));
2390
2391 // -(X >>u 31) -> (X >>s 31)
2392 // -(X >>s 31) -> (X >>u 31)
2393 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002394 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002395 if (SI->getOpcode() == Instruction::LShr) {
2396 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2397 // Check to see if we are shifting out everything but the sign bit.
2398 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2399 SI->getType()->getPrimitiveSizeInBits()-1) {
2400 // Ok, the transformation is safe. Insert AShr.
2401 return BinaryOperator::create(Instruction::AShr,
2402 SI->getOperand(0), CU, SI->getName());
2403 }
2404 }
2405 }
2406 else if (SI->getOpcode() == Instruction::AShr) {
2407 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2408 // Check to see if we are shifting out everything but the sign bit.
2409 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2410 SI->getType()->getPrimitiveSizeInBits()-1) {
2411 // Ok, the transformation is safe. Insert LShr.
2412 return BinaryOperator::createLShr(
2413 SI->getOperand(0), CU, SI->getName());
2414 }
2415 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002416 }
2417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418 }
2419
2420 // Try to fold constant sub into select arguments.
2421 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2423 return R;
2424
2425 if (isa<PHINode>(Op0))
2426 if (Instruction *NV = FoldOpIntoPhi(I))
2427 return NV;
2428 }
2429
2430 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2431 if (Op1I->getOpcode() == Instruction::Add &&
2432 !Op0->getType()->isFPOrFPVector()) {
2433 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2434 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2435 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2436 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2437 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2438 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2439 // C1-(X+C2) --> (C1-C2)-X
2440 return BinaryOperator::createSub(Subtract(CI1, CI2),
2441 Op1I->getOperand(0));
2442 }
2443 }
2444
2445 if (Op1I->hasOneUse()) {
2446 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2447 // is not used by anyone else...
2448 //
2449 if (Op1I->getOpcode() == Instruction::Sub &&
2450 !Op1I->getType()->isFPOrFPVector()) {
2451 // Swap the two operands of the subexpr...
2452 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2453 Op1I->setOperand(0, IIOp1);
2454 Op1I->setOperand(1, IIOp0);
2455
2456 // Create the new top level add instruction...
2457 return BinaryOperator::createAdd(Op0, Op1);
2458 }
2459
2460 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2461 //
2462 if (Op1I->getOpcode() == Instruction::And &&
2463 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2464 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2465
2466 Value *NewNot =
2467 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2468 return BinaryOperator::createAnd(Op0, NewNot);
2469 }
2470
2471 // 0 - (X sdiv C) -> (X sdiv -C)
2472 if (Op1I->getOpcode() == Instruction::SDiv)
2473 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2474 if (CSI->isZero())
2475 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2476 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2477 ConstantExpr::getNeg(DivRHS));
2478
2479 // X - X*C --> X * (1-C)
2480 ConstantInt *C2 = 0;
2481 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2482 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2483 return BinaryOperator::createMul(Op0, CP1);
2484 }
Dan Gohmanda338742007-09-17 17:31:57 +00002485
2486 // X - ((X / Y) * Y) --> X % Y
2487 if (Op1I->getOpcode() == Instruction::Mul)
2488 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2489 if (Op0 == I->getOperand(0) &&
2490 Op1I->getOperand(1) == I->getOperand(1)) {
2491 if (I->getOpcode() == Instruction::SDiv)
2492 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2493 if (I->getOpcode() == Instruction::UDiv)
2494 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2495 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496 }
2497 }
2498
2499 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002500 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501 if (Op0I->getOpcode() == Instruction::Add) {
2502 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2503 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2504 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2505 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2506 } else if (Op0I->getOpcode() == Instruction::Sub) {
2507 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2508 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2509 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002510 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511
2512 ConstantInt *C1;
2513 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2514 if (X == Op1) // X*C - X --> X * (C-1)
2515 return BinaryOperator::createMul(Op1, SubOne(C1));
2516
2517 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2518 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Shengc7d7cdc2008-02-22 10:00:35 +00002519 return BinaryOperator::createMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 }
2521 return 0;
2522}
2523
2524/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2525/// comparison only checks the sign bit. If it only checks the sign bit, set
2526/// TrueIfSigned if the result of the comparison is true when the input value is
2527/// signed.
2528static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2529 bool &TrueIfSigned) {
2530 switch (pred) {
2531 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2532 TrueIfSigned = true;
2533 return RHS->isZero();
2534 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2535 TrueIfSigned = true;
2536 return RHS->isAllOnesValue();
2537 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2538 TrueIfSigned = false;
2539 return RHS->isAllOnesValue();
2540 case ICmpInst::ICMP_UGT:
2541 // True if LHS u> RHS and RHS == high-bit-mask - 1
2542 TrueIfSigned = true;
2543 return RHS->getValue() ==
2544 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2545 case ICmpInst::ICMP_UGE:
2546 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2547 TrueIfSigned = true;
2548 return RHS->getValue() ==
2549 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2550 default:
2551 return false;
2552 }
2553}
2554
2555Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2556 bool Changed = SimplifyCommutative(I);
2557 Value *Op0 = I.getOperand(0);
2558
2559 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561
2562 // Simplify mul instructions with a constant RHS...
2563 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2564 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2565
2566 // ((X << C1)*C2) == (X * (C2 << C1))
2567 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2568 if (SI->getOpcode() == Instruction::Shl)
2569 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2570 return BinaryOperator::createMul(SI->getOperand(0),
2571 ConstantExpr::getShl(CI, ShOp));
2572
2573 if (CI->isZero())
2574 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2575 if (CI->equalsInt(1)) // X * 1 == X
2576 return ReplaceInstUsesWith(I, Op0);
2577 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2578 return BinaryOperator::createNeg(Op0, I.getName());
2579
2580 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2581 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2582 return BinaryOperator::createShl(Op0,
2583 ConstantInt::get(Op0->getType(), Val.logBase2()));
2584 }
2585 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2586 if (Op1F->isNullValue())
2587 return ReplaceInstUsesWith(I, Op1);
2588
2589 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2590 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002591 // We need a better interface for long double here.
2592 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2593 if (Op1F->isExactlyValue(1.0))
2594 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595 }
2596
2597 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2598 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2599 isa<ConstantInt>(Op0I->getOperand(1))) {
2600 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2601 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2602 Op1, "tmp");
2603 InsertNewInstBefore(Add, I);
2604 Value *C1C2 = ConstantExpr::getMul(Op1,
2605 cast<Constant>(Op0I->getOperand(1)));
2606 return BinaryOperator::createAdd(Add, C1C2);
2607
2608 }
2609
2610 // Try to fold constant mul into select arguments.
2611 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2613 return R;
2614
2615 if (isa<PHINode>(Op0))
2616 if (Instruction *NV = FoldOpIntoPhi(I))
2617 return NV;
2618 }
2619
2620 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2621 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2622 return BinaryOperator::createMul(Op0v, Op1v);
2623
2624 // If one of the operands of the multiply is a cast from a boolean value, then
2625 // we know the bool is either zero or one, so this is a 'masking' multiply.
2626 // See if we can simplify things based on how the boolean was originally
2627 // formed.
2628 CastInst *BoolCast = 0;
2629 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2630 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2631 BoolCast = CI;
2632 if (!BoolCast)
2633 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2634 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2635 BoolCast = CI;
2636 if (BoolCast) {
2637 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2638 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2639 const Type *SCOpTy = SCIOp0->getType();
2640 bool TIS = false;
2641
2642 // If the icmp is true iff the sign bit of X is set, then convert this
2643 // multiply into a shift/and combination.
2644 if (isa<ConstantInt>(SCIOp1) &&
2645 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2646 TIS) {
2647 // Shift the X value right to turn it into "all signbits".
2648 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2649 SCOpTy->getPrimitiveSizeInBits()-1);
2650 Value *V =
2651 InsertNewInstBefore(
2652 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2653 BoolCast->getOperand(0)->getName()+
2654 ".mask"), I);
2655
2656 // If the multiply type is not the same as the source type, sign extend
2657 // or truncate to the multiply type.
2658 if (I.getType() != V->getType()) {
2659 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2660 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2661 Instruction::CastOps opcode =
2662 (SrcBits == DstBits ? Instruction::BitCast :
2663 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2664 V = InsertCastBefore(opcode, V, I.getType(), I);
2665 }
2666
2667 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2668 return BinaryOperator::createAnd(V, OtherOp);
2669 }
2670 }
2671 }
2672
2673 return Changed ? &I : 0;
2674}
2675
2676/// This function implements the transforms on div instructions that work
2677/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2678/// used by the visitors to those instructions.
2679/// @brief Transforms common to all three div instructions
2680Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2682
Chris Lattner653ef3c2008-02-19 06:12:18 +00002683 // undef / X -> 0 for integer.
2684 // undef / X -> undef for FP (the undef could be a snan).
2685 if (isa<UndefValue>(Op0)) {
2686 if (Op0->getType()->isFPOrFPVector())
2687 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002689 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002690
2691 // X / undef -> undef
2692 if (isa<UndefValue>(Op1))
2693 return ReplaceInstUsesWith(I, Op1);
2694
Chris Lattner5be238b2008-01-28 00:58:18 +00002695 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2696 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002698 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2699 // the same basic block, then we replace the select with Y, and the
2700 // condition of the select with false (if the cond value is in the same BB).
2701 // If the select has uses other than the div, this allows them to be
2702 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2703 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704 if (ST->isNullValue()) {
2705 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2706 if (CondI && CondI->getParent() == I.getParent())
2707 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2708 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2709 I.setOperand(1, SI->getOperand(2));
2710 else
2711 UpdateValueUsesWith(SI, SI->getOperand(2));
2712 return &I;
2713 }
2714
Chris Lattner5be238b2008-01-28 00:58:18 +00002715 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2716 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717 if (ST->isNullValue()) {
2718 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2719 if (CondI && CondI->getParent() == I.getParent())
2720 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2721 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2722 I.setOperand(1, SI->getOperand(1));
2723 else
2724 UpdateValueUsesWith(SI, SI->getOperand(1));
2725 return &I;
2726 }
2727 }
2728
2729 return 0;
2730}
2731
2732/// This function implements the transforms common to both integer division
2733/// instructions (udiv and sdiv). It is called by the visitors to those integer
2734/// division instructions.
2735/// @brief Common integer divide transforms
2736Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2738
2739 if (Instruction *Common = commonDivTransforms(I))
2740 return Common;
2741
2742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2743 // div X, 1 == X
2744 if (RHS->equalsInt(1))
2745 return ReplaceInstUsesWith(I, Op0);
2746
2747 // (X / C1) / C2 -> X / (C1*C2)
2748 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2749 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2750 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002751 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2752 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2753 else
2754 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2755 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 }
2757
2758 if (!RHS->isZero()) { // avoid X udiv 0
2759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2760 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2761 return R;
2762 if (isa<PHINode>(Op0))
2763 if (Instruction *NV = FoldOpIntoPhi(I))
2764 return NV;
2765 }
2766 }
2767
2768 // 0 / X == 0, we don't need to preserve faults!
2769 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2770 if (LHS->equalsInt(0))
2771 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2772
2773 return 0;
2774}
2775
2776Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2778
2779 // Handle the integer div common cases
2780 if (Instruction *Common = commonIDivTransforms(I))
2781 return Common;
2782
2783 // X udiv C^2 -> X >> C
2784 // Check to see if this is an unsigned division with an exact power of 2,
2785 // if so, convert to a right shift.
2786 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2787 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2788 return BinaryOperator::createLShr(Op0,
2789 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2790 }
2791
2792 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2793 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2794 if (RHSI->getOpcode() == Instruction::Shl &&
2795 isa<ConstantInt>(RHSI->getOperand(0))) {
2796 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2797 if (C1.isPowerOf2()) {
2798 Value *N = RHSI->getOperand(1);
2799 const Type *NTy = N->getType();
2800 if (uint32_t C2 = C1.logBase2()) {
2801 Constant *C2V = ConstantInt::get(NTy, C2);
2802 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2803 }
2804 return BinaryOperator::createLShr(Op0, N);
2805 }
2806 }
2807 }
2808
2809 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2810 // where C1&C2 are powers of two.
2811 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2812 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2813 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2814 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2815 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2816 // Compute the shift amounts
2817 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2818 // Construct the "on true" case of the select
2819 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2820 Instruction *TSI = BinaryOperator::createLShr(
2821 Op0, TC, SI->getName()+".t");
2822 TSI = InsertNewInstBefore(TSI, I);
2823
2824 // Construct the "on false" case of the select
2825 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2826 Instruction *FSI = BinaryOperator::createLShr(
2827 Op0, FC, SI->getName()+".f");
2828 FSI = InsertNewInstBefore(FSI, I);
2829
2830 // construct the select instruction and return it.
2831 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2832 }
2833 }
2834 return 0;
2835}
2836
2837Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2838 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2839
2840 // Handle the integer div common cases
2841 if (Instruction *Common = commonIDivTransforms(I))
2842 return Common;
2843
2844 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2845 // sdiv X, -1 == -X
2846 if (RHS->isAllOnesValue())
2847 return BinaryOperator::createNeg(Op0);
2848
2849 // -X/C -> X/-C
2850 if (Value *LHSNeg = dyn_castNegVal(Op0))
2851 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2852 }
2853
2854 // If the sign bits of both operands are zero (i.e. we can prove they are
2855 // unsigned inputs), turn this into a udiv.
2856 if (I.getType()->isInteger()) {
2857 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2858 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002859 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002860 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2861 }
2862 }
2863
2864 return 0;
2865}
2866
2867Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2868 return commonDivTransforms(I);
2869}
2870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871/// This function implements the transforms on rem instructions that work
2872/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2873/// is used by the visitors to those instructions.
2874/// @brief Transforms common to all three rem instructions
2875Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2877
Chris Lattner653ef3c2008-02-19 06:12:18 +00002878 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 if (Constant *LHS = dyn_cast<Constant>(Op0))
2880 if (LHS->isNullValue())
2881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2882
Chris Lattner653ef3c2008-02-19 06:12:18 +00002883 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2884 if (I.getType()->isFPOrFPVector())
2885 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002887 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 if (isa<UndefValue>(Op1))
2889 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2890
2891 // Handle cases involving: rem X, (select Cond, Y, Z)
2892 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2893 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2894 // the same basic block, then we replace the select with Y, and the
2895 // condition of the select with false (if the cond value is in the same
2896 // BB). If the select has uses other than the div, this allows them to be
2897 // simplified also.
2898 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2899 if (ST->isNullValue()) {
2900 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2901 if (CondI && CondI->getParent() == I.getParent())
2902 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2903 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2904 I.setOperand(1, SI->getOperand(2));
2905 else
2906 UpdateValueUsesWith(SI, SI->getOperand(2));
2907 return &I;
2908 }
2909 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2910 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2911 if (ST->isNullValue()) {
2912 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2913 if (CondI && CondI->getParent() == I.getParent())
2914 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2915 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2916 I.setOperand(1, SI->getOperand(1));
2917 else
2918 UpdateValueUsesWith(SI, SI->getOperand(1));
2919 return &I;
2920 }
2921 }
2922
2923 return 0;
2924}
2925
2926/// This function implements the transforms common to both integer remainder
2927/// instructions (urem and srem). It is called by the visitors to those integer
2928/// remainder instructions.
2929/// @brief Common integer remainder transforms
2930Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
2933 if (Instruction *common = commonRemTransforms(I))
2934 return common;
2935
2936 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2937 // X % 0 == undef, we don't need to preserve faults!
2938 if (RHS->equalsInt(0))
2939 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2940
2941 if (RHS->equalsInt(1)) // X % 1 == 0
2942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2943
2944 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2945 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2946 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2947 return R;
2948 } else if (isa<PHINode>(Op0I)) {
2949 if (Instruction *NV = FoldOpIntoPhi(I))
2950 return NV;
2951 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002952
2953 // See if we can fold away this rem instruction.
2954 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2955 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2956 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2957 KnownZero, KnownOne))
2958 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002959 }
2960 }
2961
2962 return 0;
2963}
2964
2965Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2967
2968 if (Instruction *common = commonIRemTransforms(I))
2969 return common;
2970
2971 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2972 // X urem C^2 -> X and C
2973 // Check to see if this is an unsigned remainder with an exact power of 2,
2974 // if so, convert to a bitwise and.
2975 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2976 if (C->getValue().isPowerOf2())
2977 return BinaryOperator::createAnd(Op0, SubOne(C));
2978 }
2979
2980 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2981 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2982 if (RHSI->getOpcode() == Instruction::Shl &&
2983 isa<ConstantInt>(RHSI->getOperand(0))) {
2984 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2985 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2986 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2987 "tmp"), I);
2988 return BinaryOperator::createAnd(Op0, Add);
2989 }
2990 }
2991 }
2992
2993 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2994 // where C1&C2 are powers of two.
2995 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2996 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2997 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2998 // STO == 0 and SFO == 0 handled above.
2999 if ((STO->getValue().isPowerOf2()) &&
3000 (SFO->getValue().isPowerOf2())) {
3001 Value *TrueAnd = InsertNewInstBefore(
3002 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3003 Value *FalseAnd = InsertNewInstBefore(
3004 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3005 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3006 }
3007 }
3008 }
3009
3010 return 0;
3011}
3012
3013Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015
Dan Gohmandb3dd962007-11-05 23:16:33 +00003016 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 if (Instruction *common = commonIRemTransforms(I))
3018 return common;
3019
3020 if (Value *RHSNeg = dyn_castNegVal(Op1))
3021 if (!isa<ConstantInt>(RHSNeg) ||
3022 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3023 // X % -Y -> X % Y
3024 AddUsesToWorkList(I);
3025 I.setOperand(1, RHSNeg);
3026 return &I;
3027 }
3028
Dan Gohmandb3dd962007-11-05 23:16:33 +00003029 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003030 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003031 if (I.getType()->isInteger()) {
3032 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3033 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3034 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3035 return BinaryOperator::createURem(Op0, Op1, I.getName());
3036 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 }
3038
3039 return 0;
3040}
3041
3042Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3043 return commonRemTransforms(I);
3044}
3045
3046// isMaxValueMinusOne - return true if this is Max-1
3047static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3048 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3049 if (!isSigned)
3050 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3051 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3052}
3053
3054// isMinValuePlusOne - return true if this is Min+1
3055static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3056 if (!isSigned)
3057 return C->getValue() == 1; // unsigned
3058
3059 // Calculate 1111111111000000000000
3060 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3061 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3062}
3063
3064// isOneBitSet - Return true if there is exactly one bit set in the specified
3065// constant.
3066static bool isOneBitSet(const ConstantInt *CI) {
3067 return CI->getValue().isPowerOf2();
3068}
3069
3070// isHighOnes - Return true if the constant is of the form 1+0+.
3071// This is the same as lowones(~X).
3072static bool isHighOnes(const ConstantInt *CI) {
3073 return (~CI->getValue() + 1).isPowerOf2();
3074}
3075
3076/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3077/// are carefully arranged to allow folding of expressions such as:
3078///
3079/// (A < B) | (A > B) --> (A != B)
3080///
3081/// Note that this is only valid if the first and second predicates have the
3082/// same sign. Is illegal to do: (A u< B) | (A s> B)
3083///
3084/// Three bits are used to represent the condition, as follows:
3085/// 0 A > B
3086/// 1 A == B
3087/// 2 A < B
3088///
3089/// <=> Value Definition
3090/// 000 0 Always false
3091/// 001 1 A > B
3092/// 010 2 A == B
3093/// 011 3 A >= B
3094/// 100 4 A < B
3095/// 101 5 A != B
3096/// 110 6 A <= B
3097/// 111 7 Always true
3098///
3099static unsigned getICmpCode(const ICmpInst *ICI) {
3100 switch (ICI->getPredicate()) {
3101 // False -> 0
3102 case ICmpInst::ICMP_UGT: return 1; // 001
3103 case ICmpInst::ICMP_SGT: return 1; // 001
3104 case ICmpInst::ICMP_EQ: return 2; // 010
3105 case ICmpInst::ICMP_UGE: return 3; // 011
3106 case ICmpInst::ICMP_SGE: return 3; // 011
3107 case ICmpInst::ICMP_ULT: return 4; // 100
3108 case ICmpInst::ICMP_SLT: return 4; // 100
3109 case ICmpInst::ICMP_NE: return 5; // 101
3110 case ICmpInst::ICMP_ULE: return 6; // 110
3111 case ICmpInst::ICMP_SLE: return 6; // 110
3112 // True -> 7
3113 default:
3114 assert(0 && "Invalid ICmp predicate!");
3115 return 0;
3116 }
3117}
3118
3119/// getICmpValue - This is the complement of getICmpCode, which turns an
3120/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003121/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003122/// of predicate to use in new icmp instructions.
3123static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3124 switch (code) {
3125 default: assert(0 && "Illegal ICmp code!");
3126 case 0: return ConstantInt::getFalse();
3127 case 1:
3128 if (sign)
3129 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3130 else
3131 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3132 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3133 case 3:
3134 if (sign)
3135 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3136 else
3137 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3138 case 4:
3139 if (sign)
3140 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3141 else
3142 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3143 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3144 case 6:
3145 if (sign)
3146 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3147 else
3148 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3149 case 7: return ConstantInt::getTrue();
3150 }
3151}
3152
3153static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3154 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3155 (ICmpInst::isSignedPredicate(p1) &&
3156 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3157 (ICmpInst::isSignedPredicate(p2) &&
3158 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3159}
3160
3161namespace {
3162// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3163struct FoldICmpLogical {
3164 InstCombiner &IC;
3165 Value *LHS, *RHS;
3166 ICmpInst::Predicate pred;
3167 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3168 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3169 pred(ICI->getPredicate()) {}
3170 bool shouldApply(Value *V) const {
3171 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3172 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003173 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3174 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175 return false;
3176 }
3177 Instruction *apply(Instruction &Log) const {
3178 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3179 if (ICI->getOperand(0) != LHS) {
3180 assert(ICI->getOperand(1) == LHS);
3181 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3182 }
3183
3184 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3185 unsigned LHSCode = getICmpCode(ICI);
3186 unsigned RHSCode = getICmpCode(RHSICI);
3187 unsigned Code;
3188 switch (Log.getOpcode()) {
3189 case Instruction::And: Code = LHSCode & RHSCode; break;
3190 case Instruction::Or: Code = LHSCode | RHSCode; break;
3191 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3192 default: assert(0 && "Illegal logical opcode!"); return 0;
3193 }
3194
3195 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3196 ICmpInst::isSignedPredicate(ICI->getPredicate());
3197
3198 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3199 if (Instruction *I = dyn_cast<Instruction>(RV))
3200 return I;
3201 // Otherwise, it's a constant boolean value...
3202 return IC.ReplaceInstUsesWith(Log, RV);
3203 }
3204};
3205} // end anonymous namespace
3206
3207// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3208// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3209// guaranteed to be a binary operator.
3210Instruction *InstCombiner::OptAndOp(Instruction *Op,
3211 ConstantInt *OpRHS,
3212 ConstantInt *AndRHS,
3213 BinaryOperator &TheAnd) {
3214 Value *X = Op->getOperand(0);
3215 Constant *Together = 0;
3216 if (!Op->isShift())
3217 Together = And(AndRHS, OpRHS);
3218
3219 switch (Op->getOpcode()) {
3220 case Instruction::Xor:
3221 if (Op->hasOneUse()) {
3222 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3223 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3224 InsertNewInstBefore(And, TheAnd);
3225 And->takeName(Op);
3226 return BinaryOperator::createXor(And, Together);
3227 }
3228 break;
3229 case Instruction::Or:
3230 if (Together == AndRHS) // (X | C) & C --> C
3231 return ReplaceInstUsesWith(TheAnd, AndRHS);
3232
3233 if (Op->hasOneUse() && Together != OpRHS) {
3234 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3235 Instruction *Or = BinaryOperator::createOr(X, Together);
3236 InsertNewInstBefore(Or, TheAnd);
3237 Or->takeName(Op);
3238 return BinaryOperator::createAnd(Or, AndRHS);
3239 }
3240 break;
3241 case Instruction::Add:
3242 if (Op->hasOneUse()) {
3243 // Adding a one to a single bit bit-field should be turned into an XOR
3244 // of the bit. First thing to check is to see if this AND is with a
3245 // single bit constant.
3246 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3247
3248 // If there is only one bit set...
3249 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3250 // Ok, at this point, we know that we are masking the result of the
3251 // ADD down to exactly one bit. If the constant we are adding has
3252 // no bits set below this bit, then we can eliminate the ADD.
3253 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3254
3255 // Check to see if any bits below the one bit set in AndRHSV are set.
3256 if ((AddRHS & (AndRHSV-1)) == 0) {
3257 // If not, the only thing that can effect the output of the AND is
3258 // the bit specified by AndRHSV. If that bit is set, the effect of
3259 // the XOR is to toggle the bit. If it is clear, then the ADD has
3260 // no effect.
3261 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3262 TheAnd.setOperand(0, X);
3263 return &TheAnd;
3264 } else {
3265 // Pull the XOR out of the AND.
3266 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3267 InsertNewInstBefore(NewAnd, TheAnd);
3268 NewAnd->takeName(Op);
3269 return BinaryOperator::createXor(NewAnd, AndRHS);
3270 }
3271 }
3272 }
3273 }
3274 break;
3275
3276 case Instruction::Shl: {
3277 // We know that the AND will not produce any of the bits shifted in, so if
3278 // the anded constant includes them, clear them now!
3279 //
3280 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3281 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3282 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3283 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3284
3285 if (CI->getValue() == ShlMask) {
3286 // Masking out bits that the shift already masks
3287 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3288 } else if (CI != AndRHS) { // Reducing bits set in and.
3289 TheAnd.setOperand(1, CI);
3290 return &TheAnd;
3291 }
3292 break;
3293 }
3294 case Instruction::LShr:
3295 {
3296 // We know that the AND will not produce any of the bits shifted in, so if
3297 // the anded constant includes them, clear them now! This only applies to
3298 // unsigned shifts, because a signed shr may bring in set bits!
3299 //
3300 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3301 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3302 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3303 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3304
3305 if (CI->getValue() == ShrMask) {
3306 // Masking out bits that the shift already masks.
3307 return ReplaceInstUsesWith(TheAnd, Op);
3308 } else if (CI != AndRHS) {
3309 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3310 return &TheAnd;
3311 }
3312 break;
3313 }
3314 case Instruction::AShr:
3315 // Signed shr.
3316 // See if this is shifting in some sign extension, then masking it out
3317 // with an and.
3318 if (Op->hasOneUse()) {
3319 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3320 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3321 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3322 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3323 if (C == AndRHS) { // Masking out bits shifted in.
3324 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3325 // Make the argument unsigned.
3326 Value *ShVal = Op->getOperand(0);
3327 ShVal = InsertNewInstBefore(
3328 BinaryOperator::createLShr(ShVal, OpRHS,
3329 Op->getName()), TheAnd);
3330 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3331 }
3332 }
3333 break;
3334 }
3335 return 0;
3336}
3337
3338
3339/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3340/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3341/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3342/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3343/// insert new instructions.
3344Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3345 bool isSigned, bool Inside,
3346 Instruction &IB) {
3347 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3348 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3349 "Lo is not <= Hi in range emission code!");
3350
3351 if (Inside) {
3352 if (Lo == Hi) // Trivially false.
3353 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3354
3355 // V >= Min && V < Hi --> V < Hi
3356 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3357 ICmpInst::Predicate pred = (isSigned ?
3358 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3359 return new ICmpInst(pred, V, Hi);
3360 }
3361
3362 // Emit V-Lo <u Hi-Lo
3363 Constant *NegLo = ConstantExpr::getNeg(Lo);
3364 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3365 InsertNewInstBefore(Add, IB);
3366 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3367 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3368 }
3369
3370 if (Lo == Hi) // Trivially true.
3371 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3372
3373 // V < Min || V >= Hi -> V > Hi-1
3374 Hi = SubOne(cast<ConstantInt>(Hi));
3375 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3376 ICmpInst::Predicate pred = (isSigned ?
3377 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3378 return new ICmpInst(pred, V, Hi);
3379 }
3380
3381 // Emit V-Lo >u Hi-1-Lo
3382 // Note that Hi has already had one subtracted from it, above.
3383 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3384 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3385 InsertNewInstBefore(Add, IB);
3386 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3387 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3388}
3389
3390// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3391// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3392// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3393// not, since all 1s are not contiguous.
3394static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3395 const APInt& V = Val->getValue();
3396 uint32_t BitWidth = Val->getType()->getBitWidth();
3397 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3398
3399 // look for the first zero bit after the run of ones
3400 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3401 // look for the first non-zero bit
3402 ME = V.getActiveBits();
3403 return true;
3404}
3405
3406/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3407/// where isSub determines whether the operator is a sub. If we can fold one of
3408/// the following xforms:
3409///
3410/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3411/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3412/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3413///
3414/// return (A +/- B).
3415///
3416Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3417 ConstantInt *Mask, bool isSub,
3418 Instruction &I) {
3419 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3420 if (!LHSI || LHSI->getNumOperands() != 2 ||
3421 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3422
3423 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3424
3425 switch (LHSI->getOpcode()) {
3426 default: return 0;
3427 case Instruction::And:
3428 if (And(N, Mask) == Mask) {
3429 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3430 if ((Mask->getValue().countLeadingZeros() +
3431 Mask->getValue().countPopulation()) ==
3432 Mask->getValue().getBitWidth())
3433 break;
3434
3435 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3436 // part, we don't need any explicit masks to take them out of A. If that
3437 // is all N is, ignore it.
3438 uint32_t MB = 0, ME = 0;
3439 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3440 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3441 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3442 if (MaskedValueIsZero(RHS, Mask))
3443 break;
3444 }
3445 }
3446 return 0;
3447 case Instruction::Or:
3448 case Instruction::Xor:
3449 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3450 if ((Mask->getValue().countLeadingZeros() +
3451 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3452 && And(N, Mask)->isZero())
3453 break;
3454 return 0;
3455 }
3456
3457 Instruction *New;
3458 if (isSub)
3459 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3460 else
3461 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3462 return InsertNewInstBefore(New, I);
3463}
3464
3465Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3466 bool Changed = SimplifyCommutative(I);
3467 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3468
3469 if (isa<UndefValue>(Op1)) // X & undef -> 0
3470 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3471
3472 // and X, X = X
3473 if (Op0 == Op1)
3474 return ReplaceInstUsesWith(I, Op1);
3475
3476 // See if we can simplify any instructions used by the instruction whose sole
3477 // purpose is to compute bits we don't care about.
3478 if (!isa<VectorType>(I.getType())) {
3479 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3480 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3481 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3482 KnownZero, KnownOne))
3483 return &I;
3484 } else {
3485 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3486 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3487 return ReplaceInstUsesWith(I, I.getOperand(0));
3488 } else if (isa<ConstantAggregateZero>(Op1)) {
3489 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3490 }
3491 }
3492
3493 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3494 const APInt& AndRHSMask = AndRHS->getValue();
3495 APInt NotAndRHS(~AndRHSMask);
3496
3497 // Optimize a variety of ((val OP C1) & C2) combinations...
3498 if (isa<BinaryOperator>(Op0)) {
3499 Instruction *Op0I = cast<Instruction>(Op0);
3500 Value *Op0LHS = Op0I->getOperand(0);
3501 Value *Op0RHS = Op0I->getOperand(1);
3502 switch (Op0I->getOpcode()) {
3503 case Instruction::Xor:
3504 case Instruction::Or:
3505 // If the mask is only needed on one incoming arm, push it up.
3506 if (Op0I->hasOneUse()) {
3507 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3508 // Not masking anything out for the LHS, move to RHS.
3509 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3510 Op0RHS->getName()+".masked");
3511 InsertNewInstBefore(NewRHS, I);
3512 return BinaryOperator::create(
3513 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3514 }
3515 if (!isa<Constant>(Op0RHS) &&
3516 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3517 // Not masking anything out for the RHS, move to LHS.
3518 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3519 Op0LHS->getName()+".masked");
3520 InsertNewInstBefore(NewLHS, I);
3521 return BinaryOperator::create(
3522 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3523 }
3524 }
3525
3526 break;
3527 case Instruction::Add:
3528 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3529 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3530 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3531 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3532 return BinaryOperator::createAnd(V, AndRHS);
3533 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3534 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3535 break;
3536
3537 case Instruction::Sub:
3538 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3539 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3540 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3541 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3542 return BinaryOperator::createAnd(V, AndRHS);
3543 break;
3544 }
3545
3546 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3547 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3548 return Res;
3549 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3550 // If this is an integer truncation or change from signed-to-unsigned, and
3551 // if the source is an and/or with immediate, transform it. This
3552 // frequently occurs for bitfield accesses.
3553 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3554 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3555 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003556 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557 if (CastOp->getOpcode() == Instruction::And) {
3558 // Change: and (cast (and X, C1) to T), C2
3559 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3560 // This will fold the two constants together, which may allow
3561 // other simplifications.
3562 Instruction *NewCast = CastInst::createTruncOrBitCast(
3563 CastOp->getOperand(0), I.getType(),
3564 CastOp->getName()+".shrunk");
3565 NewCast = InsertNewInstBefore(NewCast, I);
3566 // trunc_or_bitcast(C1)&C2
3567 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3568 C3 = ConstantExpr::getAnd(C3, AndRHS);
3569 return BinaryOperator::createAnd(NewCast, C3);
3570 } else if (CastOp->getOpcode() == Instruction::Or) {
3571 // Change: and (cast (or X, C1) to T), C2
3572 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3573 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3574 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3575 return ReplaceInstUsesWith(I, AndRHS);
3576 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003577 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 }
3579 }
3580
3581 // Try to fold constant and into select arguments.
3582 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3583 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3584 return R;
3585 if (isa<PHINode>(Op0))
3586 if (Instruction *NV = FoldOpIntoPhi(I))
3587 return NV;
3588 }
3589
3590 Value *Op0NotVal = dyn_castNotVal(Op0);
3591 Value *Op1NotVal = dyn_castNotVal(Op1);
3592
3593 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3595
3596 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3597 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3598 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3599 I.getName()+".demorgan");
3600 InsertNewInstBefore(Or, I);
3601 return BinaryOperator::createNot(Or);
3602 }
3603
3604 {
3605 Value *A = 0, *B = 0, *C = 0, *D = 0;
3606 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3607 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3608 return ReplaceInstUsesWith(I, Op1);
3609
3610 // (A|B) & ~(A&B) -> A^B
3611 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3612 if ((A == C && B == D) || (A == D && B == C))
3613 return BinaryOperator::createXor(A, B);
3614 }
3615 }
3616
3617 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3618 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3619 return ReplaceInstUsesWith(I, Op0);
3620
3621 // ~(A&B) & (A|B) -> A^B
3622 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3623 if ((A == C && B == D) || (A == D && B == C))
3624 return BinaryOperator::createXor(A, B);
3625 }
3626 }
3627
3628 if (Op0->hasOneUse() &&
3629 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3630 if (A == Op1) { // (A^B)&A -> A&(A^B)
3631 I.swapOperands(); // Simplify below
3632 std::swap(Op0, Op1);
3633 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3634 cast<BinaryOperator>(Op0)->swapOperands();
3635 I.swapOperands(); // Simplify below
3636 std::swap(Op0, Op1);
3637 }
3638 }
3639 if (Op1->hasOneUse() &&
3640 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3641 if (B == Op0) { // B&(A^B) -> B&(B^A)
3642 cast<BinaryOperator>(Op1)->swapOperands();
3643 std::swap(A, B);
3644 }
3645 if (A == Op0) { // A&(A^B) -> A & ~B
3646 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3647 InsertNewInstBefore(NotB, I);
3648 return BinaryOperator::createAnd(A, NotB);
3649 }
3650 }
3651 }
3652
3653 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3654 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3655 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3656 return R;
3657
3658 Value *LHSVal, *RHSVal;
3659 ConstantInt *LHSCst, *RHSCst;
3660 ICmpInst::Predicate LHSCC, RHSCC;
3661 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3662 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3663 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3664 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3665 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3666 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3667 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003668 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3669
3670 // Don't try to fold ICMP_SLT + ICMP_ULT.
3671 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3672 ICmpInst::isSignedPredicate(LHSCC) ==
3673 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003675 ICmpInst::Predicate GT;
3676 if (ICmpInst::isSignedPredicate(LHSCC) ||
3677 (ICmpInst::isEquality(LHSCC) &&
3678 ICmpInst::isSignedPredicate(RHSCC)))
3679 GT = ICmpInst::ICMP_SGT;
3680 else
3681 GT = ICmpInst::ICMP_UGT;
3682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3684 ICmpInst *LHS = cast<ICmpInst>(Op0);
3685 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3686 std::swap(LHS, RHS);
3687 std::swap(LHSCst, RHSCst);
3688 std::swap(LHSCC, RHSCC);
3689 }
3690
3691 // At this point, we know we have have two icmp instructions
3692 // comparing a value against two constants and and'ing the result
3693 // together. Because of the above check, we know that we only have
3694 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3695 // (from the FoldICmpLogical check above), that the two constants
3696 // are not equal and that the larger constant is on the RHS
3697 assert(LHSCst != RHSCst && "Compares not folded above?");
3698
3699 switch (LHSCC) {
3700 default: assert(0 && "Unknown integer condition code!");
3701 case ICmpInst::ICMP_EQ:
3702 switch (RHSCC) {
3703 default: assert(0 && "Unknown integer condition code!");
3704 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3705 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3706 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3708 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3709 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3710 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3711 return ReplaceInstUsesWith(I, LHS);
3712 }
3713 case ICmpInst::ICMP_NE:
3714 switch (RHSCC) {
3715 default: assert(0 && "Unknown integer condition code!");
3716 case ICmpInst::ICMP_ULT:
3717 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3718 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3719 break; // (X != 13 & X u< 15) -> no change
3720 case ICmpInst::ICMP_SLT:
3721 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3722 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3723 break; // (X != 13 & X s< 15) -> no change
3724 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3725 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3726 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3727 return ReplaceInstUsesWith(I, RHS);
3728 case ICmpInst::ICMP_NE:
3729 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3730 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3731 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3732 LHSVal->getName()+".off");
3733 InsertNewInstBefore(Add, I);
3734 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3735 ConstantInt::get(Add->getType(), 1));
3736 }
3737 break; // (X != 13 & X != 15) -> no change
3738 }
3739 break;
3740 case ICmpInst::ICMP_ULT:
3741 switch (RHSCC) {
3742 default: assert(0 && "Unknown integer condition code!");
3743 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3744 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3745 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3746 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3747 break;
3748 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3749 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3750 return ReplaceInstUsesWith(I, LHS);
3751 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3752 break;
3753 }
3754 break;
3755 case ICmpInst::ICMP_SLT:
3756 switch (RHSCC) {
3757 default: assert(0 && "Unknown integer condition code!");
3758 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3759 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3760 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3761 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3762 break;
3763 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3764 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3765 return ReplaceInstUsesWith(I, LHS);
3766 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3767 break;
3768 }
3769 break;
3770 case ICmpInst::ICMP_UGT:
3771 switch (RHSCC) {
3772 default: assert(0 && "Unknown integer condition code!");
3773 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3774 return ReplaceInstUsesWith(I, LHS);
3775 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3776 return ReplaceInstUsesWith(I, RHS);
3777 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3778 break;
3779 case ICmpInst::ICMP_NE:
3780 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3781 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3782 break; // (X u> 13 & X != 15) -> no change
3783 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3784 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3785 true, I);
3786 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3787 break;
3788 }
3789 break;
3790 case ICmpInst::ICMP_SGT:
3791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003793 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003794 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3795 return ReplaceInstUsesWith(I, RHS);
3796 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3797 break;
3798 case ICmpInst::ICMP_NE:
3799 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3800 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3801 break; // (X s> 13 & X != 15) -> no change
3802 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3803 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3804 true, I);
3805 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3806 break;
3807 }
3808 break;
3809 }
3810 }
3811 }
3812
3813 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3814 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3815 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3816 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3817 const Type *SrcTy = Op0C->getOperand(0)->getType();
3818 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3819 // Only do this if the casts both really cause code to be generated.
3820 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3821 I.getType(), TD) &&
3822 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3823 I.getType(), TD)) {
3824 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3825 Op1C->getOperand(0),
3826 I.getName());
3827 InsertNewInstBefore(NewOp, I);
3828 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3829 }
3830 }
3831
3832 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3833 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3834 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3835 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3836 SI0->getOperand(1) == SI1->getOperand(1) &&
3837 (SI0->hasOneUse() || SI1->hasOneUse())) {
3838 Instruction *NewOp =
3839 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3840 SI1->getOperand(0),
3841 SI0->getName()), I);
3842 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3843 SI1->getOperand(1));
3844 }
3845 }
3846
Chris Lattner91882432007-10-24 05:38:08 +00003847 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3848 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3849 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3850 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3851 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3852 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3853 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3854 // If either of the constants are nans, then the whole thing returns
3855 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003856 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003857 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3858 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3859 RHS->getOperand(0));
3860 }
3861 }
3862 }
3863
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003864 return Changed ? &I : 0;
3865}
3866
3867/// CollectBSwapParts - Look to see if the specified value defines a single byte
3868/// in the result. If it does, and if the specified byte hasn't been filled in
3869/// yet, fill it in and return false.
3870static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3871 Instruction *I = dyn_cast<Instruction>(V);
3872 if (I == 0) return true;
3873
3874 // If this is an or instruction, it is an inner node of the bswap.
3875 if (I->getOpcode() == Instruction::Or)
3876 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3877 CollectBSwapParts(I->getOperand(1), ByteValues);
3878
3879 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3880 // If this is a shift by a constant int, and it is "24", then its operand
3881 // defines a byte. We only handle unsigned types here.
3882 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3883 // Not shifting the entire input by N-1 bytes?
3884 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3885 8*(ByteValues.size()-1))
3886 return true;
3887
3888 unsigned DestNo;
3889 if (I->getOpcode() == Instruction::Shl) {
3890 // X << 24 defines the top byte with the lowest of the input bytes.
3891 DestNo = ByteValues.size()-1;
3892 } else {
3893 // X >>u 24 defines the low byte with the highest of the input bytes.
3894 DestNo = 0;
3895 }
3896
3897 // If the destination byte value is already defined, the values are or'd
3898 // together, which isn't a bswap (unless it's an or of the same bits).
3899 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3900 return true;
3901 ByteValues[DestNo] = I->getOperand(0);
3902 return false;
3903 }
3904
3905 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3906 // don't have this.
3907 Value *Shift = 0, *ShiftLHS = 0;
3908 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3909 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3910 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3911 return true;
3912 Instruction *SI = cast<Instruction>(Shift);
3913
3914 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3915 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3916 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3917 return true;
3918
3919 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3920 unsigned DestByte;
3921 if (AndAmt->getValue().getActiveBits() > 64)
3922 return true;
3923 uint64_t AndAmtVal = AndAmt->getZExtValue();
3924 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3925 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3926 break;
3927 // Unknown mask for bswap.
3928 if (DestByte == ByteValues.size()) return true;
3929
3930 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3931 unsigned SrcByte;
3932 if (SI->getOpcode() == Instruction::Shl)
3933 SrcByte = DestByte - ShiftBytes;
3934 else
3935 SrcByte = DestByte + ShiftBytes;
3936
3937 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3938 if (SrcByte != ByteValues.size()-DestByte-1)
3939 return true;
3940
3941 // If the destination byte value is already defined, the values are or'd
3942 // together, which isn't a bswap (unless it's an or of the same bits).
3943 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3944 return true;
3945 ByteValues[DestByte] = SI->getOperand(0);
3946 return false;
3947}
3948
3949/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3950/// If so, insert the new bswap intrinsic and return it.
3951Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3952 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3953 if (!ITy || ITy->getBitWidth() % 16)
3954 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3955
3956 /// ByteValues - For each byte of the result, we keep track of which value
3957 /// defines each byte.
3958 SmallVector<Value*, 8> ByteValues;
3959 ByteValues.resize(ITy->getBitWidth()/8);
3960
3961 // Try to find all the pieces corresponding to the bswap.
3962 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3963 CollectBSwapParts(I.getOperand(1), ByteValues))
3964 return 0;
3965
3966 // Check to see if all of the bytes come from the same value.
3967 Value *V = ByteValues[0];
3968 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3969
3970 // Check to make sure that all of the bytes come from the same value.
3971 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3972 if (ByteValues[i] != V)
3973 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003974 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003975 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003976 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003977 return new CallInst(F, V);
3978}
3979
3980
3981Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3982 bool Changed = SimplifyCommutative(I);
3983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3984
3985 if (isa<UndefValue>(Op1)) // X | undef -> -1
3986 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3987
3988 // or X, X = X
3989 if (Op0 == Op1)
3990 return ReplaceInstUsesWith(I, Op0);
3991
3992 // See if we can simplify any instructions used by the instruction whose sole
3993 // purpose is to compute bits we don't care about.
3994 if (!isa<VectorType>(I.getType())) {
3995 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3996 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3997 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3998 KnownZero, KnownOne))
3999 return &I;
4000 } else if (isa<ConstantAggregateZero>(Op1)) {
4001 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4002 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4003 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4004 return ReplaceInstUsesWith(I, I.getOperand(1));
4005 }
4006
4007
4008
4009 // or X, -1 == -1
4010 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4011 ConstantInt *C1 = 0; Value *X = 0;
4012 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4013 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4014 Instruction *Or = BinaryOperator::createOr(X, RHS);
4015 InsertNewInstBefore(Or, I);
4016 Or->takeName(Op0);
4017 return BinaryOperator::createAnd(Or,
4018 ConstantInt::get(RHS->getValue() | C1->getValue()));
4019 }
4020
4021 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4022 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4023 Instruction *Or = BinaryOperator::createOr(X, RHS);
4024 InsertNewInstBefore(Or, I);
4025 Or->takeName(Op0);
4026 return BinaryOperator::createXor(Or,
4027 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4028 }
4029
4030 // Try to fold constant and into select arguments.
4031 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4032 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4033 return R;
4034 if (isa<PHINode>(Op0))
4035 if (Instruction *NV = FoldOpIntoPhi(I))
4036 return NV;
4037 }
4038
4039 Value *A = 0, *B = 0;
4040 ConstantInt *C1 = 0, *C2 = 0;
4041
4042 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4043 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4044 return ReplaceInstUsesWith(I, Op1);
4045 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4046 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4047 return ReplaceInstUsesWith(I, Op0);
4048
4049 // (A | B) | C and A | (B | C) -> bswap if possible.
4050 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4051 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4052 match(Op1, m_Or(m_Value(), m_Value())) ||
4053 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4054 match(Op1, m_Shift(m_Value(), m_Value())))) {
4055 if (Instruction *BSwap = MatchBSwap(I))
4056 return BSwap;
4057 }
4058
4059 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4060 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4061 MaskedValueIsZero(Op1, C1->getValue())) {
4062 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4063 InsertNewInstBefore(NOr, I);
4064 NOr->takeName(Op0);
4065 return BinaryOperator::createXor(NOr, C1);
4066 }
4067
4068 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4069 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4070 MaskedValueIsZero(Op0, C1->getValue())) {
4071 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4072 InsertNewInstBefore(NOr, I);
4073 NOr->takeName(Op0);
4074 return BinaryOperator::createXor(NOr, C1);
4075 }
4076
4077 // (A & C)|(B & D)
4078 Value *C = 0, *D = 0;
4079 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4080 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4081 Value *V1 = 0, *V2 = 0, *V3 = 0;
4082 C1 = dyn_cast<ConstantInt>(C);
4083 C2 = dyn_cast<ConstantInt>(D);
4084 if (C1 && C2) { // (A & C1)|(B & C2)
4085 // If we have: ((V + N) & C1) | (V & C2)
4086 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4087 // replace with V+N.
4088 if (C1->getValue() == ~C2->getValue()) {
4089 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4090 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4091 // Add commutes, try both ways.
4092 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4093 return ReplaceInstUsesWith(I, A);
4094 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4095 return ReplaceInstUsesWith(I, A);
4096 }
4097 // Or commutes, try both ways.
4098 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4099 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4100 // Add commutes, try both ways.
4101 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4102 return ReplaceInstUsesWith(I, B);
4103 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4104 return ReplaceInstUsesWith(I, B);
4105 }
4106 }
4107 V1 = 0; V2 = 0; V3 = 0;
4108 }
4109
4110 // Check to see if we have any common things being and'ed. If so, find the
4111 // terms for V1 & (V2|V3).
4112 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4113 if (A == B) // (A & C)|(A & D) == A & (C|D)
4114 V1 = A, V2 = C, V3 = D;
4115 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4116 V1 = A, V2 = B, V3 = C;
4117 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4118 V1 = C, V2 = A, V3 = D;
4119 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4120 V1 = C, V2 = A, V3 = B;
4121
4122 if (V1) {
4123 Value *Or =
4124 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4125 return BinaryOperator::createAnd(V1, Or);
4126 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004127 }
4128 }
4129
4130 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4131 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4132 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4133 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4134 SI0->getOperand(1) == SI1->getOperand(1) &&
4135 (SI0->hasOneUse() || SI1->hasOneUse())) {
4136 Instruction *NewOp =
4137 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4138 SI1->getOperand(0),
4139 SI0->getName()), I);
4140 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4141 SI1->getOperand(1));
4142 }
4143 }
4144
4145 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4146 if (A == Op1) // ~A | A == -1
4147 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4148 } else {
4149 A = 0;
4150 }
4151 // Note, A is still live here!
4152 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4153 if (Op0 == B)
4154 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4155
4156 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4157 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4158 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4159 I.getName()+".demorgan"), I);
4160 return BinaryOperator::createNot(And);
4161 }
4162 }
4163
4164 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4165 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4166 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4167 return R;
4168
4169 Value *LHSVal, *RHSVal;
4170 ConstantInt *LHSCst, *RHSCst;
4171 ICmpInst::Predicate LHSCC, RHSCC;
4172 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4173 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4174 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4175 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4176 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4177 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4178 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4179 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4180 // We can't fold (ugt x, C) | (sgt x, C2).
4181 PredicatesFoldable(LHSCC, RHSCC)) {
4182 // Ensure that the larger constant is on the RHS.
4183 ICmpInst *LHS = cast<ICmpInst>(Op0);
4184 bool NeedsSwap;
4185 if (ICmpInst::isSignedPredicate(LHSCC))
4186 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4187 else
4188 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4189
4190 if (NeedsSwap) {
4191 std::swap(LHS, RHS);
4192 std::swap(LHSCst, RHSCst);
4193 std::swap(LHSCC, RHSCC);
4194 }
4195
4196 // At this point, we know we have have two icmp instructions
4197 // comparing a value against two constants and or'ing the result
4198 // together. Because of the above check, we know that we only have
4199 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4200 // FoldICmpLogical check above), that the two constants are not
4201 // equal.
4202 assert(LHSCst != RHSCst && "Compares not folded above?");
4203
4204 switch (LHSCC) {
4205 default: assert(0 && "Unknown integer condition code!");
4206 case ICmpInst::ICMP_EQ:
4207 switch (RHSCC) {
4208 default: assert(0 && "Unknown integer condition code!");
4209 case ICmpInst::ICMP_EQ:
4210 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4211 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4212 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4213 LHSVal->getName()+".off");
4214 InsertNewInstBefore(Add, I);
4215 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4216 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4217 }
4218 break; // (X == 13 | X == 15) -> no change
4219 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4220 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4221 break;
4222 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4223 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4224 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4225 return ReplaceInstUsesWith(I, RHS);
4226 }
4227 break;
4228 case ICmpInst::ICMP_NE:
4229 switch (RHSCC) {
4230 default: assert(0 && "Unknown integer condition code!");
4231 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4232 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4233 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4234 return ReplaceInstUsesWith(I, LHS);
4235 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4236 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4237 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4238 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4239 }
4240 break;
4241 case ICmpInst::ICMP_ULT:
4242 switch (RHSCC) {
4243 default: assert(0 && "Unknown integer condition code!");
4244 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4245 break;
4246 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004247 // If RHSCst is [us]MAXINT, it is always false. Not handling
4248 // this can cause overflow.
4249 if (RHSCst->isMaxValue(false))
4250 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4252 false, I);
4253 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4254 break;
4255 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4256 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4257 return ReplaceInstUsesWith(I, RHS);
4258 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4259 break;
4260 }
4261 break;
4262 case ICmpInst::ICMP_SLT:
4263 switch (RHSCC) {
4264 default: assert(0 && "Unknown integer condition code!");
4265 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4266 break;
4267 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004268 // If RHSCst is [us]MAXINT, it is always false. Not handling
4269 // this can cause overflow.
4270 if (RHSCst->isMaxValue(true))
4271 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004272 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4273 false, I);
4274 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4275 break;
4276 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4277 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4278 return ReplaceInstUsesWith(I, RHS);
4279 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4280 break;
4281 }
4282 break;
4283 case ICmpInst::ICMP_UGT:
4284 switch (RHSCC) {
4285 default: assert(0 && "Unknown integer condition code!");
4286 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4287 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4288 return ReplaceInstUsesWith(I, LHS);
4289 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4290 break;
4291 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4292 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4293 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4294 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4295 break;
4296 }
4297 break;
4298 case ICmpInst::ICMP_SGT:
4299 switch (RHSCC) {
4300 default: assert(0 && "Unknown integer condition code!");
4301 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4302 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4303 return ReplaceInstUsesWith(I, LHS);
4304 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4305 break;
4306 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4307 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4308 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4309 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4310 break;
4311 }
4312 break;
4313 }
4314 }
4315 }
4316
4317 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004318 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004319 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4320 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4321 const Type *SrcTy = Op0C->getOperand(0)->getType();
4322 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4323 // Only do this if the casts both really cause code to be generated.
4324 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4325 I.getType(), TD) &&
4326 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4327 I.getType(), TD)) {
4328 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4329 Op1C->getOperand(0),
4330 I.getName());
4331 InsertNewInstBefore(NewOp, I);
4332 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4333 }
4334 }
Chris Lattner91882432007-10-24 05:38:08 +00004335 }
4336
4337
4338 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4339 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4340 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4341 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004342 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4343 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004344 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4345 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4346 // If either of the constants are nans, then the whole thing returns
4347 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004348 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004349 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4350
4351 // Otherwise, no need to compare the two constants, compare the
4352 // rest.
4353 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4354 RHS->getOperand(0));
4355 }
4356 }
4357 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358
4359 return Changed ? &I : 0;
4360}
4361
4362// XorSelf - Implements: X ^ X --> 0
4363struct XorSelf {
4364 Value *RHS;
4365 XorSelf(Value *rhs) : RHS(rhs) {}
4366 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4367 Instruction *apply(BinaryOperator &Xor) const {
4368 return &Xor;
4369 }
4370};
4371
4372
4373Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4374 bool Changed = SimplifyCommutative(I);
4375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4376
4377 if (isa<UndefValue>(Op1))
4378 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4379
4380 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4381 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004382 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4384 }
4385
4386 // See if we can simplify any instructions used by the instruction whose sole
4387 // purpose is to compute bits we don't care about.
4388 if (!isa<VectorType>(I.getType())) {
4389 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4390 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4391 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4392 KnownZero, KnownOne))
4393 return &I;
4394 } else if (isa<ConstantAggregateZero>(Op1)) {
4395 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4396 }
4397
4398 // Is this a ~ operation?
4399 if (Value *NotOp = dyn_castNotVal(&I)) {
4400 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4401 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4402 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4403 if (Op0I->getOpcode() == Instruction::And ||
4404 Op0I->getOpcode() == Instruction::Or) {
4405 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4406 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4407 Instruction *NotY =
4408 BinaryOperator::createNot(Op0I->getOperand(1),
4409 Op0I->getOperand(1)->getName()+".not");
4410 InsertNewInstBefore(NotY, I);
4411 if (Op0I->getOpcode() == Instruction::And)
4412 return BinaryOperator::createOr(Op0NotVal, NotY);
4413 else
4414 return BinaryOperator::createAnd(Op0NotVal, NotY);
4415 }
4416 }
4417 }
4418 }
4419
4420
4421 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004422 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4423 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4424 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425 return new ICmpInst(ICI->getInversePredicate(),
4426 ICI->getOperand(0), ICI->getOperand(1));
4427
Nick Lewycky1405e922007-08-06 20:04:16 +00004428 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4429 return new FCmpInst(FCI->getInversePredicate(),
4430 FCI->getOperand(0), FCI->getOperand(1));
4431 }
4432
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4434 // ~(c-X) == X-c-1 == X+(-c-1)
4435 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4436 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4437 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4438 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4439 ConstantInt::get(I.getType(), 1));
4440 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4441 }
4442
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004443 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004444 if (Op0I->getOpcode() == Instruction::Add) {
4445 // ~(X-c) --> (-c-1)-X
4446 if (RHS->isAllOnesValue()) {
4447 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4448 return BinaryOperator::createSub(
4449 ConstantExpr::getSub(NegOp0CI,
4450 ConstantInt::get(I.getType(), 1)),
4451 Op0I->getOperand(0));
4452 } else if (RHS->getValue().isSignBit()) {
4453 // (X + C) ^ signbit -> (X + C + signbit)
4454 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4455 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4456
4457 }
4458 } else if (Op0I->getOpcode() == Instruction::Or) {
4459 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4460 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4461 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4462 // Anything in both C1 and C2 is known to be zero, remove it from
4463 // NewRHS.
4464 Constant *CommonBits = And(Op0CI, RHS);
4465 NewRHS = ConstantExpr::getAnd(NewRHS,
4466 ConstantExpr::getNot(CommonBits));
4467 AddToWorkList(Op0I);
4468 I.setOperand(0, Op0I->getOperand(0));
4469 I.setOperand(1, NewRHS);
4470 return &I;
4471 }
4472 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004473 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004474 }
4475
4476 // Try to fold constant and into select arguments.
4477 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4478 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4479 return R;
4480 if (isa<PHINode>(Op0))
4481 if (Instruction *NV = FoldOpIntoPhi(I))
4482 return NV;
4483 }
4484
4485 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4486 if (X == Op1)
4487 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4488
4489 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4490 if (X == Op0)
4491 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4492
4493
4494 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4495 if (Op1I) {
4496 Value *A, *B;
4497 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4498 if (A == Op0) { // B^(B|A) == (A|B)^B
4499 Op1I->swapOperands();
4500 I.swapOperands();
4501 std::swap(Op0, Op1);
4502 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4503 I.swapOperands(); // Simplified below.
4504 std::swap(Op0, Op1);
4505 }
4506 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4507 if (Op0 == A) // A^(A^B) == B
4508 return ReplaceInstUsesWith(I, B);
4509 else if (Op0 == B) // A^(B^A) == B
4510 return ReplaceInstUsesWith(I, A);
4511 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4512 if (A == Op0) { // A^(A&B) -> A^(B&A)
4513 Op1I->swapOperands();
4514 std::swap(A, B);
4515 }
4516 if (B == Op0) { // A^(B&A) -> (B&A)^A
4517 I.swapOperands(); // Simplified below.
4518 std::swap(Op0, Op1);
4519 }
4520 }
4521 }
4522
4523 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4524 if (Op0I) {
4525 Value *A, *B;
4526 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4527 if (A == Op1) // (B|A)^B == (A|B)^B
4528 std::swap(A, B);
4529 if (B == Op1) { // (A|B)^B == A & ~B
4530 Instruction *NotB =
4531 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4532 return BinaryOperator::createAnd(A, NotB);
4533 }
4534 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4535 if (Op1 == A) // (A^B)^A == B
4536 return ReplaceInstUsesWith(I, B);
4537 else if (Op1 == B) // (B^A)^A == B
4538 return ReplaceInstUsesWith(I, A);
4539 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4540 if (A == Op1) // (A&B)^A -> (B&A)^A
4541 std::swap(A, B);
4542 if (B == Op1 && // (B&A)^A == ~B & A
4543 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4544 Instruction *N =
4545 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4546 return BinaryOperator::createAnd(N, Op1);
4547 }
4548 }
4549 }
4550
4551 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4552 if (Op0I && Op1I && Op0I->isShift() &&
4553 Op0I->getOpcode() == Op1I->getOpcode() &&
4554 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4555 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4556 Instruction *NewOp =
4557 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4558 Op1I->getOperand(0),
4559 Op0I->getName()), I);
4560 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4561 Op1I->getOperand(1));
4562 }
4563
4564 if (Op0I && Op1I) {
4565 Value *A, *B, *C, *D;
4566 // (A & B)^(A | B) -> A ^ B
4567 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4568 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4569 if ((A == C && B == D) || (A == D && B == C))
4570 return BinaryOperator::createXor(A, B);
4571 }
4572 // (A | B)^(A & B) -> A ^ B
4573 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4574 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4575 if ((A == C && B == D) || (A == D && B == C))
4576 return BinaryOperator::createXor(A, B);
4577 }
4578
4579 // (A & B)^(C & D)
4580 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4581 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4582 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4583 // (X & Y)^(X & Y) -> (Y^Z) & X
4584 Value *X = 0, *Y = 0, *Z = 0;
4585 if (A == C)
4586 X = A, Y = B, Z = D;
4587 else if (A == D)
4588 X = A, Y = B, Z = C;
4589 else if (B == C)
4590 X = B, Y = A, Z = D;
4591 else if (B == D)
4592 X = B, Y = A, Z = C;
4593
4594 if (X) {
4595 Instruction *NewOp =
4596 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4597 return BinaryOperator::createAnd(NewOp, X);
4598 }
4599 }
4600 }
4601
4602 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4603 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4604 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4605 return R;
4606
4607 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004608 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004609 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4610 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4611 const Type *SrcTy = Op0C->getOperand(0)->getType();
4612 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4613 // Only do this if the casts both really cause code to be generated.
4614 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4615 I.getType(), TD) &&
4616 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4617 I.getType(), TD)) {
4618 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4619 Op1C->getOperand(0),
4620 I.getName());
4621 InsertNewInstBefore(NewOp, I);
4622 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4623 }
4624 }
Chris Lattner91882432007-10-24 05:38:08 +00004625 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004626 return Changed ? &I : 0;
4627}
4628
4629/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4630/// overflowed for this type.
4631static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4632 ConstantInt *In2, bool IsSigned = false) {
4633 Result = cast<ConstantInt>(Add(In1, In2));
4634
4635 if (IsSigned)
4636 if (In2->getValue().isNegative())
4637 return Result->getValue().sgt(In1->getValue());
4638 else
4639 return Result->getValue().slt(In1->getValue());
4640 else
4641 return Result->getValue().ult(In1->getValue());
4642}
4643
4644/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4645/// code necessary to compute the offset from the base pointer (without adding
4646/// in the base pointer). Return the result as a signed integer of intptr size.
4647static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4648 TargetData &TD = IC.getTargetData();
4649 gep_type_iterator GTI = gep_type_begin(GEP);
4650 const Type *IntPtrTy = TD.getIntPtrType();
4651 Value *Result = Constant::getNullValue(IntPtrTy);
4652
4653 // Build a mask for high order bits.
4654 unsigned IntPtrWidth = TD.getPointerSize()*8;
4655 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4656
4657 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4658 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004659 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004660 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4661 if (OpC->isZero()) continue;
4662
4663 // Handle a struct index, which adds its field offset to the pointer.
4664 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4665 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4666
4667 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4668 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4669 else
4670 Result = IC.InsertNewInstBefore(
4671 BinaryOperator::createAdd(Result,
4672 ConstantInt::get(IntPtrTy, Size),
4673 GEP->getName()+".offs"), I);
4674 continue;
4675 }
4676
4677 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4678 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4679 Scale = ConstantExpr::getMul(OC, Scale);
4680 if (Constant *RC = dyn_cast<Constant>(Result))
4681 Result = ConstantExpr::getAdd(RC, Scale);
4682 else {
4683 // Emit an add instruction.
4684 Result = IC.InsertNewInstBefore(
4685 BinaryOperator::createAdd(Result, Scale,
4686 GEP->getName()+".offs"), I);
4687 }
4688 continue;
4689 }
4690 // Convert to correct type.
4691 if (Op->getType() != IntPtrTy) {
4692 if (Constant *OpC = dyn_cast<Constant>(Op))
4693 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4694 else
4695 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4696 Op->getName()+".c"), I);
4697 }
4698 if (Size != 1) {
4699 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4700 if (Constant *OpC = dyn_cast<Constant>(Op))
4701 Op = ConstantExpr::getMul(OpC, Scale);
4702 else // We'll let instcombine(mul) convert this to a shl if possible.
4703 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4704 GEP->getName()+".idx"), I);
4705 }
4706
4707 // Emit an add instruction.
4708 if (isa<Constant>(Op) && isa<Constant>(Result))
4709 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4710 cast<Constant>(Result));
4711 else
4712 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4713 GEP->getName()+".offs"), I);
4714 }
4715 return Result;
4716}
4717
4718/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4719/// else. At this point we know that the GEP is on the LHS of the comparison.
4720Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4721 ICmpInst::Predicate Cond,
4722 Instruction &I) {
4723 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4724
4725 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4726 if (isa<PointerType>(CI->getOperand(0)->getType()))
4727 RHS = CI->getOperand(0);
4728
4729 Value *PtrBase = GEPLHS->getOperand(0);
4730 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004731 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4732 // This transformation is valid because we know pointers can't overflow.
4733 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4735 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004736 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4737 // If the base pointers are different, but the indices are the same, just
4738 // compare the base pointer.
4739 if (PtrBase != GEPRHS->getOperand(0)) {
4740 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4741 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4742 GEPRHS->getOperand(0)->getType();
4743 if (IndicesTheSame)
4744 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4745 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4746 IndicesTheSame = false;
4747 break;
4748 }
4749
4750 // If all indices are the same, just compare the base pointers.
4751 if (IndicesTheSame)
4752 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4753 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4754
4755 // Otherwise, the base pointers are different and the indices are
4756 // different, bail out.
4757 return 0;
4758 }
4759
4760 // If one of the GEPs has all zero indices, recurse.
4761 bool AllZeros = true;
4762 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4763 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4764 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4765 AllZeros = false;
4766 break;
4767 }
4768 if (AllZeros)
4769 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4770 ICmpInst::getSwappedPredicate(Cond), I);
4771
4772 // If the other GEP has all zero indices, recurse.
4773 AllZeros = true;
4774 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4775 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4776 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4777 AllZeros = false;
4778 break;
4779 }
4780 if (AllZeros)
4781 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4782
4783 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4784 // If the GEPs only differ by one index, compare it.
4785 unsigned NumDifferences = 0; // Keep track of # differences.
4786 unsigned DiffOperand = 0; // The operand that differs.
4787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4789 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4790 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4791 // Irreconcilable differences.
4792 NumDifferences = 2;
4793 break;
4794 } else {
4795 if (NumDifferences++) break;
4796 DiffOperand = i;
4797 }
4798 }
4799
4800 if (NumDifferences == 0) // SAME GEP?
4801 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004802 ConstantInt::get(Type::Int1Ty,
4803 isTrueWhenEqual(Cond)));
4804
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004805 else if (NumDifferences == 1) {
4806 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4807 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4808 // Make sure we do a signed comparison here.
4809 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4810 }
4811 }
4812
4813 // Only lower this if the icmp is the only user of the GEP or if we expect
4814 // the result to fold to a constant!
4815 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4816 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4817 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4818 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4819 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4820 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4821 }
4822 }
4823 return 0;
4824}
4825
4826Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4827 bool Changed = SimplifyCompare(I);
4828 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4829
4830 // Fold trivial predicates.
4831 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4832 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4833 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4834 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4835
4836 // Simplify 'fcmp pred X, X'
4837 if (Op0 == Op1) {
4838 switch (I.getPredicate()) {
4839 default: assert(0 && "Unknown predicate!");
4840 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4841 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4842 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4843 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4844 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4845 case FCmpInst::FCMP_OLT: // True if ordered and less than
4846 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4847 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4848
4849 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4850 case FCmpInst::FCMP_ULT: // True if unordered or less than
4851 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4852 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4853 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4854 I.setPredicate(FCmpInst::FCMP_UNO);
4855 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4856 return &I;
4857
4858 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4859 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4860 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4861 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4862 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4863 I.setPredicate(FCmpInst::FCMP_ORD);
4864 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4865 return &I;
4866 }
4867 }
4868
4869 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4870 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4871
4872 // Handle fcmp with constant RHS
4873 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4874 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4875 switch (LHSI->getOpcode()) {
4876 case Instruction::PHI:
4877 if (Instruction *NV = FoldOpIntoPhi(I))
4878 return NV;
4879 break;
4880 case Instruction::Select:
4881 // If either operand of the select is a constant, we can fold the
4882 // comparison into the select arms, which will cause one to be
4883 // constant folded and the select turned into a bitwise or.
4884 Value *Op1 = 0, *Op2 = 0;
4885 if (LHSI->hasOneUse()) {
4886 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4887 // Fold the known value into the constant operand.
4888 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4889 // Insert a new FCmp of the other select operand.
4890 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4891 LHSI->getOperand(2), RHSC,
4892 I.getName()), I);
4893 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4894 // Fold the known value into the constant operand.
4895 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4896 // Insert a new FCmp of the other select operand.
4897 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4898 LHSI->getOperand(1), RHSC,
4899 I.getName()), I);
4900 }
4901 }
4902
4903 if (Op1)
4904 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4905 break;
4906 }
4907 }
4908
4909 return Changed ? &I : 0;
4910}
4911
4912Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4913 bool Changed = SimplifyCompare(I);
4914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4915 const Type *Ty = Op0->getType();
4916
4917 // icmp X, X
4918 if (Op0 == Op1)
4919 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4920 isTrueWhenEqual(I)));
4921
4922 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4923 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00004924
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004925 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4926 // addresses never equal each other! We already know that Op0 != Op1.
4927 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4928 isa<ConstantPointerNull>(Op0)) &&
4929 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4930 isa<ConstantPointerNull>(Op1)))
4931 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4932 !isTrueWhenEqual(I)));
4933
4934 // icmp's with boolean values can always be turned into bitwise operations
4935 if (Ty == Type::Int1Ty) {
4936 switch (I.getPredicate()) {
4937 default: assert(0 && "Invalid icmp instruction!");
4938 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4939 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4940 InsertNewInstBefore(Xor, I);
4941 return BinaryOperator::createNot(Xor);
4942 }
4943 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4944 return BinaryOperator::createXor(Op0, Op1);
4945
4946 case ICmpInst::ICMP_UGT:
4947 case ICmpInst::ICMP_SGT:
4948 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4949 // FALL THROUGH
4950 case ICmpInst::ICMP_ULT:
4951 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4952 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4953 InsertNewInstBefore(Not, I);
4954 return BinaryOperator::createAnd(Not, Op1);
4955 }
4956 case ICmpInst::ICMP_UGE:
4957 case ICmpInst::ICMP_SGE:
4958 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4959 // FALL THROUGH
4960 case ICmpInst::ICMP_ULE:
4961 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4962 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4963 InsertNewInstBefore(Not, I);
4964 return BinaryOperator::createOr(Not, Op1);
4965 }
4966 }
4967 }
4968
4969 // See if we are doing a comparison between a constant and an instruction that
4970 // can be folded into the comparison.
4971 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00004972 Value *A, *B;
4973
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00004974 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4975 if (I.isEquality() && CI->isNullValue() &&
4976 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4977 // (icmp cond A B) if cond is equality
4978 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00004979 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00004980
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004981 switch (I.getPredicate()) {
4982 default: break;
4983 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4984 if (CI->isMinValue(false))
4985 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4986 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4987 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4988 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4989 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4990 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4991 if (CI->isMinValue(true))
4992 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4993 ConstantInt::getAllOnesValue(Op0->getType()));
4994
4995 break;
4996
4997 case ICmpInst::ICMP_SLT:
4998 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4999 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5000 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5001 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5002 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5003 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5004 break;
5005
5006 case ICmpInst::ICMP_UGT:
5007 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5008 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5009 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5010 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5011 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5012 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5013
5014 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5015 if (CI->isMaxValue(true))
5016 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5017 ConstantInt::getNullValue(Op0->getType()));
5018 break;
5019
5020 case ICmpInst::ICMP_SGT:
5021 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5022 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5023 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5024 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5025 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5026 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5027 break;
5028
5029 case ICmpInst::ICMP_ULE:
5030 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5031 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5032 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5033 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5034 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5035 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5036 break;
5037
5038 case ICmpInst::ICMP_SLE:
5039 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5040 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5041 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5042 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5043 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5044 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5045 break;
5046
5047 case ICmpInst::ICMP_UGE:
5048 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5049 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5050 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5051 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5052 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5053 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5054 break;
5055
5056 case ICmpInst::ICMP_SGE:
5057 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5058 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5059 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5060 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5061 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5062 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5063 break;
5064 }
5065
5066 // If we still have a icmp le or icmp ge instruction, turn it into the
5067 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5068 // already been handled above, this requires little checking.
5069 //
5070 switch (I.getPredicate()) {
5071 default: break;
5072 case ICmpInst::ICMP_ULE:
5073 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5074 case ICmpInst::ICMP_SLE:
5075 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5076 case ICmpInst::ICMP_UGE:
5077 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5078 case ICmpInst::ICMP_SGE:
5079 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5080 }
5081
5082 // See if we can fold the comparison based on bits known to be zero or one
5083 // in the input. If this comparison is a normal comparison, it demands all
5084 // bits, if it is a sign bit comparison, it only demands the sign bit.
5085
5086 bool UnusedBit;
5087 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5088
5089 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5090 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5091 if (SimplifyDemandedBits(Op0,
5092 isSignBit ? APInt::getSignBit(BitWidth)
5093 : APInt::getAllOnesValue(BitWidth),
5094 KnownZero, KnownOne, 0))
5095 return &I;
5096
5097 // Given the known and unknown bits, compute a range that the LHS could be
5098 // in.
5099 if ((KnownOne | KnownZero) != 0) {
5100 // Compute the Min, Max and RHS values based on the known bits. For the
5101 // EQ and NE we use unsigned values.
5102 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5103 const APInt& RHSVal = CI->getValue();
5104 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5105 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5106 Max);
5107 } else {
5108 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5109 Max);
5110 }
5111 switch (I.getPredicate()) { // LE/GE have been folded already.
5112 default: assert(0 && "Unknown icmp opcode!");
5113 case ICmpInst::ICMP_EQ:
5114 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5115 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5116 break;
5117 case ICmpInst::ICMP_NE:
5118 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5119 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5120 break;
5121 case ICmpInst::ICMP_ULT:
5122 if (Max.ult(RHSVal))
5123 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5124 if (Min.uge(RHSVal))
5125 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5126 break;
5127 case ICmpInst::ICMP_UGT:
5128 if (Min.ugt(RHSVal))
5129 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5130 if (Max.ule(RHSVal))
5131 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5132 break;
5133 case ICmpInst::ICMP_SLT:
5134 if (Max.slt(RHSVal))
5135 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5136 if (Min.sgt(RHSVal))
5137 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5138 break;
5139 case ICmpInst::ICMP_SGT:
5140 if (Min.sgt(RHSVal))
5141 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5142 if (Max.sle(RHSVal))
5143 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5144 break;
5145 }
5146 }
5147
5148 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5149 // instruction, see if that instruction also has constants so that the
5150 // instruction can be folded into the icmp
5151 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5152 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5153 return Res;
5154 }
5155
5156 // Handle icmp with constant (but not simple integer constant) RHS
5157 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5158 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5159 switch (LHSI->getOpcode()) {
5160 case Instruction::GetElementPtr:
5161 if (RHSC->isNullValue()) {
5162 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5163 bool isAllZeros = true;
5164 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5165 if (!isa<Constant>(LHSI->getOperand(i)) ||
5166 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5167 isAllZeros = false;
5168 break;
5169 }
5170 if (isAllZeros)
5171 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5172 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5173 }
5174 break;
5175
5176 case Instruction::PHI:
5177 if (Instruction *NV = FoldOpIntoPhi(I))
5178 return NV;
5179 break;
5180 case Instruction::Select: {
5181 // If either operand of the select is a constant, we can fold the
5182 // comparison into the select arms, which will cause one to be
5183 // constant folded and the select turned into a bitwise or.
5184 Value *Op1 = 0, *Op2 = 0;
5185 if (LHSI->hasOneUse()) {
5186 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5187 // Fold the known value into the constant operand.
5188 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5189 // Insert a new ICmp of the other select operand.
5190 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5191 LHSI->getOperand(2), RHSC,
5192 I.getName()), I);
5193 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5194 // Fold the known value into the constant operand.
5195 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5196 // Insert a new ICmp of the other select operand.
5197 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5198 LHSI->getOperand(1), RHSC,
5199 I.getName()), I);
5200 }
5201 }
5202
5203 if (Op1)
5204 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5205 break;
5206 }
5207 case Instruction::Malloc:
5208 // If we have (malloc != null), and if the malloc has a single use, we
5209 // can assume it is successful and remove the malloc.
5210 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5211 AddToWorkList(LHSI);
5212 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5213 !isTrueWhenEqual(I)));
5214 }
5215 break;
5216 }
5217 }
5218
5219 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5220 if (User *GEP = dyn_castGetElementPtr(Op0))
5221 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5222 return NI;
5223 if (User *GEP = dyn_castGetElementPtr(Op1))
5224 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5225 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5226 return NI;
5227
5228 // Test to see if the operands of the icmp are casted versions of other
5229 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5230 // now.
5231 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5232 if (isa<PointerType>(Op0->getType()) &&
5233 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5234 // We keep moving the cast from the left operand over to the right
5235 // operand, where it can often be eliminated completely.
5236 Op0 = CI->getOperand(0);
5237
5238 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5239 // so eliminate it as well.
5240 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5241 Op1 = CI2->getOperand(0);
5242
5243 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005244 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005245 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5246 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5247 } else {
5248 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005249 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005250 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005251 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005252 return new ICmpInst(I.getPredicate(), Op0, Op1);
5253 }
5254 }
5255
5256 if (isa<CastInst>(Op0)) {
5257 // Handle the special case of: icmp (cast bool to X), <cst>
5258 // This comes up when you have code like
5259 // int X = A < B;
5260 // if (X) ...
5261 // For generality, we handle any zero-extension of any operand comparison
5262 // with a constant or another cast from the same type.
5263 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5264 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5265 return R;
5266 }
5267
5268 if (I.isEquality()) {
5269 Value *A, *B, *C, *D;
5270 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5271 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5272 Value *OtherVal = A == Op1 ? B : A;
5273 return new ICmpInst(I.getPredicate(), OtherVal,
5274 Constant::getNullValue(A->getType()));
5275 }
5276
5277 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5278 // A^c1 == C^c2 --> A == C^(c1^c2)
5279 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5280 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5281 if (Op1->hasOneUse()) {
5282 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5283 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5284 return new ICmpInst(I.getPredicate(), A,
5285 InsertNewInstBefore(Xor, I));
5286 }
5287
5288 // A^B == A^D -> B == D
5289 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5290 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5291 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5292 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5293 }
5294 }
5295
5296 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5297 (A == Op0 || B == Op0)) {
5298 // A == (A^B) -> B == 0
5299 Value *OtherVal = A == Op0 ? B : A;
5300 return new ICmpInst(I.getPredicate(), OtherVal,
5301 Constant::getNullValue(A->getType()));
5302 }
5303 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5304 // (A-B) == A -> B == 0
5305 return new ICmpInst(I.getPredicate(), B,
5306 Constant::getNullValue(B->getType()));
5307 }
5308 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5309 // A == (A-B) -> B == 0
5310 return new ICmpInst(I.getPredicate(), B,
5311 Constant::getNullValue(B->getType()));
5312 }
5313
5314 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5315 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5316 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5317 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5318 Value *X = 0, *Y = 0, *Z = 0;
5319
5320 if (A == C) {
5321 X = B; Y = D; Z = A;
5322 } else if (A == D) {
5323 X = B; Y = C; Z = A;
5324 } else if (B == C) {
5325 X = A; Y = D; Z = B;
5326 } else if (B == D) {
5327 X = A; Y = C; Z = B;
5328 }
5329
5330 if (X) { // Build (X^Y) & Z
5331 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5332 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5333 I.setOperand(0, Op1);
5334 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5335 return &I;
5336 }
5337 }
5338 }
5339 return Changed ? &I : 0;
5340}
5341
5342
5343/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5344/// and CmpRHS are both known to be integer constants.
5345Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5346 ConstantInt *DivRHS) {
5347 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5348 const APInt &CmpRHSV = CmpRHS->getValue();
5349
5350 // FIXME: If the operand types don't match the type of the divide
5351 // then don't attempt this transform. The code below doesn't have the
5352 // logic to deal with a signed divide and an unsigned compare (and
5353 // vice versa). This is because (x /s C1) <s C2 produces different
5354 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5355 // (x /u C1) <u C2. Simply casting the operands and result won't
5356 // work. :( The if statement below tests that condition and bails
5357 // if it finds it.
5358 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5359 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5360 return 0;
5361 if (DivRHS->isZero())
5362 return 0; // The ProdOV computation fails on divide by zero.
5363
5364 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5365 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5366 // C2 (CI). By solving for X we can turn this into a range check
5367 // instead of computing a divide.
5368 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5369
5370 // Determine if the product overflows by seeing if the product is
5371 // not equal to the divide. Make sure we do the same kind of divide
5372 // as in the LHS instruction that we're folding.
5373 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5374 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5375
5376 // Get the ICmp opcode
5377 ICmpInst::Predicate Pred = ICI.getPredicate();
5378
5379 // Figure out the interval that is being checked. For example, a comparison
5380 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5381 // Compute this interval based on the constants involved and the signedness of
5382 // the compare/divide. This computes a half-open interval, keeping track of
5383 // whether either value in the interval overflows. After analysis each
5384 // overflow variable is set to 0 if it's corresponding bound variable is valid
5385 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5386 int LoOverflow = 0, HiOverflow = 0;
5387 ConstantInt *LoBound = 0, *HiBound = 0;
5388
5389
5390 if (!DivIsSigned) { // udiv
5391 // e.g. X/5 op 3 --> [15, 20)
5392 LoBound = Prod;
5393 HiOverflow = LoOverflow = ProdOV;
5394 if (!HiOverflow)
5395 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005396 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005397 if (CmpRHSV == 0) { // (X / pos) op 0
5398 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5399 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5400 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005401 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005402 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5403 HiOverflow = LoOverflow = ProdOV;
5404 if (!HiOverflow)
5405 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5406 } else { // (X / pos) op neg
5407 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5408 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5409 LoOverflow = AddWithOverflow(LoBound, Prod,
5410 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5411 HiBound = AddOne(Prod);
5412 HiOverflow = ProdOV ? -1 : 0;
5413 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005414 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005415 if (CmpRHSV == 0) { // (X / neg) op 0
5416 // e.g. X/-5 op 0 --> [-4, 5)
5417 LoBound = AddOne(DivRHS);
5418 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5419 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5420 HiOverflow = 1; // [INTMIN+1, overflow)
5421 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5422 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005423 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005424 // e.g. X/-5 op 3 --> [-19, -14)
5425 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5426 if (!LoOverflow)
5427 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5428 HiBound = AddOne(Prod);
5429 } else { // (X / neg) op neg
5430 // e.g. X/-5 op -3 --> [15, 20)
5431 LoBound = Prod;
5432 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5433 HiBound = Subtract(Prod, DivRHS);
5434 }
5435
5436 // Dividing by a negative swaps the condition. LT <-> GT
5437 Pred = ICmpInst::getSwappedPredicate(Pred);
5438 }
5439
5440 Value *X = DivI->getOperand(0);
5441 switch (Pred) {
5442 default: assert(0 && "Unhandled icmp opcode!");
5443 case ICmpInst::ICMP_EQ:
5444 if (LoOverflow && HiOverflow)
5445 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5446 else if (HiOverflow)
5447 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5448 ICmpInst::ICMP_UGE, X, LoBound);
5449 else if (LoOverflow)
5450 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5451 ICmpInst::ICMP_ULT, X, HiBound);
5452 else
5453 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5454 case ICmpInst::ICMP_NE:
5455 if (LoOverflow && HiOverflow)
5456 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5457 else if (HiOverflow)
5458 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5459 ICmpInst::ICMP_ULT, X, LoBound);
5460 else if (LoOverflow)
5461 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5462 ICmpInst::ICMP_UGE, X, HiBound);
5463 else
5464 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5465 case ICmpInst::ICMP_ULT:
5466 case ICmpInst::ICMP_SLT:
5467 if (LoOverflow == +1) // Low bound is greater than input range.
5468 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5469 if (LoOverflow == -1) // Low bound is less than input range.
5470 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5471 return new ICmpInst(Pred, X, LoBound);
5472 case ICmpInst::ICMP_UGT:
5473 case ICmpInst::ICMP_SGT:
5474 if (HiOverflow == +1) // High bound greater than input range.
5475 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5476 else if (HiOverflow == -1) // High bound less than input range.
5477 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5478 if (Pred == ICmpInst::ICMP_UGT)
5479 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5480 else
5481 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5482 }
5483}
5484
5485
5486/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5487///
5488Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5489 Instruction *LHSI,
5490 ConstantInt *RHS) {
5491 const APInt &RHSV = RHS->getValue();
5492
5493 switch (LHSI->getOpcode()) {
5494 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5495 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5496 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5497 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005498 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5499 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005500 Value *CompareVal = LHSI->getOperand(0);
5501
5502 // If the sign bit of the XorCST is not set, there is no change to
5503 // the operation, just stop using the Xor.
5504 if (!XorCST->getValue().isNegative()) {
5505 ICI.setOperand(0, CompareVal);
5506 AddToWorkList(LHSI);
5507 return &ICI;
5508 }
5509
5510 // Was the old condition true if the operand is positive?
5511 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5512
5513 // If so, the new one isn't.
5514 isTrueIfPositive ^= true;
5515
5516 if (isTrueIfPositive)
5517 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5518 else
5519 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5520 }
5521 }
5522 break;
5523 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5524 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5525 LHSI->getOperand(0)->hasOneUse()) {
5526 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5527
5528 // If the LHS is an AND of a truncating cast, we can widen the
5529 // and/compare to be the input width without changing the value
5530 // produced, eliminating a cast.
5531 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5532 // We can do this transformation if either the AND constant does not
5533 // have its sign bit set or if it is an equality comparison.
5534 // Extending a relational comparison when we're checking the sign
5535 // bit would not work.
5536 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005537 (ICI.isEquality() ||
5538 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005539 uint32_t BitWidth =
5540 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5541 APInt NewCST = AndCST->getValue();
5542 NewCST.zext(BitWidth);
5543 APInt NewCI = RHSV;
5544 NewCI.zext(BitWidth);
5545 Instruction *NewAnd =
5546 BinaryOperator::createAnd(Cast->getOperand(0),
5547 ConstantInt::get(NewCST),LHSI->getName());
5548 InsertNewInstBefore(NewAnd, ICI);
5549 return new ICmpInst(ICI.getPredicate(), NewAnd,
5550 ConstantInt::get(NewCI));
5551 }
5552 }
5553
5554 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5555 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5556 // happens a LOT in code produced by the C front-end, for bitfield
5557 // access.
5558 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5559 if (Shift && !Shift->isShift())
5560 Shift = 0;
5561
5562 ConstantInt *ShAmt;
5563 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5564 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5565 const Type *AndTy = AndCST->getType(); // Type of the and.
5566
5567 // We can fold this as long as we can't shift unknown bits
5568 // into the mask. This can only happen with signed shift
5569 // rights, as they sign-extend.
5570 if (ShAmt) {
5571 bool CanFold = Shift->isLogicalShift();
5572 if (!CanFold) {
5573 // To test for the bad case of the signed shr, see if any
5574 // of the bits shifted in could be tested after the mask.
5575 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5576 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5577
5578 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5579 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5580 AndCST->getValue()) == 0)
5581 CanFold = true;
5582 }
5583
5584 if (CanFold) {
5585 Constant *NewCst;
5586 if (Shift->getOpcode() == Instruction::Shl)
5587 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5588 else
5589 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5590
5591 // Check to see if we are shifting out any of the bits being
5592 // compared.
5593 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5594 // If we shifted bits out, the fold is not going to work out.
5595 // As a special case, check to see if this means that the
5596 // result is always true or false now.
5597 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5598 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5599 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5600 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5601 } else {
5602 ICI.setOperand(1, NewCst);
5603 Constant *NewAndCST;
5604 if (Shift->getOpcode() == Instruction::Shl)
5605 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5606 else
5607 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5608 LHSI->setOperand(1, NewAndCST);
5609 LHSI->setOperand(0, Shift->getOperand(0));
5610 AddToWorkList(Shift); // Shift is dead.
5611 AddUsesToWorkList(ICI);
5612 return &ICI;
5613 }
5614 }
5615 }
5616
5617 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5618 // preferable because it allows the C<<Y expression to be hoisted out
5619 // of a loop if Y is invariant and X is not.
5620 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5621 ICI.isEquality() && !Shift->isArithmeticShift() &&
5622 isa<Instruction>(Shift->getOperand(0))) {
5623 // Compute C << Y.
5624 Value *NS;
5625 if (Shift->getOpcode() == Instruction::LShr) {
5626 NS = BinaryOperator::createShl(AndCST,
5627 Shift->getOperand(1), "tmp");
5628 } else {
5629 // Insert a logical shift.
5630 NS = BinaryOperator::createLShr(AndCST,
5631 Shift->getOperand(1), "tmp");
5632 }
5633 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5634
5635 // Compute X & (C << Y).
5636 Instruction *NewAnd =
5637 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5638 InsertNewInstBefore(NewAnd, ICI);
5639
5640 ICI.setOperand(0, NewAnd);
5641 return &ICI;
5642 }
5643 }
5644 break;
5645
5646 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5647 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5648 if (!ShAmt) break;
5649
5650 uint32_t TypeBits = RHSV.getBitWidth();
5651
5652 // Check that the shift amount is in range. If not, don't perform
5653 // undefined shifts. When the shift is visited it will be
5654 // simplified.
5655 if (ShAmt->uge(TypeBits))
5656 break;
5657
5658 if (ICI.isEquality()) {
5659 // If we are comparing against bits always shifted out, the
5660 // comparison cannot succeed.
5661 Constant *Comp =
5662 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5663 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5664 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5665 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5666 return ReplaceInstUsesWith(ICI, Cst);
5667 }
5668
5669 if (LHSI->hasOneUse()) {
5670 // Otherwise strength reduce the shift into an and.
5671 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5672 Constant *Mask =
5673 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5674
5675 Instruction *AndI =
5676 BinaryOperator::createAnd(LHSI->getOperand(0),
5677 Mask, LHSI->getName()+".mask");
5678 Value *And = InsertNewInstBefore(AndI, ICI);
5679 return new ICmpInst(ICI.getPredicate(), And,
5680 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5681 }
5682 }
5683
5684 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5685 bool TrueIfSigned = false;
5686 if (LHSI->hasOneUse() &&
5687 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5688 // (X << 31) <s 0 --> (X&1) != 0
5689 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5690 (TypeBits-ShAmt->getZExtValue()-1));
5691 Instruction *AndI =
5692 BinaryOperator::createAnd(LHSI->getOperand(0),
5693 Mask, LHSI->getName()+".mask");
5694 Value *And = InsertNewInstBefore(AndI, ICI);
5695
5696 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5697 And, Constant::getNullValue(And->getType()));
5698 }
5699 break;
5700 }
5701
5702 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5703 case Instruction::AShr: {
5704 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5705 if (!ShAmt) break;
5706
5707 if (ICI.isEquality()) {
5708 // Check that the shift amount is in range. If not, don't perform
5709 // undefined shifts. When the shift is visited it will be
5710 // simplified.
5711 uint32_t TypeBits = RHSV.getBitWidth();
5712 if (ShAmt->uge(TypeBits))
5713 break;
5714 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5715
5716 // If we are comparing against bits always shifted out, the
5717 // comparison cannot succeed.
5718 APInt Comp = RHSV << ShAmtVal;
5719 if (LHSI->getOpcode() == Instruction::LShr)
5720 Comp = Comp.lshr(ShAmtVal);
5721 else
5722 Comp = Comp.ashr(ShAmtVal);
5723
5724 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5725 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5726 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5727 return ReplaceInstUsesWith(ICI, Cst);
5728 }
5729
5730 if (LHSI->hasOneUse() || RHSV == 0) {
5731 // Otherwise strength reduce the shift into an and.
5732 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5733 Constant *Mask = ConstantInt::get(Val);
5734
5735 Instruction *AndI =
5736 BinaryOperator::createAnd(LHSI->getOperand(0),
5737 Mask, LHSI->getName()+".mask");
5738 Value *And = InsertNewInstBefore(AndI, ICI);
5739 return new ICmpInst(ICI.getPredicate(), And,
5740 ConstantExpr::getShl(RHS, ShAmt));
5741 }
5742 }
5743 break;
5744 }
5745
5746 case Instruction::SDiv:
5747 case Instruction::UDiv:
5748 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5749 // Fold this div into the comparison, producing a range check.
5750 // Determine, based on the divide type, what the range is being
5751 // checked. If there is an overflow on the low or high side, remember
5752 // it, otherwise compute the range [low, hi) bounding the new value.
5753 // See: InsertRangeTest above for the kinds of replacements possible.
5754 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5755 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5756 DivRHS))
5757 return R;
5758 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00005759
5760 case Instruction::Add:
5761 // Fold: icmp pred (add, X, C1), C2
5762
5763 if (!ICI.isEquality()) {
5764 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5765 if (!LHSC) break;
5766 const APInt &LHSV = LHSC->getValue();
5767
5768 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5769 .subtract(LHSV);
5770
5771 if (ICI.isSignedPredicate()) {
5772 if (CR.getLower().isSignBit()) {
5773 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5774 ConstantInt::get(CR.getUpper()));
5775 } else if (CR.getUpper().isSignBit()) {
5776 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5777 ConstantInt::get(CR.getLower()));
5778 }
5779 } else {
5780 if (CR.getLower().isMinValue()) {
5781 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5782 ConstantInt::get(CR.getUpper()));
5783 } else if (CR.getUpper().isMinValue()) {
5784 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5785 ConstantInt::get(CR.getLower()));
5786 }
5787 }
5788 }
5789 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005790 }
5791
5792 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5793 if (ICI.isEquality()) {
5794 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5795
5796 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5797 // the second operand is a constant, simplify a bit.
5798 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5799 switch (BO->getOpcode()) {
5800 case Instruction::SRem:
5801 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5802 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5803 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5804 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5805 Instruction *NewRem =
5806 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5807 BO->getName());
5808 InsertNewInstBefore(NewRem, ICI);
5809 return new ICmpInst(ICI.getPredicate(), NewRem,
5810 Constant::getNullValue(BO->getType()));
5811 }
5812 }
5813 break;
5814 case Instruction::Add:
5815 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5816 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5817 if (BO->hasOneUse())
5818 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5819 Subtract(RHS, BOp1C));
5820 } else if (RHSV == 0) {
5821 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5822 // efficiently invertible, or if the add has just this one use.
5823 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5824
5825 if (Value *NegVal = dyn_castNegVal(BOp1))
5826 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5827 else if (Value *NegVal = dyn_castNegVal(BOp0))
5828 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5829 else if (BO->hasOneUse()) {
5830 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5831 InsertNewInstBefore(Neg, ICI);
5832 Neg->takeName(BO);
5833 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5834 }
5835 }
5836 break;
5837 case Instruction::Xor:
5838 // For the xor case, we can xor two constants together, eliminating
5839 // the explicit xor.
5840 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5841 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5842 ConstantExpr::getXor(RHS, BOC));
5843
5844 // FALLTHROUGH
5845 case Instruction::Sub:
5846 // Replace (([sub|xor] A, B) != 0) with (A != B)
5847 if (RHSV == 0)
5848 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5849 BO->getOperand(1));
5850 break;
5851
5852 case Instruction::Or:
5853 // If bits are being or'd in that are not present in the constant we
5854 // are comparing against, then the comparison could never succeed!
5855 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5856 Constant *NotCI = ConstantExpr::getNot(RHS);
5857 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5858 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5859 isICMP_NE));
5860 }
5861 break;
5862
5863 case Instruction::And:
5864 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5865 // If bits are being compared against that are and'd out, then the
5866 // comparison can never succeed!
5867 if ((RHSV & ~BOC->getValue()) != 0)
5868 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5869 isICMP_NE));
5870
5871 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5872 if (RHS == BOC && RHSV.isPowerOf2())
5873 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5874 ICmpInst::ICMP_NE, LHSI,
5875 Constant::getNullValue(RHS->getType()));
5876
5877 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5878 if (isSignBit(BOC)) {
5879 Value *X = BO->getOperand(0);
5880 Constant *Zero = Constant::getNullValue(X->getType());
5881 ICmpInst::Predicate pred = isICMP_NE ?
5882 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5883 return new ICmpInst(pred, X, Zero);
5884 }
5885
5886 // ((X & ~7) == 0) --> X < 8
5887 if (RHSV == 0 && isHighOnes(BOC)) {
5888 Value *X = BO->getOperand(0);
5889 Constant *NegX = ConstantExpr::getNeg(BOC);
5890 ICmpInst::Predicate pred = isICMP_NE ?
5891 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5892 return new ICmpInst(pred, X, NegX);
5893 }
5894 }
5895 default: break;
5896 }
5897 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5898 // Handle icmp {eq|ne} <intrinsic>, intcst.
5899 if (II->getIntrinsicID() == Intrinsic::bswap) {
5900 AddToWorkList(II);
5901 ICI.setOperand(0, II->getOperand(1));
5902 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5903 return &ICI;
5904 }
5905 }
5906 } else { // Not a ICMP_EQ/ICMP_NE
5907 // If the LHS is a cast from an integral value of the same size,
5908 // then since we know the RHS is a constant, try to simlify.
5909 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5910 Value *CastOp = Cast->getOperand(0);
5911 const Type *SrcTy = CastOp->getType();
5912 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5913 if (SrcTy->isInteger() &&
5914 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5915 // If this is an unsigned comparison, try to make the comparison use
5916 // smaller constant values.
5917 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5918 // X u< 128 => X s> -1
5919 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5920 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5921 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5922 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5923 // X u> 127 => X s< 0
5924 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5925 Constant::getNullValue(SrcTy));
5926 }
5927 }
5928 }
5929 }
5930 return 0;
5931}
5932
5933/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5934/// We only handle extending casts so far.
5935///
5936Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5937 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5938 Value *LHSCIOp = LHSCI->getOperand(0);
5939 const Type *SrcTy = LHSCIOp->getType();
5940 const Type *DestTy = LHSCI->getType();
5941 Value *RHSCIOp;
5942
5943 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5944 // integer type is the same size as the pointer type.
5945 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5946 getTargetData().getPointerSizeInBits() ==
5947 cast<IntegerType>(DestTy)->getBitWidth()) {
5948 Value *RHSOp = 0;
5949 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5950 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5951 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5952 RHSOp = RHSC->getOperand(0);
5953 // If the pointer types don't match, insert a bitcast.
5954 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005955 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 }
5957
5958 if (RHSOp)
5959 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5960 }
5961
5962 // The code below only handles extension cast instructions, so far.
5963 // Enforce this.
5964 if (LHSCI->getOpcode() != Instruction::ZExt &&
5965 LHSCI->getOpcode() != Instruction::SExt)
5966 return 0;
5967
5968 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5969 bool isSignedCmp = ICI.isSignedPredicate();
5970
5971 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5972 // Not an extension from the same type?
5973 RHSCIOp = CI->getOperand(0);
5974 if (RHSCIOp->getType() != LHSCIOp->getType())
5975 return 0;
5976
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005977 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005978 // and the other is a zext), then we can't handle this.
5979 if (CI->getOpcode() != LHSCI->getOpcode())
5980 return 0;
5981
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005982 // Deal with equality cases early.
5983 if (ICI.isEquality())
5984 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5985
5986 // A signed comparison of sign extended values simplifies into a
5987 // signed comparison.
5988 if (isSignedCmp && isSignedExt)
5989 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5990
5991 // The other three cases all fold into an unsigned comparison.
5992 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005993 }
5994
5995 // If we aren't dealing with a constant on the RHS, exit early
5996 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5997 if (!CI)
5998 return 0;
5999
6000 // Compute the constant that would happen if we truncated to SrcTy then
6001 // reextended to DestTy.
6002 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6003 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6004
6005 // If the re-extended constant didn't change...
6006 if (Res2 == CI) {
6007 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6008 // For example, we might have:
6009 // %A = sext short %X to uint
6010 // %B = icmp ugt uint %A, 1330
6011 // It is incorrect to transform this into
6012 // %B = icmp ugt short %X, 1330
6013 // because %A may have negative value.
6014 //
6015 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6016 // OR operation is EQ/NE.
6017 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6018 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6019 else
6020 return 0;
6021 }
6022
6023 // The re-extended constant changed so the constant cannot be represented
6024 // in the shorter type. Consequently, we cannot emit a simple comparison.
6025
6026 // First, handle some easy cases. We know the result cannot be equal at this
6027 // point so handle the ICI.isEquality() cases
6028 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6029 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6030 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6031 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6032
6033 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6034 // should have been folded away previously and not enter in here.
6035 Value *Result;
6036 if (isSignedCmp) {
6037 // We're performing a signed comparison.
6038 if (cast<ConstantInt>(CI)->getValue().isNegative())
6039 Result = ConstantInt::getFalse(); // X < (small) --> false
6040 else
6041 Result = ConstantInt::getTrue(); // X < (large) --> true
6042 } else {
6043 // We're performing an unsigned comparison.
6044 if (isSignedExt) {
6045 // We're performing an unsigned comp with a sign extended value.
6046 // This is true if the input is >= 0. [aka >s -1]
6047 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6048 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6049 NegOne, ICI.getName()), ICI);
6050 } else {
6051 // Unsigned extend & unsigned compare -> always true.
6052 Result = ConstantInt::getTrue();
6053 }
6054 }
6055
6056 // Finally, return the value computed.
6057 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6058 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6059 return ReplaceInstUsesWith(ICI, Result);
6060 } else {
6061 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6062 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6063 "ICmp should be folded!");
6064 if (Constant *CI = dyn_cast<Constant>(Result))
6065 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6066 else
6067 return BinaryOperator::createNot(Result);
6068 }
6069}
6070
6071Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6072 return commonShiftTransforms(I);
6073}
6074
6075Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6076 return commonShiftTransforms(I);
6077}
6078
6079Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006080 if (Instruction *R = commonShiftTransforms(I))
6081 return R;
6082
6083 Value *Op0 = I.getOperand(0);
6084
6085 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6086 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6087 if (CSI->isAllOnesValue())
6088 return ReplaceInstUsesWith(I, CSI);
6089
6090 // See if we can turn a signed shr into an unsigned shr.
6091 if (MaskedValueIsZero(Op0,
6092 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6093 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6094
6095 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006096}
6097
6098Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6099 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6101
6102 // shl X, 0 == X and shr X, 0 == X
6103 // shl 0, X == 0 and shr 0, X == 0
6104 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6105 Op0 == Constant::getNullValue(Op0->getType()))
6106 return ReplaceInstUsesWith(I, Op0);
6107
6108 if (isa<UndefValue>(Op0)) {
6109 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6110 return ReplaceInstUsesWith(I, Op0);
6111 else // undef << X -> 0, undef >>u X -> 0
6112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6113 }
6114 if (isa<UndefValue>(Op1)) {
6115 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6116 return ReplaceInstUsesWith(I, Op0);
6117 else // X << undef, X >>u undef -> 0
6118 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6119 }
6120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006121 // Try to fold constant and into select arguments.
6122 if (isa<Constant>(Op0))
6123 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6124 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6125 return R;
6126
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006127 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6128 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6129 return Res;
6130 return 0;
6131}
6132
6133Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6134 BinaryOperator &I) {
6135 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6136
6137 // See if we can simplify any instructions used by the instruction whose sole
6138 // purpose is to compute bits we don't care about.
6139 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6140 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6141 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6142 KnownZero, KnownOne))
6143 return &I;
6144
6145 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6146 // of a signed value.
6147 //
6148 if (Op1->uge(TypeBits)) {
6149 if (I.getOpcode() != Instruction::AShr)
6150 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6151 else {
6152 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6153 return &I;
6154 }
6155 }
6156
6157 // ((X*C1) << C2) == (X * (C1 << C2))
6158 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6159 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6160 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6161 return BinaryOperator::createMul(BO->getOperand(0),
6162 ConstantExpr::getShl(BOOp, Op1));
6163
6164 // Try to fold constant and into select arguments.
6165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6167 return R;
6168 if (isa<PHINode>(Op0))
6169 if (Instruction *NV = FoldOpIntoPhi(I))
6170 return NV;
6171
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006172 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6173 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6174 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6175 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6176 // place. Don't try to do this transformation in this case. Also, we
6177 // require that the input operand is a shift-by-constant so that we have
6178 // confidence that the shifts will get folded together. We could do this
6179 // xform in more cases, but it is unlikely to be profitable.
6180 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6181 isa<ConstantInt>(TrOp->getOperand(1))) {
6182 // Okay, we'll do this xform. Make the shift of shift.
6183 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6184 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6185 I.getName());
6186 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6187
6188 // For logical shifts, the truncation has the effect of making the high
6189 // part of the register be zeros. Emulate this by inserting an AND to
6190 // clear the top bits as needed. This 'and' will usually be zapped by
6191 // other xforms later if dead.
6192 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6193 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6194 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6195
6196 // The mask we constructed says what the trunc would do if occurring
6197 // between the shifts. We want to know the effect *after* the second
6198 // shift. We know that it is a logical shift by a constant, so adjust the
6199 // mask as appropriate.
6200 if (I.getOpcode() == Instruction::Shl)
6201 MaskV <<= Op1->getZExtValue();
6202 else {
6203 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6204 MaskV = MaskV.lshr(Op1->getZExtValue());
6205 }
6206
6207 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6208 TI->getName());
6209 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6210
6211 // Return the value truncated to the interesting size.
6212 return new TruncInst(And, I.getType());
6213 }
6214 }
6215
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006216 if (Op0->hasOneUse()) {
6217 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6218 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6219 Value *V1, *V2;
6220 ConstantInt *CC;
6221 switch (Op0BO->getOpcode()) {
6222 default: break;
6223 case Instruction::Add:
6224 case Instruction::And:
6225 case Instruction::Or:
6226 case Instruction::Xor: {
6227 // These operators commute.
6228 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6229 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6230 match(Op0BO->getOperand(1),
6231 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6232 Instruction *YS = BinaryOperator::createShl(
6233 Op0BO->getOperand(0), Op1,
6234 Op0BO->getName());
6235 InsertNewInstBefore(YS, I); // (Y << C)
6236 Instruction *X =
6237 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6238 Op0BO->getOperand(1)->getName());
6239 InsertNewInstBefore(X, I); // (X + (Y << C))
6240 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6241 return BinaryOperator::createAnd(X, ConstantInt::get(
6242 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6243 }
6244
6245 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6246 Value *Op0BOOp1 = Op0BO->getOperand(1);
6247 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6248 match(Op0BOOp1,
6249 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6250 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6251 V2 == Op1) {
6252 Instruction *YS = BinaryOperator::createShl(
6253 Op0BO->getOperand(0), Op1,
6254 Op0BO->getName());
6255 InsertNewInstBefore(YS, I); // (Y << C)
6256 Instruction *XM =
6257 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6258 V1->getName()+".mask");
6259 InsertNewInstBefore(XM, I); // X & (CC << C)
6260
6261 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6262 }
6263 }
6264
6265 // FALL THROUGH.
6266 case Instruction::Sub: {
6267 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6268 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6269 match(Op0BO->getOperand(0),
6270 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6271 Instruction *YS = BinaryOperator::createShl(
6272 Op0BO->getOperand(1), Op1,
6273 Op0BO->getName());
6274 InsertNewInstBefore(YS, I); // (Y << C)
6275 Instruction *X =
6276 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6277 Op0BO->getOperand(0)->getName());
6278 InsertNewInstBefore(X, I); // (X + (Y << C))
6279 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6280 return BinaryOperator::createAnd(X, ConstantInt::get(
6281 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6282 }
6283
6284 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6285 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6286 match(Op0BO->getOperand(0),
6287 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6288 m_ConstantInt(CC))) && V2 == Op1 &&
6289 cast<BinaryOperator>(Op0BO->getOperand(0))
6290 ->getOperand(0)->hasOneUse()) {
6291 Instruction *YS = BinaryOperator::createShl(
6292 Op0BO->getOperand(1), Op1,
6293 Op0BO->getName());
6294 InsertNewInstBefore(YS, I); // (Y << C)
6295 Instruction *XM =
6296 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6297 V1->getName()+".mask");
6298 InsertNewInstBefore(XM, I); // X & (CC << C)
6299
6300 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6301 }
6302
6303 break;
6304 }
6305 }
6306
6307
6308 // If the operand is an bitwise operator with a constant RHS, and the
6309 // shift is the only use, we can pull it out of the shift.
6310 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6311 bool isValid = true; // Valid only for And, Or, Xor
6312 bool highBitSet = false; // Transform if high bit of constant set?
6313
6314 switch (Op0BO->getOpcode()) {
6315 default: isValid = false; break; // Do not perform transform!
6316 case Instruction::Add:
6317 isValid = isLeftShift;
6318 break;
6319 case Instruction::Or:
6320 case Instruction::Xor:
6321 highBitSet = false;
6322 break;
6323 case Instruction::And:
6324 highBitSet = true;
6325 break;
6326 }
6327
6328 // If this is a signed shift right, and the high bit is modified
6329 // by the logical operation, do not perform the transformation.
6330 // The highBitSet boolean indicates the value of the high bit of
6331 // the constant which would cause it to be modified for this
6332 // operation.
6333 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006334 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006335 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006336
6337 if (isValid) {
6338 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6339
6340 Instruction *NewShift =
6341 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6342 InsertNewInstBefore(NewShift, I);
6343 NewShift->takeName(Op0BO);
6344
6345 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6346 NewRHS);
6347 }
6348 }
6349 }
6350 }
6351
6352 // Find out if this is a shift of a shift by a constant.
6353 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6354 if (ShiftOp && !ShiftOp->isShift())
6355 ShiftOp = 0;
6356
6357 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6358 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6359 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6360 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6361 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6362 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6363 Value *X = ShiftOp->getOperand(0);
6364
6365 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6366 if (AmtSum > TypeBits)
6367 AmtSum = TypeBits;
6368
6369 const IntegerType *Ty = cast<IntegerType>(I.getType());
6370
6371 // Check for (X << c1) << c2 and (X >> c1) >> c2
6372 if (I.getOpcode() == ShiftOp->getOpcode()) {
6373 return BinaryOperator::create(I.getOpcode(), X,
6374 ConstantInt::get(Ty, AmtSum));
6375 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6376 I.getOpcode() == Instruction::AShr) {
6377 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6378 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6379 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6380 I.getOpcode() == Instruction::LShr) {
6381 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6382 Instruction *Shift =
6383 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6384 InsertNewInstBefore(Shift, I);
6385
6386 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6387 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6388 }
6389
6390 // Okay, if we get here, one shift must be left, and the other shift must be
6391 // right. See if the amounts are equal.
6392 if (ShiftAmt1 == ShiftAmt2) {
6393 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6394 if (I.getOpcode() == Instruction::Shl) {
6395 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6396 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6397 }
6398 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6399 if (I.getOpcode() == Instruction::LShr) {
6400 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6401 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6402 }
6403 // We can simplify ((X << C) >>s C) into a trunc + sext.
6404 // NOTE: we could do this for any C, but that would make 'unusual' integer
6405 // types. For now, just stick to ones well-supported by the code
6406 // generators.
6407 const Type *SExtType = 0;
6408 switch (Ty->getBitWidth() - ShiftAmt1) {
6409 case 1 :
6410 case 8 :
6411 case 16 :
6412 case 32 :
6413 case 64 :
6414 case 128:
6415 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6416 break;
6417 default: break;
6418 }
6419 if (SExtType) {
6420 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6421 InsertNewInstBefore(NewTrunc, I);
6422 return new SExtInst(NewTrunc, Ty);
6423 }
6424 // Otherwise, we can't handle it yet.
6425 } else if (ShiftAmt1 < ShiftAmt2) {
6426 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6427
6428 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6429 if (I.getOpcode() == Instruction::Shl) {
6430 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6431 ShiftOp->getOpcode() == Instruction::AShr);
6432 Instruction *Shift =
6433 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6434 InsertNewInstBefore(Shift, I);
6435
6436 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6437 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6438 }
6439
6440 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6441 if (I.getOpcode() == Instruction::LShr) {
6442 assert(ShiftOp->getOpcode() == Instruction::Shl);
6443 Instruction *Shift =
6444 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6445 InsertNewInstBefore(Shift, I);
6446
6447 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6448 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6449 }
6450
6451 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6452 } else {
6453 assert(ShiftAmt2 < ShiftAmt1);
6454 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6455
6456 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6457 if (I.getOpcode() == Instruction::Shl) {
6458 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6459 ShiftOp->getOpcode() == Instruction::AShr);
6460 Instruction *Shift =
6461 BinaryOperator::create(ShiftOp->getOpcode(), X,
6462 ConstantInt::get(Ty, ShiftDiff));
6463 InsertNewInstBefore(Shift, I);
6464
6465 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6466 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6467 }
6468
6469 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6470 if (I.getOpcode() == Instruction::LShr) {
6471 assert(ShiftOp->getOpcode() == Instruction::Shl);
6472 Instruction *Shift =
6473 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6474 InsertNewInstBefore(Shift, I);
6475
6476 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6477 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6478 }
6479
6480 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6481 }
6482 }
6483 return 0;
6484}
6485
6486
6487/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6488/// expression. If so, decompose it, returning some value X, such that Val is
6489/// X*Scale+Offset.
6490///
6491static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6492 int &Offset) {
6493 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6495 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006496 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006497 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006498 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6499 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6500 if (I->getOpcode() == Instruction::Shl) {
6501 // This is a value scaled by '1 << the shift amt'.
6502 Scale = 1U << RHS->getZExtValue();
6503 Offset = 0;
6504 return I->getOperand(0);
6505 } else if (I->getOpcode() == Instruction::Mul) {
6506 // This value is scaled by 'RHS'.
6507 Scale = RHS->getZExtValue();
6508 Offset = 0;
6509 return I->getOperand(0);
6510 } else if (I->getOpcode() == Instruction::Add) {
6511 // We have X+C. Check to see if we really have (X*C2)+C1,
6512 // where C1 is divisible by C2.
6513 unsigned SubScale;
6514 Value *SubVal =
6515 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6516 Offset += RHS->getZExtValue();
6517 Scale = SubScale;
6518 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006519 }
6520 }
6521 }
6522
6523 // Otherwise, we can't look past this.
6524 Scale = 1;
6525 Offset = 0;
6526 return Val;
6527}
6528
6529
6530/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6531/// try to eliminate the cast by moving the type information into the alloc.
6532Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6533 AllocationInst &AI) {
6534 const PointerType *PTy = cast<PointerType>(CI.getType());
6535
6536 // Remove any uses of AI that are dead.
6537 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6538
6539 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6540 Instruction *User = cast<Instruction>(*UI++);
6541 if (isInstructionTriviallyDead(User)) {
6542 while (UI != E && *UI == User)
6543 ++UI; // If this instruction uses AI more than once, don't break UI.
6544
6545 ++NumDeadInst;
6546 DOUT << "IC: DCE: " << *User;
6547 EraseInstFromFunction(*User);
6548 }
6549 }
6550
6551 // Get the type really allocated and the type casted to.
6552 const Type *AllocElTy = AI.getAllocatedType();
6553 const Type *CastElTy = PTy->getElementType();
6554 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6555
6556 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6557 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6558 if (CastElTyAlign < AllocElTyAlign) return 0;
6559
6560 // If the allocation has multiple uses, only promote it if we are strictly
6561 // increasing the alignment of the resultant allocation. If we keep it the
6562 // same, we open the door to infinite loops of various kinds.
6563 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6564
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006565 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6566 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006567 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6568
6569 // See if we can satisfy the modulus by pulling a scale out of the array
6570 // size argument.
6571 unsigned ArraySizeScale;
6572 int ArrayOffset;
6573 Value *NumElements = // See if the array size is a decomposable linear expr.
6574 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6575
6576 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6577 // do the xform.
6578 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6579 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6580
6581 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6582 Value *Amt = 0;
6583 if (Scale == 1) {
6584 Amt = NumElements;
6585 } else {
6586 // If the allocation size is constant, form a constant mul expression
6587 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6588 if (isa<ConstantInt>(NumElements))
6589 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6590 // otherwise multiply the amount and the number of elements
6591 else if (Scale != 1) {
6592 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6593 Amt = InsertNewInstBefore(Tmp, AI);
6594 }
6595 }
6596
6597 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6598 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6599 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6600 Amt = InsertNewInstBefore(Tmp, AI);
6601 }
6602
6603 AllocationInst *New;
6604 if (isa<MallocInst>(AI))
6605 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6606 else
6607 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6608 InsertNewInstBefore(New, AI);
6609 New->takeName(&AI);
6610
6611 // If the allocation has multiple uses, insert a cast and change all things
6612 // that used it to use the new cast. This will also hack on CI, but it will
6613 // die soon.
6614 if (!AI.hasOneUse()) {
6615 AddUsesToWorkList(AI);
6616 // New is the allocation instruction, pointer typed. AI is the original
6617 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6618 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6619 InsertNewInstBefore(NewCast, AI);
6620 AI.replaceAllUsesWith(NewCast);
6621 }
6622 return ReplaceInstUsesWith(CI, New);
6623}
6624
6625/// CanEvaluateInDifferentType - Return true if we can take the specified value
6626/// and return it as type Ty without inserting any new casts and without
6627/// changing the computed value. This is used by code that tries to decide
6628/// whether promoting or shrinking integer operations to wider or smaller types
6629/// will allow us to eliminate a truncate or extend.
6630///
6631/// This is a truncation operation if Ty is smaller than V->getType(), or an
6632/// extension operation if Ty is larger.
6633static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006634 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006635 // We can always evaluate constants in another type.
6636 if (isa<ConstantInt>(V))
6637 return true;
6638
6639 Instruction *I = dyn_cast<Instruction>(V);
6640 if (!I) return false;
6641
6642 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6643
Chris Lattneref70bb82007-08-02 06:11:14 +00006644 // If this is an extension or truncate, we can often eliminate it.
6645 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6646 // If this is a cast from the destination type, we can trivially eliminate
6647 // it, and this will remove a cast overall.
6648 if (I->getOperand(0)->getType() == Ty) {
6649 // If the first operand is itself a cast, and is eliminable, do not count
6650 // this as an eliminable cast. We would prefer to eliminate those two
6651 // casts first.
6652 if (!isa<CastInst>(I->getOperand(0)))
6653 ++NumCastsRemoved;
6654 return true;
6655 }
6656 }
6657
6658 // We can't extend or shrink something that has multiple uses: doing so would
6659 // require duplicating the instruction in general, which isn't profitable.
6660 if (!I->hasOneUse()) return false;
6661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006662 switch (I->getOpcode()) {
6663 case Instruction::Add:
6664 case Instruction::Sub:
6665 case Instruction::And:
6666 case Instruction::Or:
6667 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006669 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6670 NumCastsRemoved) &&
6671 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6672 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006674 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006675 // A multiply can be truncated by truncating its operands.
6676 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6677 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6678 NumCastsRemoved) &&
6679 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6680 NumCastsRemoved);
6681
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006682 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 // If we are truncating the result of this SHL, and if it's a shift of a
6684 // constant amount, we can always perform a SHL in a smaller type.
6685 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6686 uint32_t BitWidth = Ty->getBitWidth();
6687 if (BitWidth < OrigTy->getBitWidth() &&
6688 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006689 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6690 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006691 }
6692 break;
6693 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006694 // If this is a truncate of a logical shr, we can truncate it to a smaller
6695 // lshr iff we know that the bits we would otherwise be shifting in are
6696 // already zeros.
6697 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6698 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6699 uint32_t BitWidth = Ty->getBitWidth();
6700 if (BitWidth < OrigBitWidth &&
6701 MaskedValueIsZero(I->getOperand(0),
6702 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6703 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006704 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6705 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006706 }
6707 }
6708 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006709 case Instruction::ZExt:
6710 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006711 case Instruction::Trunc:
6712 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006713 // can safely replace it. Note that replacing it does not reduce the number
6714 // of casts in the input.
6715 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006717
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006718 break;
6719 default:
6720 // TODO: Can handle more cases here.
6721 break;
6722 }
6723
6724 return false;
6725}
6726
6727/// EvaluateInDifferentType - Given an expression that
6728/// CanEvaluateInDifferentType returns true for, actually insert the code to
6729/// evaluate the expression.
6730Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6731 bool isSigned) {
6732 if (Constant *C = dyn_cast<Constant>(V))
6733 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6734
6735 // Otherwise, it must be an instruction.
6736 Instruction *I = cast<Instruction>(V);
6737 Instruction *Res = 0;
6738 switch (I->getOpcode()) {
6739 case Instruction::Add:
6740 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006741 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006742 case Instruction::And:
6743 case Instruction::Or:
6744 case Instruction::Xor:
6745 case Instruction::AShr:
6746 case Instruction::LShr:
6747 case Instruction::Shl: {
6748 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6749 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6750 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6751 LHS, RHS, I->getName());
6752 break;
6753 }
6754 case Instruction::Trunc:
6755 case Instruction::ZExt:
6756 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006757 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006758 // just return the source. There's no need to insert it because it is not
6759 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006760 if (I->getOperand(0)->getType() == Ty)
6761 return I->getOperand(0);
6762
Chris Lattneref70bb82007-08-02 06:11:14 +00006763 // Otherwise, must be the same type of case, so just reinsert a new one.
6764 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6765 Ty, I->getName());
6766 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006767 default:
6768 // TODO: Can handle more cases here.
6769 assert(0 && "Unreachable!");
6770 break;
6771 }
6772
6773 return InsertNewInstBefore(Res, *I);
6774}
6775
6776/// @brief Implement the transforms common to all CastInst visitors.
6777Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6778 Value *Src = CI.getOperand(0);
6779
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006780 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6781 // eliminate it now.
6782 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6783 if (Instruction::CastOps opc =
6784 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6785 // The first cast (CSrc) is eliminable so we need to fix up or replace
6786 // the second cast (CI). CSrc will then have a good chance of being dead.
6787 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6788 }
6789 }
6790
6791 // If we are casting a select then fold the cast into the select
6792 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6793 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6794 return NV;
6795
6796 // If we are casting a PHI then fold the cast into the PHI
6797 if (isa<PHINode>(Src))
6798 if (Instruction *NV = FoldOpIntoPhi(CI))
6799 return NV;
6800
6801 return 0;
6802}
6803
6804/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6805Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6806 Value *Src = CI.getOperand(0);
6807
6808 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6809 // If casting the result of a getelementptr instruction with no offset, turn
6810 // this into a cast of the original pointer!
6811 if (GEP->hasAllZeroIndices()) {
6812 // Changing the cast operand is usually not a good idea but it is safe
6813 // here because the pointer operand is being replaced with another
6814 // pointer operand so the opcode doesn't need to change.
6815 AddToWorkList(GEP);
6816 CI.setOperand(0, GEP->getOperand(0));
6817 return &CI;
6818 }
6819
6820 // If the GEP has a single use, and the base pointer is a bitcast, and the
6821 // GEP computes a constant offset, see if we can convert these three
6822 // instructions into fewer. This typically happens with unions and other
6823 // non-type-safe code.
6824 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6825 if (GEP->hasAllConstantIndices()) {
6826 // We are guaranteed to get a constant from EmitGEPOffset.
6827 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6828 int64_t Offset = OffsetV->getSExtValue();
6829
6830 // Get the base pointer input of the bitcast, and the type it points to.
6831 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6832 const Type *GEPIdxTy =
6833 cast<PointerType>(OrigBase->getType())->getElementType();
6834 if (GEPIdxTy->isSized()) {
6835 SmallVector<Value*, 8> NewIndices;
6836
6837 // Start with the index over the outer type. Note that the type size
6838 // might be zero (even if the offset isn't zero) if the indexed type
6839 // is something like [0 x {int, int}]
6840 const Type *IntPtrTy = TD->getIntPtrType();
6841 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006842 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006843 FirstIdx = Offset/TySize;
6844 Offset %= TySize;
6845
6846 // Handle silly modulus not returning values values [0..TySize).
6847 if (Offset < 0) {
6848 --FirstIdx;
6849 Offset += TySize;
6850 assert(Offset >= 0);
6851 }
6852 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6853 }
6854
6855 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6856
6857 // Index into the types. If we fail, set OrigBase to null.
6858 while (Offset) {
6859 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6860 const StructLayout *SL = TD->getStructLayout(STy);
6861 if (Offset < (int64_t)SL->getSizeInBytes()) {
6862 unsigned Elt = SL->getElementContainingOffset(Offset);
6863 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6864
6865 Offset -= SL->getElementOffset(Elt);
6866 GEPIdxTy = STy->getElementType(Elt);
6867 } else {
6868 // Otherwise, we can't index into this, bail out.
6869 Offset = 0;
6870 OrigBase = 0;
6871 }
6872 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6873 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006874 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006875 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6876 Offset %= EltSize;
6877 } else {
6878 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6879 }
6880 GEPIdxTy = STy->getElementType();
6881 } else {
6882 // Otherwise, we can't index into this, bail out.
6883 Offset = 0;
6884 OrigBase = 0;
6885 }
6886 }
6887 if (OrigBase) {
6888 // If we were able to index down into an element, create the GEP
6889 // and bitcast the result. This eliminates one bitcast, potentially
6890 // two.
David Greene393be882007-09-04 15:46:09 +00006891 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6892 NewIndices.begin(),
6893 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006894 InsertNewInstBefore(NGEP, CI);
6895 NGEP->takeName(GEP);
6896
6897 if (isa<BitCastInst>(CI))
6898 return new BitCastInst(NGEP, CI.getType());
6899 assert(isa<PtrToIntInst>(CI));
6900 return new PtrToIntInst(NGEP, CI.getType());
6901 }
6902 }
6903 }
6904 }
6905 }
6906
6907 return commonCastTransforms(CI);
6908}
6909
6910
6911
6912/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6913/// integer types. This function implements the common transforms for all those
6914/// cases.
6915/// @brief Implement the transforms common to CastInst with integer operands
6916Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6917 if (Instruction *Result = commonCastTransforms(CI))
6918 return Result;
6919
6920 Value *Src = CI.getOperand(0);
6921 const Type *SrcTy = Src->getType();
6922 const Type *DestTy = CI.getType();
6923 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6924 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6925
6926 // See if we can simplify any instructions used by the LHS whose sole
6927 // purpose is to compute bits we don't care about.
6928 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6929 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6930 KnownZero, KnownOne))
6931 return &CI;
6932
6933 // If the source isn't an instruction or has more than one use then we
6934 // can't do anything more.
6935 Instruction *SrcI = dyn_cast<Instruction>(Src);
6936 if (!SrcI || !Src->hasOneUse())
6937 return 0;
6938
6939 // Attempt to propagate the cast into the instruction for int->int casts.
6940 int NumCastsRemoved = 0;
6941 if (!isa<BitCastInst>(CI) &&
6942 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006943 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006944 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006945 // eliminates the cast, so it is always a win. If this is a zero-extension,
6946 // we need to do an AND to maintain the clear top-part of the computation,
6947 // so we require that the input have eliminated at least one cast. If this
6948 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 // require that two casts have been eliminated.
6950 bool DoXForm;
6951 switch (CI.getOpcode()) {
6952 default:
6953 // All the others use floating point so we shouldn't actually
6954 // get here because of the check above.
6955 assert(0 && "Unknown cast type");
6956 case Instruction::Trunc:
6957 DoXForm = true;
6958 break;
6959 case Instruction::ZExt:
6960 DoXForm = NumCastsRemoved >= 1;
6961 break;
6962 case Instruction::SExt:
6963 DoXForm = NumCastsRemoved >= 2;
6964 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965 }
6966
6967 if (DoXForm) {
6968 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6969 CI.getOpcode() == Instruction::SExt);
6970 assert(Res->getType() == DestTy);
6971 switch (CI.getOpcode()) {
6972 default: assert(0 && "Unknown cast type!");
6973 case Instruction::Trunc:
6974 case Instruction::BitCast:
6975 // Just replace this cast with the result.
6976 return ReplaceInstUsesWith(CI, Res);
6977 case Instruction::ZExt: {
6978 // We need to emit an AND to clear the high bits.
6979 assert(SrcBitSize < DestBitSize && "Not a zext?");
6980 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6981 SrcBitSize));
6982 return BinaryOperator::createAnd(Res, C);
6983 }
6984 case Instruction::SExt:
6985 // We need to emit a cast to truncate, then a cast to sext.
6986 return CastInst::create(Instruction::SExt,
6987 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6988 CI), DestTy);
6989 }
6990 }
6991 }
6992
6993 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6994 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6995
6996 switch (SrcI->getOpcode()) {
6997 case Instruction::Add:
6998 case Instruction::Mul:
6999 case Instruction::And:
7000 case Instruction::Or:
7001 case Instruction::Xor:
7002 // If we are discarding information, rewrite.
7003 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7004 // Don't insert two casts if they cannot be eliminated. We allow
7005 // two casts to be inserted if the sizes are the same. This could
7006 // only be converting signedness, which is a noop.
7007 if (DestBitSize == SrcBitSize ||
7008 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7009 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7010 Instruction::CastOps opcode = CI.getOpcode();
7011 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7012 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7013 return BinaryOperator::create(
7014 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7015 }
7016 }
7017
7018 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7019 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7020 SrcI->getOpcode() == Instruction::Xor &&
7021 Op1 == ConstantInt::getTrue() &&
7022 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7023 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7024 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7025 }
7026 break;
7027 case Instruction::SDiv:
7028 case Instruction::UDiv:
7029 case Instruction::SRem:
7030 case Instruction::URem:
7031 // If we are just changing the sign, rewrite.
7032 if (DestBitSize == SrcBitSize) {
7033 // Don't insert two casts if they cannot be eliminated. We allow
7034 // two casts to be inserted if the sizes are the same. This could
7035 // only be converting signedness, which is a noop.
7036 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7037 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7038 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7039 Op0, DestTy, SrcI);
7040 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7041 Op1, DestTy, SrcI);
7042 return BinaryOperator::create(
7043 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7044 }
7045 }
7046 break;
7047
7048 case Instruction::Shl:
7049 // Allow changing the sign of the source operand. Do not allow
7050 // changing the size of the shift, UNLESS the shift amount is a
7051 // constant. We must not change variable sized shifts to a smaller
7052 // size, because it is undefined to shift more bits out than exist
7053 // in the value.
7054 if (DestBitSize == SrcBitSize ||
7055 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7056 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7057 Instruction::BitCast : Instruction::Trunc);
7058 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7059 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7060 return BinaryOperator::createShl(Op0c, Op1c);
7061 }
7062 break;
7063 case Instruction::AShr:
7064 // If this is a signed shr, and if all bits shifted in are about to be
7065 // truncated off, turn it into an unsigned shr to allow greater
7066 // simplifications.
7067 if (DestBitSize < SrcBitSize &&
7068 isa<ConstantInt>(Op1)) {
7069 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7070 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7071 // Insert the new logical shift right.
7072 return BinaryOperator::createLShr(Op0, Op1);
7073 }
7074 }
7075 break;
7076 }
7077 return 0;
7078}
7079
7080Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7081 if (Instruction *Result = commonIntCastTransforms(CI))
7082 return Result;
7083
7084 Value *Src = CI.getOperand(0);
7085 const Type *Ty = CI.getType();
7086 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7087 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7088
7089 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7090 switch (SrcI->getOpcode()) {
7091 default: break;
7092 case Instruction::LShr:
7093 // We can shrink lshr to something smaller if we know the bits shifted in
7094 // are already zeros.
7095 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7096 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7097
7098 // Get a mask for the bits shifting in.
7099 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7100 Value* SrcIOp0 = SrcI->getOperand(0);
7101 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7102 if (ShAmt >= DestBitWidth) // All zeros.
7103 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7104
7105 // Okay, we can shrink this. Truncate the input, then return a new
7106 // shift.
7107 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7108 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7109 Ty, CI);
7110 return BinaryOperator::createLShr(V1, V2);
7111 }
7112 } else { // This is a variable shr.
7113
7114 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7115 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7116 // loop-invariant and CSE'd.
7117 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7118 Value *One = ConstantInt::get(SrcI->getType(), 1);
7119
7120 Value *V = InsertNewInstBefore(
7121 BinaryOperator::createShl(One, SrcI->getOperand(1),
7122 "tmp"), CI);
7123 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7124 SrcI->getOperand(0),
7125 "tmp"), CI);
7126 Value *Zero = Constant::getNullValue(V->getType());
7127 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7128 }
7129 }
7130 break;
7131 }
7132 }
7133
7134 return 0;
7135}
7136
7137Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7138 // If one of the common conversion will work ..
7139 if (Instruction *Result = commonIntCastTransforms(CI))
7140 return Result;
7141
7142 Value *Src = CI.getOperand(0);
7143
7144 // If this is a cast of a cast
7145 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7146 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7147 // types and if the sizes are just right we can convert this into a logical
7148 // 'and' which will be much cheaper than the pair of casts.
7149 if (isa<TruncInst>(CSrc)) {
7150 // Get the sizes of the types involved
7151 Value *A = CSrc->getOperand(0);
7152 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7153 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7154 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7155 // If we're actually extending zero bits and the trunc is a no-op
7156 if (MidSize < DstSize && SrcSize == DstSize) {
7157 // Replace both of the casts with an And of the type mask.
7158 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7159 Constant *AndConst = ConstantInt::get(AndValue);
7160 Instruction *And =
7161 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7162 // Unfortunately, if the type changed, we need to cast it back.
7163 if (And->getType() != CI.getType()) {
7164 And->setName(CSrc->getName()+".mask");
7165 InsertNewInstBefore(And, CI);
7166 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7167 }
7168 return And;
7169 }
7170 }
7171 }
7172
7173 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7174 // If we are just checking for a icmp eq of a single bit and zext'ing it
7175 // to an integer, then shift the bit to the appropriate place and then
7176 // cast to integer to avoid the comparison.
7177 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7178 const APInt &Op1CV = Op1C->getValue();
7179
7180 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7181 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7182 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7183 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7184 Value *In = ICI->getOperand(0);
7185 Value *Sh = ConstantInt::get(In->getType(),
7186 In->getType()->getPrimitiveSizeInBits()-1);
7187 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7188 In->getName()+".lobit"),
7189 CI);
7190 if (In->getType() != CI.getType())
7191 In = CastInst::createIntegerCast(In, CI.getType(),
7192 false/*ZExt*/, "tmp", &CI);
7193
7194 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7195 Constant *One = ConstantInt::get(In->getType(), 1);
7196 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7197 In->getName()+".not"),
7198 CI);
7199 }
7200
7201 return ReplaceInstUsesWith(CI, In);
7202 }
7203
7204
7205
7206 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7207 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7208 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7209 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7210 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7211 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7212 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7213 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7214 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7215 // This only works for EQ and NE
7216 ICI->isEquality()) {
7217 // If Op1C some other power of two, convert:
7218 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7219 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7220 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7221 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7222
7223 APInt KnownZeroMask(~KnownZero);
7224 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7225 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7226 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7227 // (X&4) == 2 --> false
7228 // (X&4) != 2 --> true
7229 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7230 Res = ConstantExpr::getZExt(Res, CI.getType());
7231 return ReplaceInstUsesWith(CI, Res);
7232 }
7233
7234 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7235 Value *In = ICI->getOperand(0);
7236 if (ShiftAmt) {
7237 // Perform a logical shr by shiftamt.
7238 // Insert the shift to put the result in the low bit.
7239 In = InsertNewInstBefore(
7240 BinaryOperator::createLShr(In,
7241 ConstantInt::get(In->getType(), ShiftAmt),
7242 In->getName()+".lobit"), CI);
7243 }
7244
7245 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7246 Constant *One = ConstantInt::get(In->getType(), 1);
7247 In = BinaryOperator::createXor(In, One, "tmp");
7248 InsertNewInstBefore(cast<Instruction>(In), CI);
7249 }
7250
7251 if (CI.getType() == In->getType())
7252 return ReplaceInstUsesWith(CI, In);
7253 else
7254 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7255 }
7256 }
7257 }
7258 }
7259 return 0;
7260}
7261
7262Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7263 if (Instruction *I = commonIntCastTransforms(CI))
7264 return I;
7265
7266 Value *Src = CI.getOperand(0);
7267
7268 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7269 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7270 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7271 // If we are just checking for a icmp eq of a single bit and zext'ing it
7272 // to an integer, then shift the bit to the appropriate place and then
7273 // cast to integer to avoid the comparison.
7274 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7275 const APInt &Op1CV = Op1C->getValue();
7276
7277 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7278 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7279 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7280 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7281 Value *In = ICI->getOperand(0);
7282 Value *Sh = ConstantInt::get(In->getType(),
7283 In->getType()->getPrimitiveSizeInBits()-1);
7284 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7285 In->getName()+".lobit"),
7286 CI);
7287 if (In->getType() != CI.getType())
7288 In = CastInst::createIntegerCast(In, CI.getType(),
7289 true/*SExt*/, "tmp", &CI);
7290
7291 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7292 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7293 In->getName()+".not"), CI);
7294
7295 return ReplaceInstUsesWith(CI, In);
7296 }
7297 }
7298 }
7299
7300 return 0;
7301}
7302
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007303/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7304/// in the specified FP type without changing its value.
7305static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7306 const fltSemantics &Sem) {
7307 APFloat F = CFP->getValueAPF();
7308 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7309 return ConstantFP::get(FPTy, F);
7310 return 0;
7311}
7312
7313/// LookThroughFPExtensions - If this is an fp extension instruction, look
7314/// through it until we get the source value.
7315static Value *LookThroughFPExtensions(Value *V) {
7316 if (Instruction *I = dyn_cast<Instruction>(V))
7317 if (I->getOpcode() == Instruction::FPExt)
7318 return LookThroughFPExtensions(I->getOperand(0));
7319
7320 // If this value is a constant, return the constant in the smallest FP type
7321 // that can accurately represent it. This allows us to turn
7322 // (float)((double)X+2.0) into x+2.0f.
7323 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7324 if (CFP->getType() == Type::PPC_FP128Ty)
7325 return V; // No constant folding of this.
7326 // See if the value can be truncated to float and then reextended.
7327 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7328 return V;
7329 if (CFP->getType() == Type::DoubleTy)
7330 return V; // Won't shrink.
7331 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7332 return V;
7333 // Don't try to shrink to various long double types.
7334 }
7335
7336 return V;
7337}
7338
7339Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7340 if (Instruction *I = commonCastTransforms(CI))
7341 return I;
7342
7343 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7344 // smaller than the destination type, we can eliminate the truncate by doing
7345 // the add as the smaller type. This applies to add/sub/mul/div as well as
7346 // many builtins (sqrt, etc).
7347 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7348 if (OpI && OpI->hasOneUse()) {
7349 switch (OpI->getOpcode()) {
7350 default: break;
7351 case Instruction::Add:
7352 case Instruction::Sub:
7353 case Instruction::Mul:
7354 case Instruction::FDiv:
7355 case Instruction::FRem:
7356 const Type *SrcTy = OpI->getType();
7357 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7358 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7359 if (LHSTrunc->getType() != SrcTy &&
7360 RHSTrunc->getType() != SrcTy) {
7361 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7362 // If the source types were both smaller than the destination type of
7363 // the cast, do this xform.
7364 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7365 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7366 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7367 CI.getType(), CI);
7368 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7369 CI.getType(), CI);
7370 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7371 }
7372 }
7373 break;
7374 }
7375 }
7376 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377}
7378
7379Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7380 return commonCastTransforms(CI);
7381}
7382
7383Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7384 return commonCastTransforms(CI);
7385}
7386
7387Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7388 return commonCastTransforms(CI);
7389}
7390
7391Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7392 return commonCastTransforms(CI);
7393}
7394
7395Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7396 return commonCastTransforms(CI);
7397}
7398
7399Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7400 return commonPointerCastTransforms(CI);
7401}
7402
Chris Lattner7c1626482008-01-08 07:23:51 +00007403Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7404 if (Instruction *I = commonCastTransforms(CI))
7405 return I;
7406
7407 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7408 if (!DestPointee->isSized()) return 0;
7409
7410 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7411 ConstantInt *Cst;
7412 Value *X;
7413 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7414 m_ConstantInt(Cst)))) {
7415 // If the source and destination operands have the same type, see if this
7416 // is a single-index GEP.
7417 if (X->getType() == CI.getType()) {
7418 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007419 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007420
7421 // Convert the constant to intptr type.
7422 APInt Offset = Cst->getValue();
7423 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7424
7425 // If Offset is evenly divisible by Size, we can do this xform.
7426 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7427 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7428 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7429 }
7430 }
7431 // TODO: Could handle other cases, e.g. where add is indexing into field of
7432 // struct etc.
7433 } else if (CI.getOperand(0)->hasOneUse() &&
7434 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7435 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7436 // "inttoptr+GEP" instead of "add+intptr".
7437
7438 // Get the size of the pointee type.
7439 uint64_t Size = TD->getABITypeSize(DestPointee);
7440
7441 // Convert the constant to intptr type.
7442 APInt Offset = Cst->getValue();
7443 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7444
7445 // If Offset is evenly divisible by Size, we can do this xform.
7446 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7447 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7448
7449 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7450 "tmp"), CI);
7451 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7452 }
7453 }
7454 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007455}
7456
7457Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7458 // If the operands are integer typed then apply the integer transforms,
7459 // otherwise just apply the common ones.
7460 Value *Src = CI.getOperand(0);
7461 const Type *SrcTy = Src->getType();
7462 const Type *DestTy = CI.getType();
7463
7464 if (SrcTy->isInteger() && DestTy->isInteger()) {
7465 if (Instruction *Result = commonIntCastTransforms(CI))
7466 return Result;
7467 } else if (isa<PointerType>(SrcTy)) {
7468 if (Instruction *I = commonPointerCastTransforms(CI))
7469 return I;
7470 } else {
7471 if (Instruction *Result = commonCastTransforms(CI))
7472 return Result;
7473 }
7474
7475
7476 // Get rid of casts from one type to the same type. These are useless and can
7477 // be replaced by the operand.
7478 if (DestTy == Src->getType())
7479 return ReplaceInstUsesWith(CI, Src);
7480
7481 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7482 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7483 const Type *DstElTy = DstPTy->getElementType();
7484 const Type *SrcElTy = SrcPTy->getElementType();
7485
7486 // If we are casting a malloc or alloca to a pointer to a type of the same
7487 // size, rewrite the allocation instruction to allocate the "right" type.
7488 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7489 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7490 return V;
7491
7492 // If the source and destination are pointers, and this cast is equivalent
7493 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7494 // This can enhance SROA and other transforms that want type-safe pointers.
7495 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7496 unsigned NumZeros = 0;
7497 while (SrcElTy != DstElTy &&
7498 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7499 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7500 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7501 ++NumZeros;
7502 }
7503
7504 // If we found a path from the src to dest, create the getelementptr now.
7505 if (SrcElTy == DstElTy) {
7506 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007507 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7508 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007509 }
7510 }
7511
7512 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7513 if (SVI->hasOneUse()) {
7514 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7515 // a bitconvert to a vector with the same # elts.
7516 if (isa<VectorType>(DestTy) &&
7517 cast<VectorType>(DestTy)->getNumElements() ==
7518 SVI->getType()->getNumElements()) {
7519 CastInst *Tmp;
7520 // If either of the operands is a cast from CI.getType(), then
7521 // evaluating the shuffle in the casted destination's type will allow
7522 // us to eliminate at least one cast.
7523 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7524 Tmp->getOperand(0)->getType() == DestTy) ||
7525 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7526 Tmp->getOperand(0)->getType() == DestTy)) {
7527 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7528 SVI->getOperand(0), DestTy, &CI);
7529 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7530 SVI->getOperand(1), DestTy, &CI);
7531 // Return a new shuffle vector. Use the same element ID's, as we
7532 // know the vector types match #elts.
7533 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7534 }
7535 }
7536 }
7537 }
7538 return 0;
7539}
7540
7541/// GetSelectFoldableOperands - We want to turn code that looks like this:
7542/// %C = or %A, %B
7543/// %D = select %cond, %C, %A
7544/// into:
7545/// %C = select %cond, %B, 0
7546/// %D = or %A, %C
7547///
7548/// Assuming that the specified instruction is an operand to the select, return
7549/// a bitmask indicating which operands of this instruction are foldable if they
7550/// equal the other incoming value of the select.
7551///
7552static unsigned GetSelectFoldableOperands(Instruction *I) {
7553 switch (I->getOpcode()) {
7554 case Instruction::Add:
7555 case Instruction::Mul:
7556 case Instruction::And:
7557 case Instruction::Or:
7558 case Instruction::Xor:
7559 return 3; // Can fold through either operand.
7560 case Instruction::Sub: // Can only fold on the amount subtracted.
7561 case Instruction::Shl: // Can only fold on the shift amount.
7562 case Instruction::LShr:
7563 case Instruction::AShr:
7564 return 1;
7565 default:
7566 return 0; // Cannot fold
7567 }
7568}
7569
7570/// GetSelectFoldableConstant - For the same transformation as the previous
7571/// function, return the identity constant that goes into the select.
7572static Constant *GetSelectFoldableConstant(Instruction *I) {
7573 switch (I->getOpcode()) {
7574 default: assert(0 && "This cannot happen!"); abort();
7575 case Instruction::Add:
7576 case Instruction::Sub:
7577 case Instruction::Or:
7578 case Instruction::Xor:
7579 case Instruction::Shl:
7580 case Instruction::LShr:
7581 case Instruction::AShr:
7582 return Constant::getNullValue(I->getType());
7583 case Instruction::And:
7584 return Constant::getAllOnesValue(I->getType());
7585 case Instruction::Mul:
7586 return ConstantInt::get(I->getType(), 1);
7587 }
7588}
7589
7590/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7591/// have the same opcode and only one use each. Try to simplify this.
7592Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7593 Instruction *FI) {
7594 if (TI->getNumOperands() == 1) {
7595 // If this is a non-volatile load or a cast from the same type,
7596 // merge.
7597 if (TI->isCast()) {
7598 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7599 return 0;
7600 } else {
7601 return 0; // unknown unary op.
7602 }
7603
7604 // Fold this by inserting a select from the input values.
7605 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7606 FI->getOperand(0), SI.getName()+".v");
7607 InsertNewInstBefore(NewSI, SI);
7608 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7609 TI->getType());
7610 }
7611
7612 // Only handle binary operators here.
7613 if (!isa<BinaryOperator>(TI))
7614 return 0;
7615
7616 // Figure out if the operations have any operands in common.
7617 Value *MatchOp, *OtherOpT, *OtherOpF;
7618 bool MatchIsOpZero;
7619 if (TI->getOperand(0) == FI->getOperand(0)) {
7620 MatchOp = TI->getOperand(0);
7621 OtherOpT = TI->getOperand(1);
7622 OtherOpF = FI->getOperand(1);
7623 MatchIsOpZero = true;
7624 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7625 MatchOp = TI->getOperand(1);
7626 OtherOpT = TI->getOperand(0);
7627 OtherOpF = FI->getOperand(0);
7628 MatchIsOpZero = false;
7629 } else if (!TI->isCommutative()) {
7630 return 0;
7631 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7632 MatchOp = TI->getOperand(0);
7633 OtherOpT = TI->getOperand(1);
7634 OtherOpF = FI->getOperand(0);
7635 MatchIsOpZero = true;
7636 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7637 MatchOp = TI->getOperand(1);
7638 OtherOpT = TI->getOperand(0);
7639 OtherOpF = FI->getOperand(1);
7640 MatchIsOpZero = true;
7641 } else {
7642 return 0;
7643 }
7644
7645 // If we reach here, they do have operations in common.
7646 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7647 OtherOpF, SI.getName()+".v");
7648 InsertNewInstBefore(NewSI, SI);
7649
7650 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7651 if (MatchIsOpZero)
7652 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7653 else
7654 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7655 }
7656 assert(0 && "Shouldn't get here");
7657 return 0;
7658}
7659
7660Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7661 Value *CondVal = SI.getCondition();
7662 Value *TrueVal = SI.getTrueValue();
7663 Value *FalseVal = SI.getFalseValue();
7664
7665 // select true, X, Y -> X
7666 // select false, X, Y -> Y
7667 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7668 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7669
7670 // select C, X, X -> X
7671 if (TrueVal == FalseVal)
7672 return ReplaceInstUsesWith(SI, TrueVal);
7673
7674 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7675 return ReplaceInstUsesWith(SI, FalseVal);
7676 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7677 return ReplaceInstUsesWith(SI, TrueVal);
7678 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7679 if (isa<Constant>(TrueVal))
7680 return ReplaceInstUsesWith(SI, TrueVal);
7681 else
7682 return ReplaceInstUsesWith(SI, FalseVal);
7683 }
7684
7685 if (SI.getType() == Type::Int1Ty) {
7686 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7687 if (C->getZExtValue()) {
7688 // Change: A = select B, true, C --> A = or B, C
7689 return BinaryOperator::createOr(CondVal, FalseVal);
7690 } else {
7691 // Change: A = select B, false, C --> A = and !B, C
7692 Value *NotCond =
7693 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7694 "not."+CondVal->getName()), SI);
7695 return BinaryOperator::createAnd(NotCond, FalseVal);
7696 }
7697 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7698 if (C->getZExtValue() == false) {
7699 // Change: A = select B, C, false --> A = and B, C
7700 return BinaryOperator::createAnd(CondVal, TrueVal);
7701 } else {
7702 // Change: A = select B, C, true --> A = or !B, C
7703 Value *NotCond =
7704 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7705 "not."+CondVal->getName()), SI);
7706 return BinaryOperator::createOr(NotCond, TrueVal);
7707 }
7708 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007709
7710 // select a, b, a -> a&b
7711 // select a, a, b -> a|b
7712 if (CondVal == TrueVal)
7713 return BinaryOperator::createOr(CondVal, FalseVal);
7714 else if (CondVal == FalseVal)
7715 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 }
7717
7718 // Selecting between two integer constants?
7719 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7720 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7721 // select C, 1, 0 -> zext C to int
7722 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7723 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7724 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7725 // select C, 0, 1 -> zext !C to int
7726 Value *NotCond =
7727 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7728 "not."+CondVal->getName()), SI);
7729 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7730 }
7731
7732 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7733
7734 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7735
7736 // (x <s 0) ? -1 : 0 -> ashr x, 31
7737 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7738 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7739 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7740 // The comparison constant and the result are not neccessarily the
7741 // same width. Make an all-ones value by inserting a AShr.
7742 Value *X = IC->getOperand(0);
7743 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7744 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7745 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7746 ShAmt, "ones");
7747 InsertNewInstBefore(SRA, SI);
7748
7749 // Finally, convert to the type of the select RHS. We figure out
7750 // if this requires a SExt, Trunc or BitCast based on the sizes.
7751 Instruction::CastOps opc = Instruction::BitCast;
7752 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7753 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7754 if (SRASize < SISize)
7755 opc = Instruction::SExt;
7756 else if (SRASize > SISize)
7757 opc = Instruction::Trunc;
7758 return CastInst::create(opc, SRA, SI.getType());
7759 }
7760 }
7761
7762
7763 // If one of the constants is zero (we know they can't both be) and we
7764 // have an icmp instruction with zero, and we have an 'and' with the
7765 // non-constant value, eliminate this whole mess. This corresponds to
7766 // cases like this: ((X & 27) ? 27 : 0)
7767 if (TrueValC->isZero() || FalseValC->isZero())
7768 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7769 cast<Constant>(IC->getOperand(1))->isNullValue())
7770 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7771 if (ICA->getOpcode() == Instruction::And &&
7772 isa<ConstantInt>(ICA->getOperand(1)) &&
7773 (ICA->getOperand(1) == TrueValC ||
7774 ICA->getOperand(1) == FalseValC) &&
7775 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7776 // Okay, now we know that everything is set up, we just don't
7777 // know whether we have a icmp_ne or icmp_eq and whether the
7778 // true or false val is the zero.
7779 bool ShouldNotVal = !TrueValC->isZero();
7780 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7781 Value *V = ICA;
7782 if (ShouldNotVal)
7783 V = InsertNewInstBefore(BinaryOperator::create(
7784 Instruction::Xor, V, ICA->getOperand(1)), SI);
7785 return ReplaceInstUsesWith(SI, V);
7786 }
7787 }
7788 }
7789
7790 // See if we are selecting two values based on a comparison of the two values.
7791 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7792 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7793 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007794 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7795 // This is not safe in general for floating point:
7796 // consider X== -0, Y== +0.
7797 // It becomes safe if either operand is a nonzero constant.
7798 ConstantFP *CFPt, *CFPf;
7799 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7800 !CFPt->getValueAPF().isZero()) ||
7801 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7802 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007803 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007804 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007805 // Transform (X != Y) ? X : Y -> X
7806 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7807 return ReplaceInstUsesWith(SI, TrueVal);
7808 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7809
7810 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7811 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007812 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7813 // This is not safe in general for floating point:
7814 // consider X== -0, Y== +0.
7815 // It becomes safe if either operand is a nonzero constant.
7816 ConstantFP *CFPt, *CFPf;
7817 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7818 !CFPt->getValueAPF().isZero()) ||
7819 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7820 !CFPf->getValueAPF().isZero()))
7821 return ReplaceInstUsesWith(SI, FalseVal);
7822 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007823 // Transform (X != Y) ? Y : X -> Y
7824 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7825 return ReplaceInstUsesWith(SI, TrueVal);
7826 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7827 }
7828 }
7829
7830 // See if we are selecting two values based on a comparison of the two values.
7831 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7832 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7833 // Transform (X == Y) ? X : Y -> Y
7834 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7835 return ReplaceInstUsesWith(SI, FalseVal);
7836 // Transform (X != Y) ? X : Y -> X
7837 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7838 return ReplaceInstUsesWith(SI, TrueVal);
7839 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7840
7841 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7842 // Transform (X == Y) ? Y : X -> X
7843 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7844 return ReplaceInstUsesWith(SI, FalseVal);
7845 // Transform (X != Y) ? Y : X -> Y
7846 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7847 return ReplaceInstUsesWith(SI, TrueVal);
7848 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7849 }
7850 }
7851
7852 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7853 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7854 if (TI->hasOneUse() && FI->hasOneUse()) {
7855 Instruction *AddOp = 0, *SubOp = 0;
7856
7857 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7858 if (TI->getOpcode() == FI->getOpcode())
7859 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7860 return IV;
7861
7862 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7863 // even legal for FP.
7864 if (TI->getOpcode() == Instruction::Sub &&
7865 FI->getOpcode() == Instruction::Add) {
7866 AddOp = FI; SubOp = TI;
7867 } else if (FI->getOpcode() == Instruction::Sub &&
7868 TI->getOpcode() == Instruction::Add) {
7869 AddOp = TI; SubOp = FI;
7870 }
7871
7872 if (AddOp) {
7873 Value *OtherAddOp = 0;
7874 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7875 OtherAddOp = AddOp->getOperand(1);
7876 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7877 OtherAddOp = AddOp->getOperand(0);
7878 }
7879
7880 if (OtherAddOp) {
7881 // So at this point we know we have (Y -> OtherAddOp):
7882 // select C, (add X, Y), (sub X, Z)
7883 Value *NegVal; // Compute -Z
7884 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7885 NegVal = ConstantExpr::getNeg(C);
7886 } else {
7887 NegVal = InsertNewInstBefore(
7888 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7889 }
7890
7891 Value *NewTrueOp = OtherAddOp;
7892 Value *NewFalseOp = NegVal;
7893 if (AddOp != TI)
7894 std::swap(NewTrueOp, NewFalseOp);
7895 Instruction *NewSel =
7896 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7897
7898 NewSel = InsertNewInstBefore(NewSel, SI);
7899 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7900 }
7901 }
7902 }
7903
7904 // See if we can fold the select into one of our operands.
7905 if (SI.getType()->isInteger()) {
7906 // See the comment above GetSelectFoldableOperands for a description of the
7907 // transformation we are doing here.
7908 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7909 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7910 !isa<Constant>(FalseVal))
7911 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7912 unsigned OpToFold = 0;
7913 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7914 OpToFold = 1;
7915 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7916 OpToFold = 2;
7917 }
7918
7919 if (OpToFold) {
7920 Constant *C = GetSelectFoldableConstant(TVI);
7921 Instruction *NewSel =
7922 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7923 InsertNewInstBefore(NewSel, SI);
7924 NewSel->takeName(TVI);
7925 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7926 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7927 else {
7928 assert(0 && "Unknown instruction!!");
7929 }
7930 }
7931 }
7932
7933 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7934 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7935 !isa<Constant>(TrueVal))
7936 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7937 unsigned OpToFold = 0;
7938 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7939 OpToFold = 1;
7940 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7941 OpToFold = 2;
7942 }
7943
7944 if (OpToFold) {
7945 Constant *C = GetSelectFoldableConstant(FVI);
7946 Instruction *NewSel =
7947 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7948 InsertNewInstBefore(NewSel, SI);
7949 NewSel->takeName(FVI);
7950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7951 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7952 else
7953 assert(0 && "Unknown instruction!!");
7954 }
7955 }
7956 }
7957
7958 if (BinaryOperator::isNot(CondVal)) {
7959 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7960 SI.setOperand(1, FalseVal);
7961 SI.setOperand(2, TrueVal);
7962 return &SI;
7963 }
7964
7965 return 0;
7966}
7967
Chris Lattner47cf3452007-08-09 19:05:49 +00007968/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7969/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7970/// and it is more than the alignment of the ultimate object, see if we can
7971/// increase the alignment of the ultimate object, making this check succeed.
7972static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7973 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007974 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7975 unsigned Align = GV->getAlignment();
Andrew Lenharthdae02012007-11-08 18:45:15 +00007976 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007977 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007978
7979 // If there is a large requested alignment and we can, bump up the alignment
7980 // of the global.
7981 if (PrefAlign > Align && GV->hasInitializer()) {
7982 GV->setAlignment(PrefAlign);
7983 Align = PrefAlign;
7984 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 return Align;
7986 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7987 unsigned Align = AI->getAlignment();
7988 if (Align == 0 && TD) {
7989 if (isa<AllocaInst>(AI))
7990 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7991 else if (isa<MallocInst>(AI)) {
7992 // Malloc returns maximally aligned memory.
7993 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7994 Align =
7995 std::max(Align,
7996 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7997 Align =
7998 std::max(Align,
7999 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
8000 }
8001 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008002
8003 // If there is a requested alignment and if this is an alloca, round up. We
8004 // don't do this for malloc, because some systems can't respect the request.
8005 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8006 AI->setAlignment(PrefAlign);
8007 Align = PrefAlign;
8008 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 return Align;
8010 } else if (isa<BitCastInst>(V) ||
8011 (isa<ConstantExpr>(V) &&
8012 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008013 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8014 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008015 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008016 // If all indexes are zero, it is just the alignment of the base pointer.
8017 bool AllZeroOperands = true;
8018 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8019 if (!isa<Constant>(GEPI->getOperand(i)) ||
8020 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8021 AllZeroOperands = false;
8022 break;
8023 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008024
8025 if (AllZeroOperands) {
8026 // Treat this like a bitcast.
8027 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8028 }
8029
8030 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8031 if (BaseAlignment == 0) return 0;
8032
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008033 // Otherwise, if the base alignment is >= the alignment we expect for the
8034 // base pointer type, then we know that the resultant pointer is aligned at
8035 // least as much as its type requires.
8036 if (!TD) return 0;
8037
8038 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
8039 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00008040 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8041 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008042 const Type *GEPTy = GEPI->getType();
8043 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00008044 Align = std::min(Align, (unsigned)
8045 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8046 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008047 }
8048 return 0;
8049 }
8050 return 0;
8051}
8052
Chris Lattner00ae5132008-01-13 23:50:23 +00008053Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8054 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8055 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8056 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8057 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8058
8059 if (CopyAlign < MinAlign) {
8060 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8061 return MI;
8062 }
8063
8064 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8065 // load/store.
8066 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8067 if (MemOpLength == 0) return 0;
8068
Chris Lattnerc669fb62008-01-14 00:28:35 +00008069 // Source and destination pointer types are always "i8*" for intrinsic. See
8070 // if the size is something we can handle with a single primitive load/store.
8071 // A single load+store correctly handles overlapping memory in the memmove
8072 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008073 unsigned Size = MemOpLength->getZExtValue();
8074 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008075 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008076
Chris Lattnerc669fb62008-01-14 00:28:35 +00008077 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008078 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008079
8080 // Memcpy forces the use of i8* for the source and destination. That means
8081 // that if you're using memcpy to move one double around, you'll get a cast
8082 // from double* to i8*. We'd much rather use a double load+store rather than
8083 // an i64 load+store, here because this improves the odds that the source or
8084 // dest address will be promotable. See if we can find a better type than the
8085 // integer datatype.
8086 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8087 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8088 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8089 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8090 // down through these levels if so.
8091 while (!SrcETy->isFirstClassType()) {
8092 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8093 if (STy->getNumElements() == 1)
8094 SrcETy = STy->getElementType(0);
8095 else
8096 break;
8097 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8098 if (ATy->getNumElements() == 1)
8099 SrcETy = ATy->getElementType();
8100 else
8101 break;
8102 } else
8103 break;
8104 }
8105
8106 if (SrcETy->isFirstClassType())
8107 NewPtrTy = PointerType::getUnqual(SrcETy);
8108 }
8109 }
8110
8111
Chris Lattner00ae5132008-01-13 23:50:23 +00008112 // If the memcpy/memmove provides better alignment info than we can
8113 // infer, use it.
8114 SrcAlign = std::max(SrcAlign, CopyAlign);
8115 DstAlign = std::max(DstAlign, CopyAlign);
8116
8117 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8118 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008119 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8120 InsertNewInstBefore(L, *MI);
8121 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8122
8123 // Set the size of the copy to 0, it will be deleted on the next iteration.
8124 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8125 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008126}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008127
8128/// visitCallInst - CallInst simplification. This mostly only handles folding
8129/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8130/// the heavy lifting.
8131///
8132Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8133 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8134 if (!II) return visitCallSite(&CI);
8135
8136 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8137 // visitCallSite.
8138 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8139 bool Changed = false;
8140
8141 // memmove/cpy/set of zero bytes is a noop.
8142 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8143 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8144
8145 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8146 if (CI->getZExtValue() == 1) {
8147 // Replace the instruction with just byte operations. We would
8148 // transform other cases to loads/stores, but we don't know if
8149 // alignment is sufficient.
8150 }
8151 }
8152
8153 // If we have a memmove and the source operation is a constant global,
8154 // then the source and dest pointers can't alias, so we can change this
8155 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008156 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008157 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8158 if (GVSrc->isConstant()) {
8159 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008160 Intrinsic::ID MemCpyID;
8161 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8162 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008163 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008164 MemCpyID = Intrinsic::memcpy_i64;
8165 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008166 Changed = true;
8167 }
8168 }
8169
8170 // If we can determine a pointer alignment that is bigger than currently
8171 // set, update the alignment.
8172 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008173 if (Instruction *I = SimplifyMemTransfer(MI))
8174 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008175 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008176 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008177 if (MI->getAlignment()->getZExtValue() < Alignment) {
8178 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8179 Changed = true;
8180 }
8181 }
8182
8183 if (Changed) return II;
8184 } else {
8185 switch (II->getIntrinsicID()) {
8186 default: break;
8187 case Intrinsic::ppc_altivec_lvx:
8188 case Intrinsic::ppc_altivec_lvxl:
8189 case Intrinsic::x86_sse_loadu_ps:
8190 case Intrinsic::x86_sse2_loadu_pd:
8191 case Intrinsic::x86_sse2_loadu_dq:
8192 // Turn PPC lvx -> load if the pointer is known aligned.
8193 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008194 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008195 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8196 PointerType::getUnqual(II->getType()),
8197 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 return new LoadInst(Ptr);
8199 }
8200 break;
8201 case Intrinsic::ppc_altivec_stvx:
8202 case Intrinsic::ppc_altivec_stvxl:
8203 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008204 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008205 const Type *OpPtrTy =
8206 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008207 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008208 return new StoreInst(II->getOperand(1), Ptr);
8209 }
8210 break;
8211 case Intrinsic::x86_sse_storeu_ps:
8212 case Intrinsic::x86_sse2_storeu_pd:
8213 case Intrinsic::x86_sse2_storeu_dq:
8214 case Intrinsic::x86_sse2_storel_dq:
8215 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008216 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008217 const Type *OpPtrTy =
8218 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008219 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008220 return new StoreInst(II->getOperand(2), Ptr);
8221 }
8222 break;
8223
8224 case Intrinsic::x86_sse_cvttss2si: {
8225 // These intrinsics only demands the 0th element of its input vector. If
8226 // we can simplify the input based on that, do so now.
8227 uint64_t UndefElts;
8228 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8229 UndefElts)) {
8230 II->setOperand(1, V);
8231 return II;
8232 }
8233 break;
8234 }
8235
8236 case Intrinsic::ppc_altivec_vperm:
8237 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8238 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8239 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8240
8241 // Check that all of the elements are integer constants or undefs.
8242 bool AllEltsOk = true;
8243 for (unsigned i = 0; i != 16; ++i) {
8244 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8245 !isa<UndefValue>(Mask->getOperand(i))) {
8246 AllEltsOk = false;
8247 break;
8248 }
8249 }
8250
8251 if (AllEltsOk) {
8252 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008253 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8254 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255 Value *Result = UndefValue::get(Op0->getType());
8256
8257 // Only extract each element once.
8258 Value *ExtractedElts[32];
8259 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8260
8261 for (unsigned i = 0; i != 16; ++i) {
8262 if (isa<UndefValue>(Mask->getOperand(i)))
8263 continue;
8264 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8265 Idx &= 31; // Match the hardware behavior.
8266
8267 if (ExtractedElts[Idx] == 0) {
8268 Instruction *Elt =
8269 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8270 InsertNewInstBefore(Elt, CI);
8271 ExtractedElts[Idx] = Elt;
8272 }
8273
8274 // Insert this value into the result vector.
8275 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8276 InsertNewInstBefore(cast<Instruction>(Result), CI);
8277 }
8278 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8279 }
8280 }
8281 break;
8282
8283 case Intrinsic::stackrestore: {
8284 // If the save is right next to the restore, remove the restore. This can
8285 // happen when variable allocas are DCE'd.
8286 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8287 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8288 BasicBlock::iterator BI = SS;
8289 if (&*++BI == II)
8290 return EraseInstFromFunction(CI);
8291 }
8292 }
8293
Chris Lattner416d91c2008-02-18 06:12:38 +00008294 // Scan down this block to see if there is another stack restore in the
8295 // same block without an intervening call/alloca.
8296 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008297 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008298 bool CannotRemove = false;
8299 for (++BI; &*BI != TI; ++BI) {
8300 if (isa<AllocaInst>(BI)) {
8301 CannotRemove = true;
8302 break;
8303 }
8304 if (isa<CallInst>(BI)) {
8305 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008306 CannotRemove = true;
8307 break;
8308 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008309 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008310 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008311 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008312 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008313
8314 // If the stack restore is in a return/unwind block and if there are no
8315 // allocas or calls between the restore and the return, nuke the restore.
8316 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8317 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 break;
8319 }
8320 }
8321 }
8322
8323 return visitCallSite(II);
8324}
8325
8326// InvokeInst simplification
8327//
8328Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8329 return visitCallSite(&II);
8330}
8331
8332// visitCallSite - Improvements for call and invoke instructions.
8333//
8334Instruction *InstCombiner::visitCallSite(CallSite CS) {
8335 bool Changed = false;
8336
8337 // If the callee is a constexpr cast of a function, attempt to move the cast
8338 // to the arguments of the call/invoke.
8339 if (transformConstExprCastCall(CS)) return 0;
8340
8341 Value *Callee = CS.getCalledValue();
8342
8343 if (Function *CalleeF = dyn_cast<Function>(Callee))
8344 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8345 Instruction *OldCall = CS.getInstruction();
8346 // If the call and callee calling conventions don't match, this call must
8347 // be unreachable, as the call is undefined.
8348 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008349 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8350 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008351 if (!OldCall->use_empty())
8352 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8353 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8354 return EraseInstFromFunction(*OldCall);
8355 return 0;
8356 }
8357
8358 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8359 // This instruction is not reachable, just remove it. We insert a store to
8360 // undef so that we know that this code is not reachable, despite the fact
8361 // that we can't modify the CFG here.
8362 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008363 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008364 CS.getInstruction());
8365
8366 if (!CS.getInstruction()->use_empty())
8367 CS.getInstruction()->
8368 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8369
8370 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8371 // Don't break the CFG, insert a dummy cond branch.
8372 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8373 ConstantInt::getTrue(), II);
8374 }
8375 return EraseInstFromFunction(*CS.getInstruction());
8376 }
8377
Duncan Sands74833f22007-09-17 10:26:40 +00008378 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8379 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8380 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8381 return transformCallThroughTrampoline(CS);
8382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008383 const PointerType *PTy = cast<PointerType>(Callee->getType());
8384 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8385 if (FTy->isVarArg()) {
8386 // See if we can optimize any arguments passed through the varargs area of
8387 // the call.
8388 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8389 E = CS.arg_end(); I != E; ++I)
8390 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8391 // If this cast does not effect the value passed through the varargs
8392 // area, we can eliminate the use of the cast.
8393 Value *Op = CI->getOperand(0);
8394 if (CI->isLosslessCast()) {
8395 *I = Op;
8396 Changed = true;
8397 }
8398 }
8399 }
8400
Duncan Sands2937e352007-12-19 21:13:37 +00008401 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008402 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008403 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008404 Changed = true;
8405 }
8406
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008407 return Changed ? CS.getInstruction() : 0;
8408}
8409
8410// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8411// attempt to move the cast to the arguments of the call/invoke.
8412//
8413bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8414 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8415 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8416 if (CE->getOpcode() != Instruction::BitCast ||
8417 !isa<Function>(CE->getOperand(0)))
8418 return false;
8419 Function *Callee = cast<Function>(CE->getOperand(0));
8420 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008421 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008422
8423 // Okay, this is a cast from a function to a different type. Unless doing so
8424 // would cause a type conversion of one of our arguments, change this call to
8425 // be a direct call with arguments casted to the appropriate types.
8426 //
8427 const FunctionType *FT = Callee->getFunctionType();
8428 const Type *OldRetTy = Caller->getType();
8429
Devang Pateld091d322008-03-11 18:04:06 +00008430 if (isa<StructType>(FT->getReturnType()))
8431 return false; // TODO: Handle multiple return values.
8432
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 // Check to see if we are changing the return type...
8434 if (OldRetTy != FT->getReturnType()) {
8435 if (Callee->isDeclaration() && !Caller->use_empty() &&
8436 // Conversion is ok if changing from pointer to int of same size.
8437 !(isa<PointerType>(FT->getReturnType()) &&
8438 TD->getIntPtrType() == OldRetTy))
8439 return false; // Cannot transform this return value.
8440
Duncan Sands5c489582008-01-06 10:12:28 +00008441 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008442 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008443 FT->getReturnType() != Type::VoidTy &&
8444 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008445 return false; // Cannot transform this return value.
8446
Chris Lattner1c8733e2008-03-12 17:45:29 +00008447 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8448 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008449 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8450 return false; // Attribute not compatible with transformed value.
8451 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008452
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008453 // If the callsite is an invoke instruction, and the return value is used by
8454 // a PHI node in a successor, we cannot change the return type of the call
8455 // because there is no place to put the cast instruction (without breaking
8456 // the critical edge). Bail out in this case.
8457 if (!Caller->use_empty())
8458 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8459 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8460 UI != E; ++UI)
8461 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8462 if (PN->getParent() == II->getNormalDest() ||
8463 PN->getParent() == II->getUnwindDest())
8464 return false;
8465 }
8466
8467 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8468 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8469
8470 CallSite::arg_iterator AI = CS.arg_begin();
8471 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8472 const Type *ParamTy = FT->getParamType(i);
8473 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008474
8475 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008476 return false; // Cannot transform this parameter value.
8477
Chris Lattner1c8733e2008-03-12 17:45:29 +00008478 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8479 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008480
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008481 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008482 // Some conversions are safe even if we do not have a body.
8483 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008484 bool isConvertible = ActTy == ParamTy ||
8485 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8486 (ParamTy->isInteger() && ActTy->isInteger() &&
8487 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8488 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8489 && c->getValue().isStrictlyPositive());
8490 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008491 }
8492
8493 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8494 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00008495 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008496
Chris Lattner1c8733e2008-03-12 17:45:29 +00008497 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8498 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00008499 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008500 // won't be dropping them. Check that these extra arguments have attributes
8501 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008502 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8503 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00008504 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008505 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00008506 if (PAttrs & ParamAttr::VarArgsIncompatible)
8507 return false;
8508 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008509
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008510 // Okay, we decided that this is a safe thing to do: go ahead and start
8511 // inserting cast instructions as necessary...
8512 std::vector<Value*> Args;
8513 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008514 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00008515 attrVec.reserve(NumCommonArgs);
8516
8517 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008518 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00008519
8520 // If the return value is not being used, the type may not be compatible
8521 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008522 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008523
8524 // Add the new return attributes.
8525 if (RAttrs)
8526 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008527
8528 AI = CS.arg_begin();
8529 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8530 const Type *ParamTy = FT->getParamType(i);
8531 if ((*AI)->getType() == ParamTy) {
8532 Args.push_back(*AI);
8533 } else {
8534 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8535 false, ParamTy, false);
8536 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8537 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8538 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008539
8540 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008541 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00008542 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008543 }
8544
8545 // If the function takes more arguments than the call was taking, add them
8546 // now...
8547 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8548 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8549
8550 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008551 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008552 if (!FT->isVarArg()) {
8553 cerr << "WARNING: While resolving call to function '"
8554 << Callee->getName() << "' arguments were dropped!\n";
8555 } else {
8556 // Add all of the arguments in their promoted form to the arg list...
8557 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8558 const Type *PTy = getPromotedType((*AI)->getType());
8559 if (PTy != (*AI)->getType()) {
8560 // Must promote to pass through va_arg area!
8561 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8562 PTy, false);
8563 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8564 InsertNewInstBefore(Cast, *Caller);
8565 Args.push_back(Cast);
8566 } else {
8567 Args.push_back(*AI);
8568 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008569
Duncan Sands4ced1f82008-01-13 08:02:44 +00008570 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008571 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00008572 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8573 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008574 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008575 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008576
8577 if (FT->getReturnType() == Type::VoidTy)
8578 Caller->setName(""); // Void type should not have a name.
8579
Chris Lattner1c8733e2008-03-12 17:45:29 +00008580 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00008581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008582 Instruction *NC;
8583 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8584 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008585 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008586 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008587 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008588 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008589 NC = new CallInst(Callee, Args.begin(), Args.end(),
8590 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008591 CallInst *CI = cast<CallInst>(Caller);
8592 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008593 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008594 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008595 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008596 }
8597
8598 // Insert a cast of the return type as necessary.
8599 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008600 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008601 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008602 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008603 OldRetTy, false);
8604 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008605
8606 // If this is an invoke instruction, we should insert it after the first
8607 // non-phi, instruction in the normal successor block.
8608 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8609 BasicBlock::iterator I = II->getNormalDest()->begin();
8610 while (isa<PHINode>(I)) ++I;
8611 InsertNewInstBefore(NC, *I);
8612 } else {
8613 // Otherwise, it's a call, just insert cast right after the call instr
8614 InsertNewInstBefore(NC, *Caller);
8615 }
8616 AddUsersToWorkList(*Caller);
8617 } else {
8618 NV = UndefValue::get(Caller->getType());
8619 }
8620 }
8621
8622 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8623 Caller->replaceAllUsesWith(NV);
8624 Caller->eraseFromParent();
8625 RemoveFromWorkList(Caller);
8626 return true;
8627}
8628
Duncan Sands74833f22007-09-17 10:26:40 +00008629// transformCallThroughTrampoline - Turn a call to a function created by the
8630// init_trampoline intrinsic into a direct call to the underlying function.
8631//
8632Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8633 Value *Callee = CS.getCalledValue();
8634 const PointerType *PTy = cast<PointerType>(Callee->getType());
8635 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00008636 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00008637
8638 // If the call already has the 'nest' attribute somewhere then give up -
8639 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008640 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00008641 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008642
8643 IntrinsicInst *Tramp =
8644 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8645
8646 Function *NestF =
8647 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8648 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8649 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8650
Chris Lattner1c8733e2008-03-12 17:45:29 +00008651 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8652 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008653 unsigned NestIdx = 1;
8654 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00008655 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00008656
8657 // Look for a parameter marked with the 'nest' attribute.
8658 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8659 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00008660 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00008661 // Record the parameter type and any other attributes.
8662 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008663 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00008664 break;
8665 }
8666
8667 if (NestTy) {
8668 Instruction *Caller = CS.getInstruction();
8669 std::vector<Value*> NewArgs;
8670 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8671
Chris Lattner1c8733e2008-03-12 17:45:29 +00008672 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8673 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00008674
Duncan Sands74833f22007-09-17 10:26:40 +00008675 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008676 // mean appending it. Likewise for attributes.
8677
8678 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008679 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8680 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00008681
Duncan Sands74833f22007-09-17 10:26:40 +00008682 {
8683 unsigned Idx = 1;
8684 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8685 do {
8686 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008687 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008688 Value *NestVal = Tramp->getOperand(3);
8689 if (NestVal->getType() != NestTy)
8690 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8691 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008692 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008693 }
8694
8695 if (I == E)
8696 break;
8697
Duncan Sands48b81112008-01-14 19:52:09 +00008698 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008699 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008700 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00008701 NewAttrs.push_back
8702 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008703
8704 ++Idx, ++I;
8705 } while (1);
8706 }
8707
8708 // The trampoline may have been bitcast to a bogus type (FTy).
8709 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008710 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008711
Duncan Sands74833f22007-09-17 10:26:40 +00008712 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008713 NewTypes.reserve(FTy->getNumParams()+1);
8714
Duncan Sands74833f22007-09-17 10:26:40 +00008715 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008716 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008717 {
8718 unsigned Idx = 1;
8719 FunctionType::param_iterator I = FTy->param_begin(),
8720 E = FTy->param_end();
8721
8722 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008723 if (Idx == NestIdx)
8724 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008725 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008726
8727 if (I == E)
8728 break;
8729
Duncan Sands48b81112008-01-14 19:52:09 +00008730 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008731 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008732
8733 ++Idx, ++I;
8734 } while (1);
8735 }
8736
8737 // Replace the trampoline call with a direct call. Let the generic
8738 // code sort out any function type mismatches.
8739 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008740 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008741 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8742 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00008743 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00008744
8745 Instruction *NewCaller;
8746 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8747 NewCaller = new InvokeInst(NewCallee,
8748 II->getNormalDest(), II->getUnwindDest(),
8749 NewArgs.begin(), NewArgs.end(),
8750 Caller->getName(), Caller);
8751 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008752 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008753 } else {
8754 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8755 Caller->getName(), Caller);
8756 if (cast<CallInst>(Caller)->isTailCall())
8757 cast<CallInst>(NewCaller)->setTailCall();
8758 cast<CallInst>(NewCaller)->
8759 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008760 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008761 }
8762 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8763 Caller->replaceAllUsesWith(NewCaller);
8764 Caller->eraseFromParent();
8765 RemoveFromWorkList(Caller);
8766 return 0;
8767 }
8768 }
8769
8770 // Replace the trampoline call with a direct call. Since there is no 'nest'
8771 // parameter, there is no need to adjust the argument list. Let the generic
8772 // code sort out any function type mismatches.
8773 Constant *NewCallee =
8774 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8775 CS.setCalledFunction(NewCallee);
8776 return CS.getInstruction();
8777}
8778
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008779/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8780/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8781/// and a single binop.
8782Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8783 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8784 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8785 isa<CmpInst>(FirstInst));
8786 unsigned Opc = FirstInst->getOpcode();
8787 Value *LHSVal = FirstInst->getOperand(0);
8788 Value *RHSVal = FirstInst->getOperand(1);
8789
8790 const Type *LHSType = LHSVal->getType();
8791 const Type *RHSType = RHSVal->getType();
8792
8793 // Scan to see if all operands are the same opcode, all have one use, and all
8794 // kill their operands (i.e. the operands have one use).
8795 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8796 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8797 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8798 // Verify type of the LHS matches so we don't fold cmp's of different
8799 // types or GEP's with different index types.
8800 I->getOperand(0)->getType() != LHSType ||
8801 I->getOperand(1)->getType() != RHSType)
8802 return 0;
8803
8804 // If they are CmpInst instructions, check their predicates
8805 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8806 if (cast<CmpInst>(I)->getPredicate() !=
8807 cast<CmpInst>(FirstInst)->getPredicate())
8808 return 0;
8809
8810 // Keep track of which operand needs a phi node.
8811 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8812 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8813 }
8814
8815 // Otherwise, this is safe to transform, determine if it is profitable.
8816
8817 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8818 // Indexes are often folded into load/store instructions, so we don't want to
8819 // hide them behind a phi.
8820 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8821 return 0;
8822
8823 Value *InLHS = FirstInst->getOperand(0);
8824 Value *InRHS = FirstInst->getOperand(1);
8825 PHINode *NewLHS = 0, *NewRHS = 0;
8826 if (LHSVal == 0) {
8827 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8828 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8829 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8830 InsertNewInstBefore(NewLHS, PN);
8831 LHSVal = NewLHS;
8832 }
8833
8834 if (RHSVal == 0) {
8835 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8836 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8837 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8838 InsertNewInstBefore(NewRHS, PN);
8839 RHSVal = NewRHS;
8840 }
8841
8842 // Add all operands to the new PHIs.
8843 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8844 if (NewLHS) {
8845 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8846 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8847 }
8848 if (NewRHS) {
8849 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8850 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8851 }
8852 }
8853
8854 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8855 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8856 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8857 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8858 RHSVal);
8859 else {
8860 assert(isa<GetElementPtrInst>(FirstInst));
8861 return new GetElementPtrInst(LHSVal, RHSVal);
8862 }
8863}
8864
8865/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8866/// of the block that defines it. This means that it must be obvious the value
8867/// of the load is not changed from the point of the load to the end of the
8868/// block it is in.
8869///
8870/// Finally, it is safe, but not profitable, to sink a load targetting a
8871/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8872/// to a register.
8873static bool isSafeToSinkLoad(LoadInst *L) {
8874 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8875
8876 for (++BBI; BBI != E; ++BBI)
8877 if (BBI->mayWriteToMemory())
8878 return false;
8879
8880 // Check for non-address taken alloca. If not address-taken already, it isn't
8881 // profitable to do this xform.
8882 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8883 bool isAddressTaken = false;
8884 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8885 UI != E; ++UI) {
8886 if (isa<LoadInst>(UI)) continue;
8887 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8888 // If storing TO the alloca, then the address isn't taken.
8889 if (SI->getOperand(1) == AI) continue;
8890 }
8891 isAddressTaken = true;
8892 break;
8893 }
8894
8895 if (!isAddressTaken)
8896 return false;
8897 }
8898
8899 return true;
8900}
8901
8902
8903// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8904// operator and they all are only used by the PHI, PHI together their
8905// inputs, and do the operation once, to the result of the PHI.
8906Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8907 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8908
8909 // Scan the instruction, looking for input operations that can be folded away.
8910 // If all input operands to the phi are the same instruction (e.g. a cast from
8911 // the same type or "+42") we can pull the operation through the PHI, reducing
8912 // code size and simplifying code.
8913 Constant *ConstantOp = 0;
8914 const Type *CastSrcTy = 0;
8915 bool isVolatile = false;
8916 if (isa<CastInst>(FirstInst)) {
8917 CastSrcTy = FirstInst->getOperand(0)->getType();
8918 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8919 // Can fold binop, compare or shift here if the RHS is a constant,
8920 // otherwise call FoldPHIArgBinOpIntoPHI.
8921 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8922 if (ConstantOp == 0)
8923 return FoldPHIArgBinOpIntoPHI(PN);
8924 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8925 isVolatile = LI->isVolatile();
8926 // We can't sink the load if the loaded value could be modified between the
8927 // load and the PHI.
8928 if (LI->getParent() != PN.getIncomingBlock(0) ||
8929 !isSafeToSinkLoad(LI))
8930 return 0;
8931 } else if (isa<GetElementPtrInst>(FirstInst)) {
8932 if (FirstInst->getNumOperands() == 2)
8933 return FoldPHIArgBinOpIntoPHI(PN);
8934 // Can't handle general GEPs yet.
8935 return 0;
8936 } else {
8937 return 0; // Cannot fold this operation.
8938 }
8939
8940 // Check to see if all arguments are the same operation.
8941 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8942 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8943 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8944 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8945 return 0;
8946 if (CastSrcTy) {
8947 if (I->getOperand(0)->getType() != CastSrcTy)
8948 return 0; // Cast operation must match.
8949 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8950 // We can't sink the load if the loaded value could be modified between
8951 // the load and the PHI.
8952 if (LI->isVolatile() != isVolatile ||
8953 LI->getParent() != PN.getIncomingBlock(i) ||
8954 !isSafeToSinkLoad(LI))
8955 return 0;
8956 } else if (I->getOperand(1) != ConstantOp) {
8957 return 0;
8958 }
8959 }
8960
8961 // Okay, they are all the same operation. Create a new PHI node of the
8962 // correct type, and PHI together all of the LHS's of the instructions.
8963 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8964 PN.getName()+".in");
8965 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8966
8967 Value *InVal = FirstInst->getOperand(0);
8968 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8969
8970 // Add all operands to the new PHI.
8971 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8972 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8973 if (NewInVal != InVal)
8974 InVal = 0;
8975 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8976 }
8977
8978 Value *PhiVal;
8979 if (InVal) {
8980 // The new PHI unions all of the same values together. This is really
8981 // common, so we handle it intelligently here for compile-time speed.
8982 PhiVal = InVal;
8983 delete NewPN;
8984 } else {
8985 InsertNewInstBefore(NewPN, PN);
8986 PhiVal = NewPN;
8987 }
8988
8989 // Insert and return the new operation.
8990 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8991 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8992 else if (isa<LoadInst>(FirstInst))
8993 return new LoadInst(PhiVal, "", isVolatile);
8994 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8995 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8996 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8997 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8998 PhiVal, ConstantOp);
8999 else
9000 assert(0 && "Unknown operation");
9001 return 0;
9002}
9003
9004/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9005/// that is dead.
9006static bool DeadPHICycle(PHINode *PN,
9007 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9008 if (PN->use_empty()) return true;
9009 if (!PN->hasOneUse()) return false;
9010
9011 // Remember this node, and if we find the cycle, return.
9012 if (!PotentiallyDeadPHIs.insert(PN))
9013 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009014
9015 // Don't scan crazily complex things.
9016 if (PotentiallyDeadPHIs.size() == 16)
9017 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009018
9019 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9020 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9021
9022 return false;
9023}
9024
Chris Lattner27b695d2007-11-06 21:52:06 +00009025/// PHIsEqualValue - Return true if this phi node is always equal to
9026/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9027/// z = some value; x = phi (y, z); y = phi (x, z)
9028static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9029 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9030 // See if we already saw this PHI node.
9031 if (!ValueEqualPHIs.insert(PN))
9032 return true;
9033
9034 // Don't scan crazily complex things.
9035 if (ValueEqualPHIs.size() == 16)
9036 return false;
9037
9038 // Scan the operands to see if they are either phi nodes or are equal to
9039 // the value.
9040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9041 Value *Op = PN->getIncomingValue(i);
9042 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9043 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9044 return false;
9045 } else if (Op != NonPhiInVal)
9046 return false;
9047 }
9048
9049 return true;
9050}
9051
9052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009053// PHINode simplification
9054//
9055Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9056 // If LCSSA is around, don't mess with Phi nodes
9057 if (MustPreserveLCSSA) return 0;
9058
9059 if (Value *V = PN.hasConstantValue())
9060 return ReplaceInstUsesWith(PN, V);
9061
9062 // If all PHI operands are the same operation, pull them through the PHI,
9063 // reducing code size.
9064 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9065 PN.getIncomingValue(0)->hasOneUse())
9066 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9067 return Result;
9068
9069 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9070 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9071 // PHI)... break the cycle.
9072 if (PN.hasOneUse()) {
9073 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9074 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9075 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9076 PotentiallyDeadPHIs.insert(&PN);
9077 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9078 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9079 }
9080
9081 // If this phi has a single use, and if that use just computes a value for
9082 // the next iteration of a loop, delete the phi. This occurs with unused
9083 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9084 // common case here is good because the only other things that catch this
9085 // are induction variable analysis (sometimes) and ADCE, which is only run
9086 // late.
9087 if (PHIUser->hasOneUse() &&
9088 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9089 PHIUser->use_back() == &PN) {
9090 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9091 }
9092 }
9093
Chris Lattner27b695d2007-11-06 21:52:06 +00009094 // We sometimes end up with phi cycles that non-obviously end up being the
9095 // same value, for example:
9096 // z = some value; x = phi (y, z); y = phi (x, z)
9097 // where the phi nodes don't necessarily need to be in the same block. Do a
9098 // quick check to see if the PHI node only contains a single non-phi value, if
9099 // so, scan to see if the phi cycle is actually equal to that value.
9100 {
9101 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9102 // Scan for the first non-phi operand.
9103 while (InValNo != NumOperandVals &&
9104 isa<PHINode>(PN.getIncomingValue(InValNo)))
9105 ++InValNo;
9106
9107 if (InValNo != NumOperandVals) {
9108 Value *NonPhiInVal = PN.getOperand(InValNo);
9109
9110 // Scan the rest of the operands to see if there are any conflicts, if so
9111 // there is no need to recursively scan other phis.
9112 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9113 Value *OpVal = PN.getIncomingValue(InValNo);
9114 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9115 break;
9116 }
9117
9118 // If we scanned over all operands, then we have one unique value plus
9119 // phi values. Scan PHI nodes to see if they all merge in each other or
9120 // the value.
9121 if (InValNo == NumOperandVals) {
9122 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9123 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9124 return ReplaceInstUsesWith(PN, NonPhiInVal);
9125 }
9126 }
9127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009128 return 0;
9129}
9130
9131static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9132 Instruction *InsertPoint,
9133 InstCombiner *IC) {
9134 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9135 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9136 // We must cast correctly to the pointer type. Ensure that we
9137 // sign extend the integer value if it is smaller as this is
9138 // used for address computation.
9139 Instruction::CastOps opcode =
9140 (VTySize < PtrSize ? Instruction::SExt :
9141 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9142 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9143}
9144
9145
9146Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9147 Value *PtrOp = GEP.getOperand(0);
9148 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9149 // If so, eliminate the noop.
9150 if (GEP.getNumOperands() == 1)
9151 return ReplaceInstUsesWith(GEP, PtrOp);
9152
9153 if (isa<UndefValue>(GEP.getOperand(0)))
9154 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9155
9156 bool HasZeroPointerIndex = false;
9157 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9158 HasZeroPointerIndex = C->isNullValue();
9159
9160 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9161 return ReplaceInstUsesWith(GEP, PtrOp);
9162
9163 // Eliminate unneeded casts for indices.
9164 bool MadeChange = false;
9165
9166 gep_type_iterator GTI = gep_type_begin(GEP);
9167 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9168 if (isa<SequentialType>(*GTI)) {
9169 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9170 if (CI->getOpcode() == Instruction::ZExt ||
9171 CI->getOpcode() == Instruction::SExt) {
9172 const Type *SrcTy = CI->getOperand(0)->getType();
9173 // We can eliminate a cast from i32 to i64 iff the target
9174 // is a 32-bit pointer target.
9175 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9176 MadeChange = true;
9177 GEP.setOperand(i, CI->getOperand(0));
9178 }
9179 }
9180 }
9181 // If we are using a wider index than needed for this platform, shrink it
9182 // to what we need. If the incoming value needs a cast instruction,
9183 // insert it. This explicit cast can make subsequent optimizations more
9184 // obvious.
9185 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009186 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009187 if (Constant *C = dyn_cast<Constant>(Op)) {
9188 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9189 MadeChange = true;
9190 } else {
9191 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9192 GEP);
9193 GEP.setOperand(i, Op);
9194 MadeChange = true;
9195 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009196 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009197 }
9198 }
9199 if (MadeChange) return &GEP;
9200
9201 // If this GEP instruction doesn't move the pointer, and if the input operand
9202 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9203 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009204 if (GEP.hasAllZeroIndices()) {
9205 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9206 // If the bitcast is of an allocation, and the allocation will be
9207 // converted to match the type of the cast, don't touch this.
9208 if (isa<AllocationInst>(BCI->getOperand(0))) {
9209 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009210 if (Instruction *I = visitBitCast(*BCI)) {
9211 if (I != BCI) {
9212 I->takeName(BCI);
9213 BCI->getParent()->getInstList().insert(BCI, I);
9214 ReplaceInstUsesWith(*BCI, I);
9215 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009216 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009217 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009218 }
9219 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9220 }
9221 }
9222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009223 // Combine Indices - If the source pointer to this getelementptr instruction
9224 // is a getelementptr instruction, combine the indices of the two
9225 // getelementptr instructions into a single instruction.
9226 //
9227 SmallVector<Value*, 8> SrcGEPOperands;
9228 if (User *Src = dyn_castGetElementPtr(PtrOp))
9229 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9230
9231 if (!SrcGEPOperands.empty()) {
9232 // Note that if our source is a gep chain itself that we wait for that
9233 // chain to be resolved before we perform this transformation. This
9234 // avoids us creating a TON of code in some cases.
9235 //
9236 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9237 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9238 return 0; // Wait until our source is folded to completion.
9239
9240 SmallVector<Value*, 8> Indices;
9241
9242 // Find out whether the last index in the source GEP is a sequential idx.
9243 bool EndsWithSequential = false;
9244 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9245 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9246 EndsWithSequential = !isa<StructType>(*I);
9247
9248 // Can we combine the two pointer arithmetics offsets?
9249 if (EndsWithSequential) {
9250 // Replace: gep (gep %P, long B), long A, ...
9251 // With: T = long A+B; gep %P, T, ...
9252 //
9253 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9254 if (SO1 == Constant::getNullValue(SO1->getType())) {
9255 Sum = GO1;
9256 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9257 Sum = SO1;
9258 } else {
9259 // If they aren't the same type, convert both to an integer of the
9260 // target's pointer size.
9261 if (SO1->getType() != GO1->getType()) {
9262 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9263 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9264 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9265 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9266 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009267 unsigned PS = TD->getPointerSizeInBits();
9268 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009269 // Convert GO1 to SO1's type.
9270 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9271
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009272 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009273 // Convert SO1 to GO1's type.
9274 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9275 } else {
9276 const Type *PT = TD->getIntPtrType();
9277 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9278 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9279 }
9280 }
9281 }
9282 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9283 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9284 else {
9285 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9286 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9287 }
9288 }
9289
9290 // Recycle the GEP we already have if possible.
9291 if (SrcGEPOperands.size() == 2) {
9292 GEP.setOperand(0, SrcGEPOperands[0]);
9293 GEP.setOperand(1, Sum);
9294 return &GEP;
9295 } else {
9296 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9297 SrcGEPOperands.end()-1);
9298 Indices.push_back(Sum);
9299 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9300 }
9301 } else if (isa<Constant>(*GEP.idx_begin()) &&
9302 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9303 SrcGEPOperands.size() != 1) {
9304 // Otherwise we can do the fold if the first index of the GEP is a zero
9305 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9306 SrcGEPOperands.end());
9307 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9308 }
9309
9310 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00009311 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9312 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009313
9314 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9315 // GEP of global variable. If all of the indices for this GEP are
9316 // constants, we can promote this to a constexpr instead of an instruction.
9317
9318 // Scan for nonconstants...
9319 SmallVector<Constant*, 8> Indices;
9320 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9321 for (; I != E && isa<Constant>(*I); ++I)
9322 Indices.push_back(cast<Constant>(*I));
9323
9324 if (I == E) { // If they are all constants...
9325 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9326 &Indices[0],Indices.size());
9327
9328 // Replace all uses of the GEP with the new constexpr...
9329 return ReplaceInstUsesWith(GEP, CE);
9330 }
9331 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9332 if (!isa<PointerType>(X->getType())) {
9333 // Not interesting. Source pointer must be a cast from pointer.
9334 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009335 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9336 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009337 //
9338 // This occurs when the program declares an array extern like "int X[];"
9339 //
9340 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9341 const PointerType *XTy = cast<PointerType>(X->getType());
9342 if (const ArrayType *XATy =
9343 dyn_cast<ArrayType>(XTy->getElementType()))
9344 if (const ArrayType *CATy =
9345 dyn_cast<ArrayType>(CPTy->getElementType()))
9346 if (CATy->getElementType() == XATy->getElementType()) {
9347 // At this point, we know that the cast source type is a pointer
9348 // to an array of the same type as the destination pointer
9349 // array. Because the array type is never stepped over (there
9350 // is a leading zero) we can fold the cast into this GEP.
9351 GEP.setOperand(0, X);
9352 return &GEP;
9353 }
9354 } else if (GEP.getNumOperands() == 2) {
9355 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009356 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9357 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009358 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9359 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9360 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009361 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9362 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009363 Value *Idx[2];
9364 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9365 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009366 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00009367 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009368 // V and GEP are both pointer types --> BitCast
9369 return new BitCastInst(V, GEP.getType());
9370 }
9371
9372 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009373 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009374 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009375 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009377 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009378 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009379 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009380
9381 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9382 // allow either a mul, shift, or constant here.
9383 Value *NewIdx = 0;
9384 ConstantInt *Scale = 0;
9385 if (ArrayEltSize == 1) {
9386 NewIdx = GEP.getOperand(1);
9387 Scale = ConstantInt::get(NewIdx->getType(), 1);
9388 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9389 NewIdx = ConstantInt::get(CI->getType(), 1);
9390 Scale = CI;
9391 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9392 if (Inst->getOpcode() == Instruction::Shl &&
9393 isa<ConstantInt>(Inst->getOperand(1))) {
9394 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9395 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9396 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9397 NewIdx = Inst->getOperand(0);
9398 } else if (Inst->getOpcode() == Instruction::Mul &&
9399 isa<ConstantInt>(Inst->getOperand(1))) {
9400 Scale = cast<ConstantInt>(Inst->getOperand(1));
9401 NewIdx = Inst->getOperand(0);
9402 }
9403 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009405 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009406 // out, perform the transformation. Note, we don't know whether Scale is
9407 // signed or not. We'll use unsigned version of division/modulo
9408 // operation after making sure Scale doesn't have the sign bit set.
9409 if (Scale && Scale->getSExtValue() >= 0LL &&
9410 Scale->getZExtValue() % ArrayEltSize == 0) {
9411 Scale = ConstantInt::get(Scale->getType(),
9412 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009413 if (Scale->getZExtValue() != 1) {
9414 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009415 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009416 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9417 NewIdx = InsertNewInstBefore(Sc, GEP);
9418 }
9419
9420 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009421 Value *Idx[2];
9422 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9423 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009424 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00009425 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009426 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9427 // The NewGEP must be pointer typed, so must the old one -> BitCast
9428 return new BitCastInst(NewGEP, GEP.getType());
9429 }
9430 }
9431 }
9432 }
9433
9434 return 0;
9435}
9436
9437Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9438 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009439 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009440 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9441 const Type *NewTy =
9442 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9443 AllocationInst *New = 0;
9444
9445 // Create and insert the replacement instruction...
9446 if (isa<MallocInst>(AI))
9447 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9448 else {
9449 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9450 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9451 }
9452
9453 InsertNewInstBefore(New, AI);
9454
9455 // Scan to the end of the allocation instructions, to skip over a block of
9456 // allocas if possible...
9457 //
9458 BasicBlock::iterator It = New;
9459 while (isa<AllocationInst>(*It)) ++It;
9460
9461 // Now that I is pointing to the first non-allocation-inst in the block,
9462 // insert our getelementptr instruction...
9463 //
9464 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009465 Value *Idx[2];
9466 Idx[0] = NullIdx;
9467 Idx[1] = NullIdx;
9468 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009469 New->getName()+".sub", It);
9470
9471 // Now make everything use the getelementptr instead of the original
9472 // allocation.
9473 return ReplaceInstUsesWith(AI, V);
9474 } else if (isa<UndefValue>(AI.getArraySize())) {
9475 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9476 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009477 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009478
9479 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9480 // Note that we only do this for alloca's, because malloc should allocate and
9481 // return a unique pointer, even for a zero byte allocation.
9482 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009483 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009484 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9485
9486 return 0;
9487}
9488
9489Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9490 Value *Op = FI.getOperand(0);
9491
9492 // free undef -> unreachable.
9493 if (isa<UndefValue>(Op)) {
9494 // Insert a new store to null because we cannot modify the CFG here.
9495 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009496 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009497 return EraseInstFromFunction(FI);
9498 }
9499
9500 // If we have 'free null' delete the instruction. This can happen in stl code
9501 // when lots of inlining happens.
9502 if (isa<ConstantPointerNull>(Op))
9503 return EraseInstFromFunction(FI);
9504
9505 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9506 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9507 FI.setOperand(0, CI->getOperand(0));
9508 return &FI;
9509 }
9510
9511 // Change free (gep X, 0,0,0,0) into free(X)
9512 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9513 if (GEPI->hasAllZeroIndices()) {
9514 AddToWorkList(GEPI);
9515 FI.setOperand(0, GEPI->getOperand(0));
9516 return &FI;
9517 }
9518 }
9519
9520 // Change free(malloc) into nothing, if the malloc has a single use.
9521 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9522 if (MI->hasOneUse()) {
9523 EraseInstFromFunction(FI);
9524 return EraseInstFromFunction(*MI);
9525 }
9526
9527 return 0;
9528}
9529
9530
9531/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009532static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00009533 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009534 User *CI = cast<User>(LI.getOperand(0));
9535 Value *CastOp = CI->getOperand(0);
9536
Devang Patela0f8ea82007-10-18 19:52:32 +00009537 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9538 // Instead of loading constant c string, use corresponding integer value
9539 // directly if string length is small enough.
9540 const std::string &Str = CE->getOperand(0)->getStringValue();
9541 if (!Str.empty()) {
9542 unsigned len = Str.length();
9543 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9544 unsigned numBits = Ty->getPrimitiveSizeInBits();
9545 // Replace LI with immediate integer store.
9546 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00009547 APInt StrVal(numBits, 0);
9548 APInt SingleChar(numBits, 0);
9549 if (TD->isLittleEndian()) {
9550 for (signed i = len-1; i >= 0; i--) {
9551 SingleChar = (uint64_t) Str[i];
9552 StrVal = (StrVal << 8) | SingleChar;
9553 }
9554 } else {
9555 for (unsigned i = 0; i < len; i++) {
9556 SingleChar = (uint64_t) Str[i];
9557 StrVal = (StrVal << 8) | SingleChar;
9558 }
9559 // Append NULL at the end.
9560 SingleChar = 0;
9561 StrVal = (StrVal << 8) | SingleChar;
9562 }
9563 Value *NL = ConstantInt::get(StrVal);
9564 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +00009565 }
9566 }
9567 }
9568
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009569 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9570 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9571 const Type *SrcPTy = SrcTy->getElementType();
9572
9573 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9574 isa<VectorType>(DestPTy)) {
9575 // If the source is an array, the code below will not succeed. Check to
9576 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9577 // constants.
9578 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9579 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9580 if (ASrcTy->getNumElements() != 0) {
9581 Value *Idxs[2];
9582 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9583 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9584 SrcTy = cast<PointerType>(CastOp->getType());
9585 SrcPTy = SrcTy->getElementType();
9586 }
9587
9588 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9589 isa<VectorType>(SrcPTy)) &&
9590 // Do not allow turning this into a load of an integer, which is then
9591 // casted to a pointer, this pessimizes pointer analysis a lot.
9592 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9593 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9594 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9595
9596 // Okay, we are casting from one integer or pointer type to another of
9597 // the same size. Instead of casting the pointer before the load, cast
9598 // the result of the loaded value.
9599 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9600 CI->getName(),
9601 LI.isVolatile()),LI);
9602 // Now cast the result of the load.
9603 return new BitCastInst(NewLoad, LI.getType());
9604 }
9605 }
9606 }
9607 return 0;
9608}
9609
9610/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9611/// from this value cannot trap. If it is not obviously safe to load from the
9612/// specified pointer, we do a quick local scan of the basic block containing
9613/// ScanFrom, to determine if the address is already accessed.
9614static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009615 // If it is an alloca it is always safe to load from.
9616 if (isa<AllocaInst>(V)) return true;
9617
Duncan Sandse40a94a2007-09-19 10:25:38 +00009618 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009619 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009620 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009621 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009622
9623 // Otherwise, be a little bit agressive by scanning the local block where we
9624 // want to check to see if the pointer is already being loaded or stored
9625 // from/to. If so, the previous load or store would have already trapped,
9626 // so there is no harm doing an extra load (also, CSE will later eliminate
9627 // the load entirely).
9628 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9629
9630 while (BBI != E) {
9631 --BBI;
9632
9633 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9634 if (LI->getOperand(0) == V) return true;
9635 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9636 if (SI->getOperand(1) == V) return true;
9637
9638 }
9639 return false;
9640}
9641
Chris Lattner0270a112007-08-11 18:48:48 +00009642/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9643/// until we find the underlying object a pointer is referring to or something
9644/// we don't understand. Note that the returned pointer may be offset from the
9645/// input, because we ignore GEP indices.
9646static Value *GetUnderlyingObject(Value *Ptr) {
9647 while (1) {
9648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9649 if (CE->getOpcode() == Instruction::BitCast ||
9650 CE->getOpcode() == Instruction::GetElementPtr)
9651 Ptr = CE->getOperand(0);
9652 else
9653 return Ptr;
9654 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9655 Ptr = BCI->getOperand(0);
9656 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9657 Ptr = GEP->getOperand(0);
9658 } else {
9659 return Ptr;
9660 }
9661 }
9662}
9663
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009664Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9665 Value *Op = LI.getOperand(0);
9666
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009667 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009668 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009669 if (KnownAlign > LI.getAlignment())
9670 LI.setAlignment(KnownAlign);
9671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009672 // load (cast X) --> cast (load X) iff safe
9673 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009674 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009675 return Res;
9676
9677 // None of the following transforms are legal for volatile loads.
9678 if (LI.isVolatile()) return 0;
9679
9680 if (&LI.getParent()->front() != &LI) {
9681 BasicBlock::iterator BBI = &LI; --BBI;
9682 // If the instruction immediately before this is a store to the same
9683 // address, do a simple form of store->load forwarding.
9684 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9685 if (SI->getOperand(1) == LI.getOperand(0))
9686 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9687 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9688 if (LIB->getOperand(0) == LI.getOperand(0))
9689 return ReplaceInstUsesWith(LI, LIB);
9690 }
9691
Christopher Lamb2c175392007-12-29 07:56:53 +00009692 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9693 const Value *GEPI0 = GEPI->getOperand(0);
9694 // TODO: Consider a target hook for valid address spaces for this xform.
9695 if (isa<ConstantPointerNull>(GEPI0) &&
9696 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009697 // Insert a new store to null instruction before the load to indicate
9698 // that this code is not reachable. We do this instead of inserting
9699 // an unreachable instruction directly because we cannot modify the
9700 // CFG.
9701 new StoreInst(UndefValue::get(LI.getType()),
9702 Constant::getNullValue(Op->getType()), &LI);
9703 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9704 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009706
9707 if (Constant *C = dyn_cast<Constant>(Op)) {
9708 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009709 // TODO: Consider a target hook for valid address spaces for this xform.
9710 if (isa<UndefValue>(C) || (C->isNullValue() &&
9711 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009712 // Insert a new store to null instruction before the load to indicate that
9713 // this code is not reachable. We do this instead of inserting an
9714 // unreachable instruction directly because we cannot modify the CFG.
9715 new StoreInst(UndefValue::get(LI.getType()),
9716 Constant::getNullValue(Op->getType()), &LI);
9717 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9718 }
9719
9720 // Instcombine load (constant global) into the value loaded.
9721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9722 if (GV->isConstant() && !GV->isDeclaration())
9723 return ReplaceInstUsesWith(LI, GV->getInitializer());
9724
9725 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009726 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009727 if (CE->getOpcode() == Instruction::GetElementPtr) {
9728 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9729 if (GV->isConstant() && !GV->isDeclaration())
9730 if (Constant *V =
9731 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9732 return ReplaceInstUsesWith(LI, V);
9733 if (CE->getOperand(0)->isNullValue()) {
9734 // Insert a new store to null instruction before the load to indicate
9735 // that this code is not reachable. We do this instead of inserting
9736 // an unreachable instruction directly because we cannot modify the
9737 // CFG.
9738 new StoreInst(UndefValue::get(LI.getType()),
9739 Constant::getNullValue(Op->getType()), &LI);
9740 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9741 }
9742
9743 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009744 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009745 return Res;
9746 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009747 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009748 }
Chris Lattner0270a112007-08-11 18:48:48 +00009749
9750 // If this load comes from anywhere in a constant global, and if the global
9751 // is all undef or zero, we know what it loads.
9752 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9753 if (GV->isConstant() && GV->hasInitializer()) {
9754 if (GV->getInitializer()->isNullValue())
9755 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9756 else if (isa<UndefValue>(GV->getInitializer()))
9757 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9758 }
9759 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009760
9761 if (Op->hasOneUse()) {
9762 // Change select and PHI nodes to select values instead of addresses: this
9763 // helps alias analysis out a lot, allows many others simplifications, and
9764 // exposes redundancy in the code.
9765 //
9766 // Note that we cannot do the transformation unless we know that the
9767 // introduced loads cannot trap! Something like this is valid as long as
9768 // the condition is always false: load (select bool %C, int* null, int* %G),
9769 // but it would not be valid if we transformed it to load from null
9770 // unconditionally.
9771 //
9772 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9773 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9774 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9775 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9776 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9777 SI->getOperand(1)->getName()+".val"), LI);
9778 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9779 SI->getOperand(2)->getName()+".val"), LI);
9780 return new SelectInst(SI->getCondition(), V1, V2);
9781 }
9782
9783 // load (select (cond, null, P)) -> load P
9784 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9785 if (C->isNullValue()) {
9786 LI.setOperand(0, SI->getOperand(2));
9787 return &LI;
9788 }
9789
9790 // load (select (cond, P, null)) -> load P
9791 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9792 if (C->isNullValue()) {
9793 LI.setOperand(0, SI->getOperand(1));
9794 return &LI;
9795 }
9796 }
9797 }
9798 return 0;
9799}
9800
9801/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9802/// when possible.
9803static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9804 User *CI = cast<User>(SI.getOperand(1));
9805 Value *CastOp = CI->getOperand(0);
9806
9807 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9808 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9809 const Type *SrcPTy = SrcTy->getElementType();
9810
9811 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9812 // If the source is an array, the code below will not succeed. Check to
9813 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9814 // constants.
9815 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9816 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9817 if (ASrcTy->getNumElements() != 0) {
9818 Value* Idxs[2];
9819 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9820 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9821 SrcTy = cast<PointerType>(CastOp->getType());
9822 SrcPTy = SrcTy->getElementType();
9823 }
9824
9825 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9826 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9827 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9828
9829 // Okay, we are casting from one integer or pointer type to another of
9830 // the same size. Instead of casting the pointer before
9831 // the store, cast the value to be stored.
9832 Value *NewCast;
9833 Value *SIOp0 = SI.getOperand(0);
9834 Instruction::CastOps opcode = Instruction::BitCast;
9835 const Type* CastSrcTy = SIOp0->getType();
9836 const Type* CastDstTy = SrcPTy;
9837 if (isa<PointerType>(CastDstTy)) {
9838 if (CastSrcTy->isInteger())
9839 opcode = Instruction::IntToPtr;
9840 } else if (isa<IntegerType>(CastDstTy)) {
9841 if (isa<PointerType>(SIOp0->getType()))
9842 opcode = Instruction::PtrToInt;
9843 }
9844 if (Constant *C = dyn_cast<Constant>(SIOp0))
9845 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9846 else
9847 NewCast = IC.InsertNewInstBefore(
9848 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9849 SI);
9850 return new StoreInst(NewCast, CastOp);
9851 }
9852 }
9853 }
9854 return 0;
9855}
9856
9857Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9858 Value *Val = SI.getOperand(0);
9859 Value *Ptr = SI.getOperand(1);
9860
9861 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9862 EraseInstFromFunction(SI);
9863 ++NumCombined;
9864 return 0;
9865 }
9866
9867 // If the RHS is an alloca with a single use, zapify the store, making the
9868 // alloca dead.
9869 if (Ptr->hasOneUse()) {
9870 if (isa<AllocaInst>(Ptr)) {
9871 EraseInstFromFunction(SI);
9872 ++NumCombined;
9873 return 0;
9874 }
9875
9876 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9877 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9878 GEP->getOperand(0)->hasOneUse()) {
9879 EraseInstFromFunction(SI);
9880 ++NumCombined;
9881 return 0;
9882 }
9883 }
9884
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009885 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009886 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009887 if (KnownAlign > SI.getAlignment())
9888 SI.setAlignment(KnownAlign);
9889
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009890 // Do really simple DSE, to catch cases where there are several consequtive
9891 // stores to the same location, separated by a few arithmetic operations. This
9892 // situation often occurs with bitfield accesses.
9893 BasicBlock::iterator BBI = &SI;
9894 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9895 --ScanInsts) {
9896 --BBI;
9897
9898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9899 // Prev store isn't volatile, and stores to the same location?
9900 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9901 ++NumDeadStore;
9902 ++BBI;
9903 EraseInstFromFunction(*PrevSI);
9904 continue;
9905 }
9906 break;
9907 }
9908
9909 // If this is a load, we have to stop. However, if the loaded value is from
9910 // the pointer we're loading and is producing the pointer we're storing,
9911 // then *this* store is dead (X = load P; store X -> P).
9912 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009913 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009914 EraseInstFromFunction(SI);
9915 ++NumCombined;
9916 return 0;
9917 }
9918 // Otherwise, this is a load from some other location. Stores before it
9919 // may not be dead.
9920 break;
9921 }
9922
9923 // Don't skip over loads or things that can modify memory.
9924 if (BBI->mayWriteToMemory())
9925 break;
9926 }
9927
9928
9929 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9930
9931 // store X, null -> turns into 'unreachable' in SimplifyCFG
9932 if (isa<ConstantPointerNull>(Ptr)) {
9933 if (!isa<UndefValue>(Val)) {
9934 SI.setOperand(0, UndefValue::get(Val->getType()));
9935 if (Instruction *U = dyn_cast<Instruction>(Val))
9936 AddToWorkList(U); // Dropped a use.
9937 ++NumCombined;
9938 }
9939 return 0; // Do not modify these!
9940 }
9941
9942 // store undef, Ptr -> noop
9943 if (isa<UndefValue>(Val)) {
9944 EraseInstFromFunction(SI);
9945 ++NumCombined;
9946 return 0;
9947 }
9948
9949 // If the pointer destination is a cast, see if we can fold the cast into the
9950 // source instead.
9951 if (isa<CastInst>(Ptr))
9952 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9953 return Res;
9954 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9955 if (CE->isCast())
9956 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9957 return Res;
9958
9959
9960 // If this store is the last instruction in the basic block, and if the block
9961 // ends with an unconditional branch, try to move it to the successor block.
9962 BBI = &SI; ++BBI;
9963 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9964 if (BI->isUnconditional())
9965 if (SimplifyStoreAtEndOfBlock(SI))
9966 return 0; // xform done!
9967
9968 return 0;
9969}
9970
9971/// SimplifyStoreAtEndOfBlock - Turn things like:
9972/// if () { *P = v1; } else { *P = v2 }
9973/// into a phi node with a store in the successor.
9974///
9975/// Simplify things like:
9976/// *P = v1; if () { *P = v2; }
9977/// into a phi node with a store in the successor.
9978///
9979bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9980 BasicBlock *StoreBB = SI.getParent();
9981
9982 // Check to see if the successor block has exactly two incoming edges. If
9983 // so, see if the other predecessor contains a store to the same location.
9984 // if so, insert a PHI node (if needed) and move the stores down.
9985 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9986
9987 // Determine whether Dest has exactly two predecessors and, if so, compute
9988 // the other predecessor.
9989 pred_iterator PI = pred_begin(DestBB);
9990 BasicBlock *OtherBB = 0;
9991 if (*PI != StoreBB)
9992 OtherBB = *PI;
9993 ++PI;
9994 if (PI == pred_end(DestBB))
9995 return false;
9996
9997 if (*PI != StoreBB) {
9998 if (OtherBB)
9999 return false;
10000 OtherBB = *PI;
10001 }
10002 if (++PI != pred_end(DestBB))
10003 return false;
10004
10005
10006 // Verify that the other block ends in a branch and is not otherwise empty.
10007 BasicBlock::iterator BBI = OtherBB->getTerminator();
10008 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10009 if (!OtherBr || BBI == OtherBB->begin())
10010 return false;
10011
10012 // If the other block ends in an unconditional branch, check for the 'if then
10013 // else' case. there is an instruction before the branch.
10014 StoreInst *OtherStore = 0;
10015 if (OtherBr->isUnconditional()) {
10016 // If this isn't a store, or isn't a store to the same location, bail out.
10017 --BBI;
10018 OtherStore = dyn_cast<StoreInst>(BBI);
10019 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10020 return false;
10021 } else {
10022 // Otherwise, the other block ended with a conditional branch. If one of the
10023 // destinations is StoreBB, then we have the if/then case.
10024 if (OtherBr->getSuccessor(0) != StoreBB &&
10025 OtherBr->getSuccessor(1) != StoreBB)
10026 return false;
10027
10028 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10029 // if/then triangle. See if there is a store to the same ptr as SI that
10030 // lives in OtherBB.
10031 for (;; --BBI) {
10032 // Check to see if we find the matching store.
10033 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10034 if (OtherStore->getOperand(1) != SI.getOperand(1))
10035 return false;
10036 break;
10037 }
10038 // If we find something that may be using the stored value, or if we run
10039 // out of instructions, we can't do the xform.
10040 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10041 BBI == OtherBB->begin())
10042 return false;
10043 }
10044
10045 // In order to eliminate the store in OtherBr, we have to
10046 // make sure nothing reads the stored value in StoreBB.
10047 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10048 // FIXME: This should really be AA driven.
10049 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10050 return false;
10051 }
10052 }
10053
10054 // Insert a PHI node now if we need it.
10055 Value *MergedVal = OtherStore->getOperand(0);
10056 if (MergedVal != SI.getOperand(0)) {
10057 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10058 PN->reserveOperandSpace(2);
10059 PN->addIncoming(SI.getOperand(0), SI.getParent());
10060 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10061 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10062 }
10063
10064 // Advance to a place where it is safe to insert the new store and
10065 // insert it.
10066 BBI = DestBB->begin();
10067 while (isa<PHINode>(BBI)) ++BBI;
10068 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10069 OtherStore->isVolatile()), *BBI);
10070
10071 // Nuke the old stores.
10072 EraseInstFromFunction(SI);
10073 EraseInstFromFunction(*OtherStore);
10074 ++NumCombined;
10075 return true;
10076}
10077
10078
10079Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10080 // Change br (not X), label True, label False to: br X, label False, True
10081 Value *X = 0;
10082 BasicBlock *TrueDest;
10083 BasicBlock *FalseDest;
10084 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10085 !isa<Constant>(X)) {
10086 // Swap Destinations and condition...
10087 BI.setCondition(X);
10088 BI.setSuccessor(0, FalseDest);
10089 BI.setSuccessor(1, TrueDest);
10090 return &BI;
10091 }
10092
10093 // Cannonicalize fcmp_one -> fcmp_oeq
10094 FCmpInst::Predicate FPred; Value *Y;
10095 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10096 TrueDest, FalseDest)))
10097 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10098 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10099 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10100 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10101 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10102 NewSCC->takeName(I);
10103 // Swap Destinations and condition...
10104 BI.setCondition(NewSCC);
10105 BI.setSuccessor(0, FalseDest);
10106 BI.setSuccessor(1, TrueDest);
10107 RemoveFromWorkList(I);
10108 I->eraseFromParent();
10109 AddToWorkList(NewSCC);
10110 return &BI;
10111 }
10112
10113 // Cannonicalize icmp_ne -> icmp_eq
10114 ICmpInst::Predicate IPred;
10115 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10116 TrueDest, FalseDest)))
10117 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10118 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10119 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10120 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10121 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10122 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10123 NewSCC->takeName(I);
10124 // Swap Destinations and condition...
10125 BI.setCondition(NewSCC);
10126 BI.setSuccessor(0, FalseDest);
10127 BI.setSuccessor(1, TrueDest);
10128 RemoveFromWorkList(I);
10129 I->eraseFromParent();;
10130 AddToWorkList(NewSCC);
10131 return &BI;
10132 }
10133
10134 return 0;
10135}
10136
10137Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10138 Value *Cond = SI.getCondition();
10139 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10140 if (I->getOpcode() == Instruction::Add)
10141 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10142 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10143 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10144 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10145 AddRHS));
10146 SI.setOperand(0, I->getOperand(0));
10147 AddToWorkList(I);
10148 return &SI;
10149 }
10150 }
10151 return 0;
10152}
10153
10154/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10155/// is to leave as a vector operation.
10156static bool CheapToScalarize(Value *V, bool isConstant) {
10157 if (isa<ConstantAggregateZero>(V))
10158 return true;
10159 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10160 if (isConstant) return true;
10161 // If all elts are the same, we can extract.
10162 Constant *Op0 = C->getOperand(0);
10163 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10164 if (C->getOperand(i) != Op0)
10165 return false;
10166 return true;
10167 }
10168 Instruction *I = dyn_cast<Instruction>(V);
10169 if (!I) return false;
10170
10171 // Insert element gets simplified to the inserted element or is deleted if
10172 // this is constant idx extract element and its a constant idx insertelt.
10173 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10174 isa<ConstantInt>(I->getOperand(2)))
10175 return true;
10176 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10177 return true;
10178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10179 if (BO->hasOneUse() &&
10180 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10181 CheapToScalarize(BO->getOperand(1), isConstant)))
10182 return true;
10183 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10184 if (CI->hasOneUse() &&
10185 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10186 CheapToScalarize(CI->getOperand(1), isConstant)))
10187 return true;
10188
10189 return false;
10190}
10191
10192/// Read and decode a shufflevector mask.
10193///
10194/// It turns undef elements into values that are larger than the number of
10195/// elements in the input.
10196static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10197 unsigned NElts = SVI->getType()->getNumElements();
10198 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10199 return std::vector<unsigned>(NElts, 0);
10200 if (isa<UndefValue>(SVI->getOperand(2)))
10201 return std::vector<unsigned>(NElts, 2*NElts);
10202
10203 std::vector<unsigned> Result;
10204 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10205 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10206 if (isa<UndefValue>(CP->getOperand(i)))
10207 Result.push_back(NElts*2); // undef -> 8
10208 else
10209 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10210 return Result;
10211}
10212
10213/// FindScalarElement - Given a vector and an element number, see if the scalar
10214/// value is already around as a register, for example if it were inserted then
10215/// extracted from the vector.
10216static Value *FindScalarElement(Value *V, unsigned EltNo) {
10217 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10218 const VectorType *PTy = cast<VectorType>(V->getType());
10219 unsigned Width = PTy->getNumElements();
10220 if (EltNo >= Width) // Out of range access.
10221 return UndefValue::get(PTy->getElementType());
10222
10223 if (isa<UndefValue>(V))
10224 return UndefValue::get(PTy->getElementType());
10225 else if (isa<ConstantAggregateZero>(V))
10226 return Constant::getNullValue(PTy->getElementType());
10227 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10228 return CP->getOperand(EltNo);
10229 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10230 // If this is an insert to a variable element, we don't know what it is.
10231 if (!isa<ConstantInt>(III->getOperand(2)))
10232 return 0;
10233 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10234
10235 // If this is an insert to the element we are looking for, return the
10236 // inserted value.
10237 if (EltNo == IIElt)
10238 return III->getOperand(1);
10239
10240 // Otherwise, the insertelement doesn't modify the value, recurse on its
10241 // vector input.
10242 return FindScalarElement(III->getOperand(0), EltNo);
10243 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10244 unsigned InEl = getShuffleMask(SVI)[EltNo];
10245 if (InEl < Width)
10246 return FindScalarElement(SVI->getOperand(0), InEl);
10247 else if (InEl < Width*2)
10248 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10249 else
10250 return UndefValue::get(PTy->getElementType());
10251 }
10252
10253 // Otherwise, we don't know.
10254 return 0;
10255}
10256
10257Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10258
10259 // If vector val is undef, replace extract with scalar undef.
10260 if (isa<UndefValue>(EI.getOperand(0)))
10261 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10262
10263 // If vector val is constant 0, replace extract with scalar 0.
10264 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10265 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10266
10267 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10268 // If vector val is constant with uniform operands, replace EI
10269 // with that operand
10270 Constant *op0 = C->getOperand(0);
10271 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10272 if (C->getOperand(i) != op0) {
10273 op0 = 0;
10274 break;
10275 }
10276 if (op0)
10277 return ReplaceInstUsesWith(EI, op0);
10278 }
10279
10280 // If extracting a specified index from the vector, see if we can recursively
10281 // find a previously computed scalar that was inserted into the vector.
10282 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10283 unsigned IndexVal = IdxC->getZExtValue();
10284 unsigned VectorWidth =
10285 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10286
10287 // If this is extracting an invalid index, turn this into undef, to avoid
10288 // crashing the code below.
10289 if (IndexVal >= VectorWidth)
10290 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10291
10292 // This instruction only demands the single element from the input vector.
10293 // If the input vector has a single use, simplify it based on this use
10294 // property.
10295 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10296 uint64_t UndefElts;
10297 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10298 1 << IndexVal,
10299 UndefElts)) {
10300 EI.setOperand(0, V);
10301 return &EI;
10302 }
10303 }
10304
10305 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10306 return ReplaceInstUsesWith(EI, Elt);
10307
10308 // If the this extractelement is directly using a bitcast from a vector of
10309 // the same number of elements, see if we can find the source element from
10310 // it. In this case, we will end up needing to bitcast the scalars.
10311 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10312 if (const VectorType *VT =
10313 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10314 if (VT->getNumElements() == VectorWidth)
10315 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10316 return new BitCastInst(Elt, EI.getType());
10317 }
10318 }
10319
10320 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10321 if (I->hasOneUse()) {
10322 // Push extractelement into predecessor operation if legal and
10323 // profitable to do so
10324 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10325 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10326 if (CheapToScalarize(BO, isConstantElt)) {
10327 ExtractElementInst *newEI0 =
10328 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10329 EI.getName()+".lhs");
10330 ExtractElementInst *newEI1 =
10331 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10332 EI.getName()+".rhs");
10333 InsertNewInstBefore(newEI0, EI);
10334 InsertNewInstBefore(newEI1, EI);
10335 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10336 }
10337 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010338 unsigned AS =
10339 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010340 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10341 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010342 GetElementPtrInst *GEP =
10343 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10344 InsertNewInstBefore(GEP, EI);
10345 return new LoadInst(GEP);
10346 }
10347 }
10348 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10349 // Extracting the inserted element?
10350 if (IE->getOperand(2) == EI.getOperand(1))
10351 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10352 // If the inserted and extracted elements are constants, they must not
10353 // be the same value, extract from the pre-inserted value instead.
10354 if (isa<Constant>(IE->getOperand(2)) &&
10355 isa<Constant>(EI.getOperand(1))) {
10356 AddUsesToWorkList(EI);
10357 EI.setOperand(0, IE->getOperand(0));
10358 return &EI;
10359 }
10360 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10361 // If this is extracting an element from a shufflevector, figure out where
10362 // it came from and extract from the appropriate input element instead.
10363 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10364 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10365 Value *Src;
10366 if (SrcIdx < SVI->getType()->getNumElements())
10367 Src = SVI->getOperand(0);
10368 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10369 SrcIdx -= SVI->getType()->getNumElements();
10370 Src = SVI->getOperand(1);
10371 } else {
10372 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10373 }
10374 return new ExtractElementInst(Src, SrcIdx);
10375 }
10376 }
10377 }
10378 return 0;
10379}
10380
10381/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10382/// elements from either LHS or RHS, return the shuffle mask and true.
10383/// Otherwise, return false.
10384static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10385 std::vector<Constant*> &Mask) {
10386 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10387 "Invalid CollectSingleShuffleElements");
10388 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10389
10390 if (isa<UndefValue>(V)) {
10391 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10392 return true;
10393 } else if (V == LHS) {
10394 for (unsigned i = 0; i != NumElts; ++i)
10395 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10396 return true;
10397 } else if (V == RHS) {
10398 for (unsigned i = 0; i != NumElts; ++i)
10399 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10400 return true;
10401 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10402 // If this is an insert of an extract from some other vector, include it.
10403 Value *VecOp = IEI->getOperand(0);
10404 Value *ScalarOp = IEI->getOperand(1);
10405 Value *IdxOp = IEI->getOperand(2);
10406
10407 if (!isa<ConstantInt>(IdxOp))
10408 return false;
10409 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10410
10411 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10412 // Okay, we can handle this if the vector we are insertinting into is
10413 // transitively ok.
10414 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10415 // If so, update the mask to reflect the inserted undef.
10416 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10417 return true;
10418 }
10419 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10420 if (isa<ConstantInt>(EI->getOperand(1)) &&
10421 EI->getOperand(0)->getType() == V->getType()) {
10422 unsigned ExtractedIdx =
10423 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10424
10425 // This must be extracting from either LHS or RHS.
10426 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10427 // Okay, we can handle this if the vector we are insertinting into is
10428 // transitively ok.
10429 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10430 // If so, update the mask to reflect the inserted value.
10431 if (EI->getOperand(0) == LHS) {
10432 Mask[InsertedIdx & (NumElts-1)] =
10433 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10434 } else {
10435 assert(EI->getOperand(0) == RHS);
10436 Mask[InsertedIdx & (NumElts-1)] =
10437 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10438
10439 }
10440 return true;
10441 }
10442 }
10443 }
10444 }
10445 }
10446 // TODO: Handle shufflevector here!
10447
10448 return false;
10449}
10450
10451/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10452/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10453/// that computes V and the LHS value of the shuffle.
10454static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10455 Value *&RHS) {
10456 assert(isa<VectorType>(V->getType()) &&
10457 (RHS == 0 || V->getType() == RHS->getType()) &&
10458 "Invalid shuffle!");
10459 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10460
10461 if (isa<UndefValue>(V)) {
10462 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10463 return V;
10464 } else if (isa<ConstantAggregateZero>(V)) {
10465 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10466 return V;
10467 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10468 // If this is an insert of an extract from some other vector, include it.
10469 Value *VecOp = IEI->getOperand(0);
10470 Value *ScalarOp = IEI->getOperand(1);
10471 Value *IdxOp = IEI->getOperand(2);
10472
10473 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10474 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10475 EI->getOperand(0)->getType() == V->getType()) {
10476 unsigned ExtractedIdx =
10477 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10478 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10479
10480 // Either the extracted from or inserted into vector must be RHSVec,
10481 // otherwise we'd end up with a shuffle of three inputs.
10482 if (EI->getOperand(0) == RHS || RHS == 0) {
10483 RHS = EI->getOperand(0);
10484 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10485 Mask[InsertedIdx & (NumElts-1)] =
10486 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10487 return V;
10488 }
10489
10490 if (VecOp == RHS) {
10491 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10492 // Everything but the extracted element is replaced with the RHS.
10493 for (unsigned i = 0; i != NumElts; ++i) {
10494 if (i != InsertedIdx)
10495 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10496 }
10497 return V;
10498 }
10499
10500 // If this insertelement is a chain that comes from exactly these two
10501 // vectors, return the vector and the effective shuffle.
10502 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10503 return EI->getOperand(0);
10504
10505 }
10506 }
10507 }
10508 // TODO: Handle shufflevector here!
10509
10510 // Otherwise, can't do anything fancy. Return an identity vector.
10511 for (unsigned i = 0; i != NumElts; ++i)
10512 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10513 return V;
10514}
10515
10516Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10517 Value *VecOp = IE.getOperand(0);
10518 Value *ScalarOp = IE.getOperand(1);
10519 Value *IdxOp = IE.getOperand(2);
10520
10521 // Inserting an undef or into an undefined place, remove this.
10522 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10523 ReplaceInstUsesWith(IE, VecOp);
10524
10525 // If the inserted element was extracted from some other vector, and if the
10526 // indexes are constant, try to turn this into a shufflevector operation.
10527 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10528 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10529 EI->getOperand(0)->getType() == IE.getType()) {
10530 unsigned NumVectorElts = IE.getType()->getNumElements();
10531 unsigned ExtractedIdx =
10532 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10533 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10534
10535 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10536 return ReplaceInstUsesWith(IE, VecOp);
10537
10538 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10539 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10540
10541 // If we are extracting a value from a vector, then inserting it right
10542 // back into the same place, just use the input vector.
10543 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10544 return ReplaceInstUsesWith(IE, VecOp);
10545
10546 // We could theoretically do this for ANY input. However, doing so could
10547 // turn chains of insertelement instructions into a chain of shufflevector
10548 // instructions, and right now we do not merge shufflevectors. As such,
10549 // only do this in a situation where it is clear that there is benefit.
10550 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10551 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10552 // the values of VecOp, except then one read from EIOp0.
10553 // Build a new shuffle mask.
10554 std::vector<Constant*> Mask;
10555 if (isa<UndefValue>(VecOp))
10556 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10557 else {
10558 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10559 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10560 NumVectorElts));
10561 }
10562 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10563 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10564 ConstantVector::get(Mask));
10565 }
10566
10567 // If this insertelement isn't used by some other insertelement, turn it
10568 // (and any insertelements it points to), into one big shuffle.
10569 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10570 std::vector<Constant*> Mask;
10571 Value *RHS = 0;
10572 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10573 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10574 // We now have a shuffle of LHS, RHS, Mask.
10575 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10576 }
10577 }
10578 }
10579
10580 return 0;
10581}
10582
10583
10584Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10585 Value *LHS = SVI.getOperand(0);
10586 Value *RHS = SVI.getOperand(1);
10587 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10588
10589 bool MadeChange = false;
10590
10591 // Undefined shuffle mask -> undefined value.
10592 if (isa<UndefValue>(SVI.getOperand(2)))
10593 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10594
10595 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10596 // the undef, change them to undefs.
10597 if (isa<UndefValue>(SVI.getOperand(1))) {
10598 // Scan to see if there are any references to the RHS. If so, replace them
10599 // with undef element refs and set MadeChange to true.
10600 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10601 if (Mask[i] >= e && Mask[i] != 2*e) {
10602 Mask[i] = 2*e;
10603 MadeChange = true;
10604 }
10605 }
10606
10607 if (MadeChange) {
10608 // Remap any references to RHS to use LHS.
10609 std::vector<Constant*> Elts;
10610 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10611 if (Mask[i] == 2*e)
10612 Elts.push_back(UndefValue::get(Type::Int32Ty));
10613 else
10614 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10615 }
10616 SVI.setOperand(2, ConstantVector::get(Elts));
10617 }
10618 }
10619
10620 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10621 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10622 if (LHS == RHS || isa<UndefValue>(LHS)) {
10623 if (isa<UndefValue>(LHS) && LHS == RHS) {
10624 // shuffle(undef,undef,mask) -> undef.
10625 return ReplaceInstUsesWith(SVI, LHS);
10626 }
10627
10628 // Remap any references to RHS to use LHS.
10629 std::vector<Constant*> Elts;
10630 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10631 if (Mask[i] >= 2*e)
10632 Elts.push_back(UndefValue::get(Type::Int32Ty));
10633 else {
10634 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10635 (Mask[i] < e && isa<UndefValue>(LHS)))
10636 Mask[i] = 2*e; // Turn into undef.
10637 else
10638 Mask[i] &= (e-1); // Force to LHS.
10639 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10640 }
10641 }
10642 SVI.setOperand(0, SVI.getOperand(1));
10643 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10644 SVI.setOperand(2, ConstantVector::get(Elts));
10645 LHS = SVI.getOperand(0);
10646 RHS = SVI.getOperand(1);
10647 MadeChange = true;
10648 }
10649
10650 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10651 bool isLHSID = true, isRHSID = true;
10652
10653 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10654 if (Mask[i] >= e*2) continue; // Ignore undef values.
10655 // Is this an identity shuffle of the LHS value?
10656 isLHSID &= (Mask[i] == i);
10657
10658 // Is this an identity shuffle of the RHS value?
10659 isRHSID &= (Mask[i]-e == i);
10660 }
10661
10662 // Eliminate identity shuffles.
10663 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10664 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10665
10666 // If the LHS is a shufflevector itself, see if we can combine it with this
10667 // one without producing an unusual shuffle. Here we are really conservative:
10668 // we are absolutely afraid of producing a shuffle mask not in the input
10669 // program, because the code gen may not be smart enough to turn a merged
10670 // shuffle into two specific shuffles: it may produce worse code. As such,
10671 // we only merge two shuffles if the result is one of the two input shuffle
10672 // masks. In this case, merging the shuffles just removes one instruction,
10673 // which we know is safe. This is good for things like turning:
10674 // (splat(splat)) -> splat.
10675 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10676 if (isa<UndefValue>(RHS)) {
10677 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10678
10679 std::vector<unsigned> NewMask;
10680 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10681 if (Mask[i] >= 2*e)
10682 NewMask.push_back(2*e);
10683 else
10684 NewMask.push_back(LHSMask[Mask[i]]);
10685
10686 // If the result mask is equal to the src shuffle or this shuffle mask, do
10687 // the replacement.
10688 if (NewMask == LHSMask || NewMask == Mask) {
10689 std::vector<Constant*> Elts;
10690 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10691 if (NewMask[i] >= e*2) {
10692 Elts.push_back(UndefValue::get(Type::Int32Ty));
10693 } else {
10694 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10695 }
10696 }
10697 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10698 LHSSVI->getOperand(1),
10699 ConstantVector::get(Elts));
10700 }
10701 }
10702 }
10703
10704 return MadeChange ? &SVI : 0;
10705}
10706
10707
10708
10709
10710/// TryToSinkInstruction - Try to move the specified instruction from its
10711/// current block into the beginning of DestBlock, which can only happen if it's
10712/// safe to move the instruction past all of the instructions between it and the
10713/// end of its block.
10714static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10715 assert(I->hasOneUse() && "Invariants didn't hold!");
10716
10717 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10718 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10719
10720 // Do not sink alloca instructions out of the entry block.
10721 if (isa<AllocaInst>(I) && I->getParent() ==
10722 &DestBlock->getParent()->getEntryBlock())
10723 return false;
10724
10725 // We can only sink load instructions if there is nothing between the load and
10726 // the end of block that could change the value.
10727 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10728 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10729 Scan != E; ++Scan)
10730 if (Scan->mayWriteToMemory())
10731 return false;
10732 }
10733
10734 BasicBlock::iterator InsertPos = DestBlock->begin();
10735 while (isa<PHINode>(InsertPos)) ++InsertPos;
10736
10737 I->moveBefore(InsertPos);
10738 ++NumSunkInst;
10739 return true;
10740}
10741
10742
10743/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10744/// all reachable code to the worklist.
10745///
10746/// This has a couple of tricks to make the code faster and more powerful. In
10747/// particular, we constant fold and DCE instructions as we go, to avoid adding
10748/// them to the worklist (this significantly speeds up instcombine on code where
10749/// many instructions are dead or constant). Additionally, if we find a branch
10750/// whose condition is a known constant, we only visit the reachable successors.
10751///
10752static void AddReachableCodeToWorklist(BasicBlock *BB,
10753 SmallPtrSet<BasicBlock*, 64> &Visited,
10754 InstCombiner &IC,
10755 const TargetData *TD) {
10756 std::vector<BasicBlock*> Worklist;
10757 Worklist.push_back(BB);
10758
10759 while (!Worklist.empty()) {
10760 BB = Worklist.back();
10761 Worklist.pop_back();
10762
10763 // We have now visited this block! If we've already been here, ignore it.
10764 if (!Visited.insert(BB)) continue;
10765
10766 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10767 Instruction *Inst = BBI++;
10768
10769 // DCE instruction if trivially dead.
10770 if (isInstructionTriviallyDead(Inst)) {
10771 ++NumDeadInst;
10772 DOUT << "IC: DCE: " << *Inst;
10773 Inst->eraseFromParent();
10774 continue;
10775 }
10776
10777 // ConstantProp instruction if trivially constant.
10778 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10779 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10780 Inst->replaceAllUsesWith(C);
10781 ++NumConstProp;
10782 Inst->eraseFromParent();
10783 continue;
10784 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010785
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010786 IC.AddToWorkList(Inst);
10787 }
10788
10789 // Recursively visit successors. If this is a branch or switch on a
10790 // constant, only visit the reachable successor.
Nick Lewyckyd551cf12008-03-09 08:50:23 +000010791 if (BB->getUnwindDest())
10792 Worklist.push_back(BB->getUnwindDest());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010793 TerminatorInst *TI = BB->getTerminator();
10794 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10795 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10796 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000010797 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10798 if (ReachableBB != BB->getUnwindDest())
10799 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010800 continue;
10801 }
10802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10803 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10804 // See if this is an explicit destination.
10805 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10806 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000010807 BasicBlock *ReachableBB = SI->getSuccessor(i);
10808 if (ReachableBB != BB->getUnwindDest())
10809 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010810 continue;
10811 }
10812
10813 // Otherwise it is the default destination.
10814 Worklist.push_back(SI->getSuccessor(0));
10815 continue;
10816 }
10817 }
10818
10819 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10820 Worklist.push_back(TI->getSuccessor(i));
10821 }
10822}
10823
10824bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10825 bool Changed = false;
10826 TD = &getAnalysis<TargetData>();
10827
10828 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10829 << F.getNameStr() << "\n");
10830
10831 {
10832 // Do a depth-first traversal of the function, populate the worklist with
10833 // the reachable instructions. Ignore blocks that are not reachable. Keep
10834 // track of which blocks we visit.
10835 SmallPtrSet<BasicBlock*, 64> Visited;
10836 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10837
10838 // Do a quick scan over the function. If we find any blocks that are
10839 // unreachable, remove any instructions inside of them. This prevents
10840 // the instcombine code from having to deal with some bad special cases.
10841 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10842 if (!Visited.count(BB)) {
10843 Instruction *Term = BB->getTerminator();
10844 while (Term != BB->begin()) { // Remove instrs bottom-up
10845 BasicBlock::iterator I = Term; --I;
10846
10847 DOUT << "IC: DCE: " << *I;
10848 ++NumDeadInst;
10849
10850 if (!I->use_empty())
10851 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10852 I->eraseFromParent();
10853 }
10854 }
10855 }
10856
10857 while (!Worklist.empty()) {
10858 Instruction *I = RemoveOneFromWorkList();
10859 if (I == 0) continue; // skip null values.
10860
10861 // Check to see if we can DCE the instruction.
10862 if (isInstructionTriviallyDead(I)) {
10863 // Add operands to the worklist.
10864 if (I->getNumOperands() < 4)
10865 AddUsesToWorkList(*I);
10866 ++NumDeadInst;
10867
10868 DOUT << "IC: DCE: " << *I;
10869
10870 I->eraseFromParent();
10871 RemoveFromWorkList(I);
10872 continue;
10873 }
10874
10875 // Instruction isn't dead, see if we can constant propagate it.
10876 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10877 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10878
10879 // Add operands to the worklist.
10880 AddUsesToWorkList(*I);
10881 ReplaceInstUsesWith(*I, C);
10882
10883 ++NumConstProp;
10884 I->eraseFromParent();
10885 RemoveFromWorkList(I);
10886 continue;
10887 }
10888
10889 // See if we can trivially sink this instruction to a successor basic block.
10890 if (I->hasOneUse()) {
10891 BasicBlock *BB = I->getParent();
10892 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10893 if (UserParent != BB) {
10894 bool UserIsSuccessor = false;
10895 // See if the user is one of our successors.
10896 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10897 if (*SI == UserParent) {
10898 UserIsSuccessor = true;
10899 break;
10900 }
10901
10902 // If the user is one of our immediate successors, and if that successor
10903 // only has us as a predecessors (we'd have to split the critical edge
10904 // otherwise), we can keep going.
10905 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10906 next(pred_begin(UserParent)) == pred_end(UserParent))
10907 // Okay, the CFG is simple enough, try to sink this instruction.
10908 Changed |= TryToSinkInstruction(I, UserParent);
10909 }
10910 }
10911
10912 // Now that we have an instruction, try combining it to simplify it...
10913#ifndef NDEBUG
10914 std::string OrigI;
10915#endif
10916 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10917 if (Instruction *Result = visit(*I)) {
10918 ++NumCombined;
10919 // Should we replace the old instruction with a new one?
10920 if (Result != I) {
10921 DOUT << "IC: Old = " << *I
10922 << " New = " << *Result;
10923
10924 // Everything uses the new instruction now.
10925 I->replaceAllUsesWith(Result);
10926
10927 // Push the new instruction and any users onto the worklist.
10928 AddToWorkList(Result);
10929 AddUsersToWorkList(*Result);
10930
10931 // Move the name to the new instruction first.
10932 Result->takeName(I);
10933
10934 // Insert the new instruction into the basic block...
10935 BasicBlock *InstParent = I->getParent();
10936 BasicBlock::iterator InsertPos = I;
10937
10938 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10939 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10940 ++InsertPos;
10941
10942 InstParent->getInstList().insert(InsertPos, Result);
10943
10944 // Make sure that we reprocess all operands now that we reduced their
10945 // use counts.
10946 AddUsesToWorkList(*I);
10947
10948 // Instructions can end up on the worklist more than once. Make sure
10949 // we do not process an instruction that has been deleted.
10950 RemoveFromWorkList(I);
10951
10952 // Erase the old instruction.
10953 InstParent->getInstList().erase(I);
10954 } else {
10955#ifndef NDEBUG
10956 DOUT << "IC: Mod = " << OrigI
10957 << " New = " << *I;
10958#endif
10959
10960 // If the instruction was modified, it's possible that it is now dead.
10961 // if so, remove it.
10962 if (isInstructionTriviallyDead(I)) {
10963 // Make sure we process all operands now that we are reducing their
10964 // use counts.
10965 AddUsesToWorkList(*I);
10966
10967 // Instructions may end up in the worklist more than once. Erase all
10968 // occurrences of this instruction.
10969 RemoveFromWorkList(I);
10970 I->eraseFromParent();
10971 } else {
10972 AddToWorkList(I);
10973 AddUsersToWorkList(*I);
10974 }
10975 }
10976 Changed = true;
10977 }
10978 }
10979
10980 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010981
10982 // Do an explicit clear, this shrinks the map if needed.
10983 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010984 return Changed;
10985}
10986
10987
10988bool InstCombiner::runOnFunction(Function &F) {
10989 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10990
10991 bool EverMadeChange = false;
10992
10993 // Iterate while there is work to do.
10994 unsigned Iteration = 0;
10995 while (DoOneIteration(F, Iteration++))
10996 EverMadeChange = true;
10997 return EverMadeChange;
10998}
10999
11000FunctionPass *llvm::createInstructionCombiningPass() {
11001 return new InstCombiner();
11002}
11003