blob: 1968f9b36ef7751dc91f95258214b1a857aab2b1 [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"
Duncan Sandscf7ecaa2007-09-11 14:35:41 +000042#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043#include "llvm/Analysis/ConstantFolding.h"
44#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
48#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}
607
608/// ComputeMaskedBits - Determine which of the bits specified in Mask are
609/// known to be either zero or one and return them in the KnownZero/KnownOne
610/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
611/// processing.
612/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
613/// we cannot optimize based on the assumption that it is zero without changing
614/// it to be an explicit zero. If we don't change it to zero, other code could
615/// optimized based on the contradictory assumption that it is non-zero.
616/// Because instcombine aggressively folds operations with undef args anyway,
617/// this won't lose us code quality.
618static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
619 APInt& KnownOne, unsigned Depth = 0) {
620 assert(V && "No Value?");
621 assert(Depth <= 6 && "Limit Search Depth");
622 uint32_t BitWidth = Mask.getBitWidth();
623 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
624 KnownZero.getBitWidth() == BitWidth &&
625 KnownOne.getBitWidth() == BitWidth &&
626 "V, Mask, KnownOne and KnownZero should have same BitWidth");
627 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
628 // We know all of the bits for a constant!
629 KnownOne = CI->getValue() & Mask;
630 KnownZero = ~KnownOne & Mask;
631 return;
632 }
633
634 if (Depth == 6 || Mask == 0)
635 return; // Limit search depth.
636
637 Instruction *I = dyn_cast<Instruction>(V);
638 if (!I) return;
639
640 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
641 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
642
643 switch (I->getOpcode()) {
644 case Instruction::And: {
645 // If either the LHS or the RHS are Zero, the result is zero.
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 APInt Mask2(Mask & ~KnownZero);
648 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
649 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651
652 // Output known-1 bits are only known if set in both the LHS & RHS.
653 KnownOne &= KnownOne2;
654 // Output known-0 are known to be clear if zero in either the LHS | RHS.
655 KnownZero |= KnownZero2;
656 return;
657 }
658 case Instruction::Or: {
659 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
660 APInt Mask2(Mask & ~KnownOne);
661 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
664
665 // Output known-0 bits are only known if clear in both the LHS & RHS.
666 KnownZero &= KnownZero2;
667 // Output known-1 are known to be set if set in either the LHS | RHS.
668 KnownOne |= KnownOne2;
669 return;
670 }
671 case Instruction::Xor: {
672 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
673 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
675 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676
677 // Output known-0 bits are known if clear or set in both the LHS & RHS.
678 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
679 // Output known-1 are known to be set if set in only one of the LHS, RHS.
680 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
681 KnownZero = KnownZeroOut;
682 return;
683 }
684 case Instruction::Select:
685 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
686 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
687 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
688 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
689
690 // Only known if known in both the LHS and RHS.
691 KnownOne &= KnownOne2;
692 KnownZero &= KnownZero2;
693 return;
694 case Instruction::FPTrunc:
695 case Instruction::FPExt:
696 case Instruction::FPToUI:
697 case Instruction::FPToSI:
698 case Instruction::SIToFP:
699 case Instruction::PtrToInt:
700 case Instruction::UIToFP:
701 case Instruction::IntToPtr:
702 return; // Can't work with floating point or pointers
703 case Instruction::Trunc: {
704 // All these have integer operands
705 uint32_t SrcBitWidth =
706 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
707 APInt MaskIn(Mask);
708 MaskIn.zext(SrcBitWidth);
709 KnownZero.zext(SrcBitWidth);
710 KnownOne.zext(SrcBitWidth);
711 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
712 KnownZero.trunc(BitWidth);
713 KnownOne.trunc(BitWidth);
714 return;
715 }
716 case Instruction::BitCast: {
717 const Type *SrcTy = I->getOperand(0)->getType();
718 if (SrcTy->isInteger()) {
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
720 return;
721 }
722 break;
723 }
724 case Instruction::ZExt: {
725 // Compute the bits in the result that are not present in the input.
726 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
727 uint32_t SrcBitWidth = SrcTy->getBitWidth();
728
729 APInt MaskIn(Mask);
730 MaskIn.trunc(SrcBitWidth);
731 KnownZero.trunc(SrcBitWidth);
732 KnownOne.trunc(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 // The top bits are known to be zero.
736 KnownZero.zext(BitWidth);
737 KnownOne.zext(BitWidth);
738 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
739 return;
740 }
741 case Instruction::SExt: {
742 // Compute the bits in the result that are not present in the input.
743 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
744 uint32_t SrcBitWidth = SrcTy->getBitWidth();
745
746 APInt MaskIn(Mask);
747 MaskIn.trunc(SrcBitWidth);
748 KnownZero.trunc(SrcBitWidth);
749 KnownOne.trunc(SrcBitWidth);
750 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 KnownZero.zext(BitWidth);
753 KnownOne.zext(BitWidth);
754
755 // If the sign bit of the input is known set or clear, then we know the
756 // top bits of the result.
757 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
758 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
759 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
760 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
761 return;
762 }
763 case Instruction::Shl:
764 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
765 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
766 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
767 APInt Mask2(Mask.lshr(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
769 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
770 KnownZero <<= ShiftAmt;
771 KnownOne <<= ShiftAmt;
772 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
773 return;
774 }
775 break;
776 case Instruction::LShr:
777 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
778 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
779 // Compute the new bits that are at the top now.
780 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
781
782 // Unsigned shift right.
783 APInt Mask2(Mask.shl(ShiftAmt));
784 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
785 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
786 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
788 // high bits known zero.
789 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
790 return;
791 }
792 break;
793 case Instruction::AShr:
794 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
795 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
796 // Compute the new bits that are at the top now.
797 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
798
799 // Signed shift right.
800 APInt Mask2(Mask.shl(ShiftAmt));
801 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
802 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
803 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
804 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
805
806 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
807 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
808 KnownZero |= HighBits;
809 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
810 KnownOne |= HighBits;
811 return;
812 }
813 break;
814 }
815}
816
817/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
818/// this predicate to simplify operations downstream. Mask is known to be zero
819/// for bits that V cannot have.
820static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
821 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
822 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
823 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
824 return (KnownZero & Mask) == Mask;
825}
826
827/// ShrinkDemandedConstant - Check to see if the specified operand of the
828/// specified instruction is a constant integer. If so, check to see if there
829/// are any bits set in the constant that are not demanded. If so, shrink the
830/// constant and return true.
831static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
832 APInt Demanded) {
833 assert(I && "No instruction?");
834 assert(OpNo < I->getNumOperands() && "Operand index too large");
835
836 // If the operand is not a constant integer, nothing to do.
837 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
838 if (!OpC) return false;
839
840 // If there are no bits set that aren't demanded, nothing to do.
841 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
842 if ((~Demanded & OpC->getValue()) == 0)
843 return false;
844
845 // This instruction is producing bits that are not demanded. Shrink the RHS.
846 Demanded &= OpC->getValue();
847 I->setOperand(OpNo, ConstantInt::get(Demanded));
848 return true;
849}
850
851// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
852// set of known zero and one bits, compute the maximum and minimum values that
853// could have the specified known zero and known one bits, returning them in
854// min/max.
855static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
856 const APInt& KnownZero,
857 const APInt& KnownOne,
858 APInt& Min, APInt& Max) {
859 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
860 assert(KnownZero.getBitWidth() == BitWidth &&
861 KnownOne.getBitWidth() == BitWidth &&
862 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
863 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
864 APInt UnknownBits = ~(KnownZero|KnownOne);
865
866 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
867 // bit if it is unknown.
868 Min = KnownOne;
869 Max = KnownOne|UnknownBits;
870
871 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
872 Min.set(BitWidth-1);
873 Max.clear(BitWidth-1);
874 }
875}
876
877// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
878// a set of known zero and one bits, compute the maximum and minimum values that
879// could have the specified known zero and known one bits, returning them in
880// min/max.
881static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000882 const APInt &KnownZero,
883 const APInt &KnownOne,
884 APInt &Min, APInt &Max) {
885 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 assert(KnownZero.getBitWidth() == BitWidth &&
887 KnownOne.getBitWidth() == BitWidth &&
888 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
889 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
890 APInt UnknownBits = ~(KnownZero|KnownOne);
891
892 // The minimum value is when the unknown bits are all zeros.
893 Min = KnownOne;
894 // The maximum value is when the unknown bits are all ones.
895 Max = KnownOne|UnknownBits;
896}
897
898/// SimplifyDemandedBits - This function attempts to replace V with a simpler
899/// value based on the demanded bits. When this function is called, it is known
900/// that only the bits set in DemandedMask of the result of V are ever used
901/// downstream. Consequently, depending on the mask and V, it may be possible
902/// to replace V with a constant or one of its operands. In such cases, this
903/// function does the replacement and returns true. In all other cases, it
904/// returns false after analyzing the expression and setting KnownOne and known
905/// to be one in the expression. KnownZero contains all the bits that are known
906/// to be zero in the expression. These are provided to potentially allow the
907/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
908/// the expression. KnownOne and KnownZero always follow the invariant that
909/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
910/// the bits in KnownOne and KnownZero may only be accurate for those bits set
911/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
912/// and KnownOne must all be the same.
913bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
914 APInt& KnownZero, APInt& KnownOne,
915 unsigned Depth) {
916 assert(V != 0 && "Null pointer of Value???");
917 assert(Depth <= 6 && "Limit Search Depth");
918 uint32_t BitWidth = DemandedMask.getBitWidth();
919 const IntegerType *VTy = cast<IntegerType>(V->getType());
920 assert(VTy->getBitWidth() == BitWidth &&
921 KnownZero.getBitWidth() == BitWidth &&
922 KnownOne.getBitWidth() == BitWidth &&
923 "Value *V, DemandedMask, KnownZero and KnownOne \
924 must have same BitWidth");
925 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
926 // We know all of the bits for a constant!
927 KnownOne = CI->getValue() & DemandedMask;
928 KnownZero = ~KnownOne & DemandedMask;
929 return false;
930 }
931
932 KnownZero.clear();
933 KnownOne.clear();
934 if (!V->hasOneUse()) { // Other users may use these bits.
935 if (Depth != 0) { // Not at the root.
936 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
937 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
938 return false;
939 }
940 // If this is the root being simplified, allow it to have multiple uses,
941 // just set the DemandedMask to all bits.
942 DemandedMask = APInt::getAllOnesValue(BitWidth);
943 } else if (DemandedMask == 0) { // Not demanding any bits from V.
944 if (V != UndefValue::get(VTy))
945 return UpdateValueUsesWith(V, UndefValue::get(VTy));
946 return false;
947 } else if (Depth == 6) { // Limit search depth.
948 return false;
949 }
950
951 Instruction *I = dyn_cast<Instruction>(V);
952 if (!I) return false; // Only analyze instructions.
953
954 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
955 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
956 switch (I->getOpcode()) {
957 default: break;
958 case Instruction::And:
959 // If either the LHS or the RHS are Zero, the result is zero.
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 RHSKnownZero, RHSKnownOne, Depth+1))
962 return true;
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965
966 // If something is known zero on the RHS, the bits aren't demanded on the
967 // LHS.
968 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
969 LHSKnownZero, LHSKnownOne, Depth+1))
970 return true;
971 assert((LHSKnownZero & LHSKnownOne) == 0 &&
972 "Bits known to be one AND zero?");
973
974 // If all of the demanded bits are known 1 on one side, return the other.
975 // These bits cannot contribute to the result of the 'and'.
976 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
977 (DemandedMask & ~LHSKnownZero))
978 return UpdateValueUsesWith(I, I->getOperand(0));
979 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
980 (DemandedMask & ~RHSKnownZero))
981 return UpdateValueUsesWith(I, I->getOperand(1));
982
983 // If all of the demanded bits in the inputs are known zeros, return zero.
984 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
985 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
986
987 // If the RHS is a constant, see if we can simplify it.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
989 return UpdateValueUsesWith(I, I);
990
991 // Output known-1 bits are only known if set in both the LHS & RHS.
992 RHSKnownOne &= LHSKnownOne;
993 // Output known-0 are known to be clear if zero in either the LHS | RHS.
994 RHSKnownZero |= LHSKnownZero;
995 break;
996 case Instruction::Or:
997 // If either the LHS or the RHS are One, the result is One.
998 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1000 return true;
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1003 // If something is known one on the RHS, the bits aren't demanded on the
1004 // LHS.
1005 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1006 LHSKnownZero, LHSKnownOne, Depth+1))
1007 return true;
1008 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1009 "Bits known to be one AND zero?");
1010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
1015 return UpdateValueUsesWith(I, I->getOperand(0));
1016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
1018 return UpdateValueUsesWith(I, I->getOperand(1));
1019
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
1024 return UpdateValueUsesWith(I, I->getOperand(0));
1025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
1027 return UpdateValueUsesWith(I, I->getOperand(1));
1028
1029 // If the RHS is a constant, see if we can simplify it.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 return UpdateValueUsesWith(I, I);
1032
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1037 break;
1038 case Instruction::Xor: {
1039 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1))
1041 return true;
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1045 LHSKnownZero, LHSKnownOne, Depth+1))
1046 return true;
1047 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1049
1050 // If all of the demanded bits are known zero on one side, return the other.
1051 // These bits cannot contribute to the result of the 'xor'.
1052 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1053 return UpdateValueUsesWith(I, I->getOperand(0));
1054 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1055 return UpdateValueUsesWith(I, I->getOperand(1));
1056
1057 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1059 (RHSKnownOne & LHSKnownOne);
1060 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1062 (RHSKnownOne & LHSKnownZero);
1063
1064 // If all of the demanded bits are known to be zero on one side or the
1065 // other, turn this into an *inclusive* or.
1066 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1067 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068 Instruction *Or =
1069 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1070 I->getName());
1071 InsertNewInstBefore(Or, *I);
1072 return UpdateValueUsesWith(I, Or);
1073 }
1074
1075 // If all of the demanded bits on one side are known, and all of the set
1076 // bits on that side are also known to be set on the other side, turn this
1077 // into an AND, as we know the bits will be cleared.
1078 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1080 // all known
1081 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1082 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1083 Instruction *And =
1084 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1085 InsertNewInstBefore(And, *I);
1086 return UpdateValueUsesWith(I, And);
1087 }
1088 }
1089
1090 // If the RHS is a constant, see if we can simplify it.
1091 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1092 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1093 return UpdateValueUsesWith(I, I);
1094
1095 RHSKnownZero = KnownZeroOut;
1096 RHSKnownOne = KnownOneOut;
1097 break;
1098 }
1099 case Instruction::Select:
1100 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1101 RHSKnownZero, RHSKnownOne, Depth+1))
1102 return true;
1103 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1104 LHSKnownZero, LHSKnownOne, Depth+1))
1105 return true;
1106 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1107 "Bits known to be one AND zero?");
1108 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1109 "Bits known to be one AND zero?");
1110
1111 // If the operands are constants, see if we can simplify them.
1112 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1113 return UpdateValueUsesWith(I, I);
1114 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1115 return UpdateValueUsesWith(I, I);
1116
1117 // Only known if known in both the LHS and RHS.
1118 RHSKnownOne &= LHSKnownOne;
1119 RHSKnownZero &= LHSKnownZero;
1120 break;
1121 case Instruction::Trunc: {
1122 uint32_t truncBf =
1123 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1124 DemandedMask.zext(truncBf);
1125 RHSKnownZero.zext(truncBf);
1126 RHSKnownOne.zext(truncBf);
1127 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
1129 return true;
1130 DemandedMask.trunc(BitWidth);
1131 RHSKnownZero.trunc(BitWidth);
1132 RHSKnownOne.trunc(BitWidth);
1133 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1134 "Bits known to be one AND zero?");
1135 break;
1136 }
1137 case Instruction::BitCast:
1138 if (!I->getOperand(0)->getType()->isInteger())
1139 return false;
1140
1141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
1143 return true;
1144 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1145 "Bits known to be one AND zero?");
1146 break;
1147 case Instruction::ZExt: {
1148 // Compute the bits in the result that are not present in the input.
1149 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1150 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1151
1152 DemandedMask.trunc(SrcBitWidth);
1153 RHSKnownZero.trunc(SrcBitWidth);
1154 RHSKnownOne.trunc(SrcBitWidth);
1155 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1156 RHSKnownZero, RHSKnownOne, Depth+1))
1157 return true;
1158 DemandedMask.zext(BitWidth);
1159 RHSKnownZero.zext(BitWidth);
1160 RHSKnownOne.zext(BitWidth);
1161 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1162 "Bits known to be one AND zero?");
1163 // The top bits are known to be zero.
1164 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1165 break;
1166 }
1167 case Instruction::SExt: {
1168 // Compute the bits in the result that are not present in the input.
1169 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1170 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1171
1172 APInt InputDemandedBits = DemandedMask &
1173 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176 // If any of the sign extended bits are demanded, we know that the sign
1177 // bit is demanded.
1178 if ((NewBits & DemandedMask) != 0)
1179 InputDemandedBits.set(SrcBitWidth-1);
1180
1181 InputDemandedBits.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
1184 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1185 RHSKnownZero, RHSKnownOne, Depth+1))
1186 return true;
1187 InputDemandedBits.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
1192
1193 // If the sign bit of the input is known set or clear, then we know the
1194 // top bits of the result.
1195
1196 // If the input sign bit is known zero, or if the NewBits are not demanded
1197 // convert this into a zero extension.
1198 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1199 {
1200 // Convert to ZExt cast
1201 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1202 return UpdateValueUsesWith(I, NewCast);
1203 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1204 RHSKnownOne |= NewBits;
1205 }
1206 break;
1207 }
1208 case Instruction::Add: {
1209 // Figure out what the input bits are. If the top bits of the and result
1210 // are not demanded, then the add doesn't demand them from its input
1211 // either.
1212 uint32_t NLZ = DemandedMask.countLeadingZeros();
1213
1214 // If there is a constant on the RHS, there are a variety of xformations
1215 // we can do.
1216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217 // If null, this should be simplified elsewhere. Some of the xforms here
1218 // won't work if the RHS is zero.
1219 if (RHS->isZero())
1220 break;
1221
1222 // If the top bit of the output is demanded, demand everything from the
1223 // input. Otherwise, we demand all the input bits except NLZ top bits.
1224 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1225
1226 // Find information about known zero/one bits in the input.
1227 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1228 LHSKnownZero, LHSKnownOne, Depth+1))
1229 return true;
1230
1231 // If the RHS of the add has bits set that can't affect the input, reduce
1232 // the constant.
1233 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1234 return UpdateValueUsesWith(I, I);
1235
1236 // Avoid excess work.
1237 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1238 break;
1239
1240 // Turn it into OR if input bits are zero.
1241 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1242 Instruction *Or =
1243 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1244 I->getName());
1245 InsertNewInstBefore(Or, *I);
1246 return UpdateValueUsesWith(I, Or);
1247 }
1248
1249 // We can say something about the output known-zero and known-one bits,
1250 // depending on potential carries from the input constant and the
1251 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1252 // bits set and the RHS constant is 0x01001, then we know we have a known
1253 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1254
1255 // To compute this, we first compute the potential carry bits. These are
1256 // the bits which may be modified. I'm not aware of a better way to do
1257 // this scan.
1258 const APInt& RHSVal = RHS->getValue();
1259 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1260
1261 // Now that we know which bits have carries, compute the known-1/0 sets.
1262
1263 // Bits are known one if they are known zero in one operand and one in the
1264 // other, and there is no input carry.
1265 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1266 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1267
1268 // Bits are known zero if they are known zero in both operands and there
1269 // is no input carry.
1270 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1271 } else {
1272 // If the high-bits of this ADD are not demanded, then it does not demand
1273 // the high bits of its LHS or RHS.
1274 if (DemandedMask[BitWidth-1] == 0) {
1275 // Right fill the mask of bits for this ADD to demand the most
1276 // significant bit and all those below it.
1277 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1278 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1279 LHSKnownZero, LHSKnownOne, Depth+1))
1280 return true;
1281 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1282 LHSKnownZero, LHSKnownOne, Depth+1))
1283 return true;
1284 }
1285 }
1286 break;
1287 }
1288 case Instruction::Sub:
1289 // If the high-bits of this SUB are not demanded, then it does not demand
1290 // the high bits of its LHS or RHS.
1291 if (DemandedMask[BitWidth-1] == 0) {
1292 // Right fill the mask of bits for this SUB to demand the most
1293 // significant bit and all those below it.
1294 uint32_t NLZ = DemandedMask.countLeadingZeros();
1295 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1296 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1297 LHSKnownZero, LHSKnownOne, Depth+1))
1298 return true;
1299 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1300 LHSKnownZero, LHSKnownOne, Depth+1))
1301 return true;
1302 }
1303 break;
1304 case Instruction::Shl:
1305 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1306 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1307 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1309 RHSKnownZero, RHSKnownOne, Depth+1))
1310 return true;
1311 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313 RHSKnownZero <<= ShiftAmt;
1314 RHSKnownOne <<= ShiftAmt;
1315 // low bits known zero.
1316 if (ShiftAmt)
1317 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1318 }
1319 break;
1320 case Instruction::LShr:
1321 // For a logical shift right
1322 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1323 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1324
1325 // Unsigned shift right.
1326 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1327 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1328 RHSKnownZero, RHSKnownOne, Depth+1))
1329 return true;
1330 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1331 "Bits known to be one AND zero?");
1332 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334 if (ShiftAmt) {
1335 // Compute the new bits that are at the top now.
1336 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1337 RHSKnownZero |= HighBits; // high bits known zero.
1338 }
1339 }
1340 break;
1341 case Instruction::AShr:
1342 // If this is an arithmetic shift right and only the low-bit is set, we can
1343 // always convert this into a logical shr, even if the shift amount is
1344 // variable. The low bit of the shift cannot be an input sign bit unless
1345 // the shift amount is >= the size of the datatype, which is undefined.
1346 if (DemandedMask == 1) {
1347 // Perform the logical shift right.
1348 Value *NewVal = BinaryOperator::createLShr(
1349 I->getOperand(0), I->getOperand(1), I->getName());
1350 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1351 return UpdateValueUsesWith(I, NewVal);
1352 }
1353
1354 // If the sign bit is the only bit demanded by this ashr, then there is no
1355 // need to do it, the shift doesn't change the high bit.
1356 if (DemandedMask.isSignBit())
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358
1359 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1360 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1361
1362 // Signed shift right.
1363 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1364 // If any of the "high bits" are demanded, we should set the sign bit as
1365 // demanded.
1366 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1367 DemandedMaskIn.set(BitWidth-1);
1368 if (SimplifyDemandedBits(I->getOperand(0),
1369 DemandedMaskIn,
1370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 // Compute the new bits that are at the top now.
1375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1377 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1378
1379 // Handle the sign bits.
1380 APInt SignBit(APInt::getSignBit(BitWidth));
1381 // Adjust to where it is now in the mask.
1382 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1383
1384 // If the input sign bit is known to be zero, or if none of the top bits
1385 // are demanded, turn this into an unsigned shift right.
1386 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1387 (HighBits & ~DemandedMask) == HighBits) {
1388 // Perform the logical shift right.
1389 Value *NewVal = BinaryOperator::createLShr(
1390 I->getOperand(0), SA, I->getName());
1391 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1392 return UpdateValueUsesWith(I, NewVal);
1393 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1394 RHSKnownOne |= HighBits;
1395 }
1396 }
1397 break;
1398 }
1399
1400 // If the client is only demanding bits that we know, return the known
1401 // constant.
1402 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1403 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1404 return false;
1405}
1406
1407
1408/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1409/// 64 or fewer elements. DemandedElts contains the set of elements that are
1410/// actually used by the caller. This method analyzes which elements of the
1411/// operand are undef and returns that information in UndefElts.
1412///
1413/// If the information about demanded elements can be used to simplify the
1414/// operation, the operation is simplified, then the resultant value is
1415/// returned. This returns null if no change was made.
1416Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1417 uint64_t &UndefElts,
1418 unsigned Depth) {
1419 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1420 assert(VWidth <= 64 && "Vector too wide to analyze!");
1421 uint64_t EltMask = ~0ULL >> (64-VWidth);
1422 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1423 "Invalid DemandedElts!");
1424
1425 if (isa<UndefValue>(V)) {
1426 // If the entire vector is undefined, just return this info.
1427 UndefElts = EltMask;
1428 return 0;
1429 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1430 UndefElts = EltMask;
1431 return UndefValue::get(V->getType());
1432 }
1433
1434 UndefElts = 0;
1435 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1436 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1437 Constant *Undef = UndefValue::get(EltTy);
1438
1439 std::vector<Constant*> Elts;
1440 for (unsigned i = 0; i != VWidth; ++i)
1441 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1442 Elts.push_back(Undef);
1443 UndefElts |= (1ULL << i);
1444 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1445 Elts.push_back(Undef);
1446 UndefElts |= (1ULL << i);
1447 } else { // Otherwise, defined.
1448 Elts.push_back(CP->getOperand(i));
1449 }
1450
1451 // If we changed the constant, return it.
1452 Constant *NewCP = ConstantVector::get(Elts);
1453 return NewCP != CP ? NewCP : 0;
1454 } else if (isa<ConstantAggregateZero>(V)) {
1455 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1456 // set to undef.
1457 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1458 Constant *Zero = Constant::getNullValue(EltTy);
1459 Constant *Undef = UndefValue::get(EltTy);
1460 std::vector<Constant*> Elts;
1461 for (unsigned i = 0; i != VWidth; ++i)
1462 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1463 UndefElts = DemandedElts ^ EltMask;
1464 return ConstantVector::get(Elts);
1465 }
1466
1467 if (!V->hasOneUse()) { // Other users may use these bits.
1468 if (Depth != 0) { // Not at the root.
1469 // TODO: Just compute the UndefElts information recursively.
1470 return false;
1471 }
1472 return false;
1473 } else if (Depth == 10) { // Limit search depth.
1474 return false;
1475 }
1476
1477 Instruction *I = dyn_cast<Instruction>(V);
1478 if (!I) return false; // Only analyze instructions.
1479
1480 bool MadeChange = false;
1481 uint64_t UndefElts2;
1482 Value *TmpV;
1483 switch (I->getOpcode()) {
1484 default: break;
1485
1486 case Instruction::InsertElement: {
1487 // If this is a variable index, we don't know which element it overwrites.
1488 // demand exactly the same input as we produce.
1489 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1490 if (Idx == 0) {
1491 // Note that we can't propagate undef elt info, because we don't know
1492 // which elt is getting updated.
1493 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1494 UndefElts2, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496 break;
1497 }
1498
1499 // If this is inserting an element that isn't demanded, remove this
1500 // insertelement.
1501 unsigned IdxNo = Idx->getZExtValue();
1502 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1503 return AddSoonDeadInstToWorklist(*I, 0);
1504
1505 // Otherwise, the element inserted overwrites whatever was there, so the
1506 // input demanded set is simpler than the output set.
1507 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1508 DemandedElts & ~(1ULL << IdxNo),
1509 UndefElts, Depth+1);
1510 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512 // The inserted element is defined.
1513 UndefElts |= 1ULL << IdxNo;
1514 break;
1515 }
1516 case Instruction::BitCast: {
1517 // Vector->vector casts only.
1518 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519 if (!VTy) break;
1520 unsigned InVWidth = VTy->getNumElements();
1521 uint64_t InputDemandedElts = 0;
1522 unsigned Ratio;
1523
1524 if (VWidth == InVWidth) {
1525 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1526 // elements as are demanded of us.
1527 Ratio = 1;
1528 InputDemandedElts = DemandedElts;
1529 } else if (VWidth > InVWidth) {
1530 // Untested so far.
1531 break;
1532
1533 // If there are more elements in the result than there are in the source,
1534 // then an input element is live if any of the corresponding output
1535 // elements are live.
1536 Ratio = VWidth/InVWidth;
1537 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538 if (DemandedElts & (1ULL << OutIdx))
1539 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540 }
1541 } else {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the source than there are in the result,
1546 // then an input element is live if the corresponding output element is
1547 // live.
1548 Ratio = InVWidth/VWidth;
1549 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550 if (DemandedElts & (1ULL << InIdx/Ratio))
1551 InputDemandedElts |= 1ULL << InIdx;
1552 }
1553
1554 // div/rem demand all inputs, because they don't want divide by zero.
1555 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556 UndefElts2, Depth+1);
1557 if (TmpV) {
1558 I->setOperand(0, TmpV);
1559 MadeChange = true;
1560 }
1561
1562 UndefElts = UndefElts2;
1563 if (VWidth > InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the result than there are in the source,
1566 // then an output element is undef if the corresponding input element is
1567 // undef.
1568 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570 UndefElts |= 1ULL << OutIdx;
1571 } else if (VWidth < InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the source than there are in the result,
1574 // then a result element is undef if all of the corresponding input
1575 // elements are undef.
1576 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1577 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1579 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1580 }
1581 break;
1582 }
1583 case Instruction::And:
1584 case Instruction::Or:
1585 case Instruction::Xor:
1586 case Instruction::Add:
1587 case Instruction::Sub:
1588 case Instruction::Mul:
1589 // div/rem demand all inputs, because they don't want divide by zero.
1590 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591 UndefElts, Depth+1);
1592 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594 UndefElts2, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 // Output elements are undefined if both are undefined. Consider things
1598 // like undef&0. The result is known zero, not undef.
1599 UndefElts &= UndefElts2;
1600 break;
1601
1602 case Instruction::Call: {
1603 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604 if (!II) break;
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607
1608 // Binary vector operations that work column-wise. A dest element is a
1609 // function of the corresponding input elements from the two inputs.
1610 case Intrinsic::x86_sse_sub_ss:
1611 case Intrinsic::x86_sse_mul_ss:
1612 case Intrinsic::x86_sse_min_ss:
1613 case Intrinsic::x86_sse_max_ss:
1614 case Intrinsic::x86_sse2_sub_sd:
1615 case Intrinsic::x86_sse2_mul_sd:
1616 case Intrinsic::x86_sse2_min_sd:
1617 case Intrinsic::x86_sse2_max_sd:
1618 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619 UndefElts, Depth+1);
1620 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625 // If only the low elt is demanded and this is a scalarizable intrinsic,
1626 // scalarize it now.
1627 if (DemandedElts == 1) {
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630 case Intrinsic::x86_sse_sub_ss:
1631 case Intrinsic::x86_sse_mul_ss:
1632 case Intrinsic::x86_sse2_sub_sd:
1633 case Intrinsic::x86_sse2_mul_sd:
1634 // TODO: Lower MIN/MAX/ABS/etc
1635 Value *LHS = II->getOperand(1);
1636 Value *RHS = II->getOperand(2);
1637 // Extract the element as scalars.
1638 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640
1641 switch (II->getIntrinsicID()) {
1642 default: assert(0 && "Case stmts out of sync!");
1643 case Intrinsic::x86_sse_sub_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
1645 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1646 II->getName()), *II);
1647 break;
1648 case Intrinsic::x86_sse_mul_ss:
1649 case Intrinsic::x86_sse2_mul_sd:
1650 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1651 II->getName()), *II);
1652 break;
1653 }
1654
1655 Instruction *New =
1656 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1657 II->getName());
1658 InsertNewInstBefore(New, *II);
1659 AddSoonDeadInstToWorklist(*II, 0);
1660 return New;
1661 }
1662 }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668 }
1669 break;
1670 }
1671 }
1672 return MadeChange ? I : 0;
1673}
1674
Nick Lewycky2de09a92007-09-06 02:40:25 +00001675/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00001677/// @brief Determine if the icmp Predicate is true when both operands are equal
1678static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1680 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1681 pred == ICmpInst::ICMP_SLE;
1682}
1683
Nick Lewycky2de09a92007-09-06 02:40:25 +00001684/// @returns true if the specified compare instruction is
1685/// true when both operands are equal...
1686/// @brief Determine if the ICmpInst returns true when both operands are equal
1687static bool isTrueWhenEqual(ICmpInst &ICI) {
1688 return isTrueWhenEqual(ICI.getPredicate());
1689}
1690
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691/// AssociativeOpt - Perform an optimization on an associative operator. This
1692/// function is designed to check a chain of associative operators for a
1693/// potential to apply a certain optimization. Since the optimization may be
1694/// applicable if the expression was reassociated, this checks the chain, then
1695/// reassociates the expression as necessary to expose the optimization
1696/// opportunity. This makes use of a special Functor, which must define
1697/// 'shouldApply' and 'apply' methods.
1698///
1699template<typename Functor>
1700Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701 unsigned Opcode = Root.getOpcode();
1702 Value *LHS = Root.getOperand(0);
1703
1704 // Quick check, see if the immediate LHS matches...
1705 if (F.shouldApply(LHS))
1706 return F.apply(Root);
1707
1708 // Otherwise, if the LHS is not of the same opcode as the root, return.
1709 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711 // Should we apply this transform to the RHS?
1712 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714 // If not to the RHS, check to see if we should apply to the LHS...
1715 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1717 ShouldApply = true;
1718 }
1719
1720 // If the functor wants to apply the optimization to the RHS of LHSI,
1721 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722 if (ShouldApply) {
1723 BasicBlock *BB = Root.getParent();
1724
1725 // Now all of the instructions are in the current basic block, go ahead
1726 // and perform the reassociation.
1727 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1728
1729 // First move the selected RHS to the LHS of the root...
1730 Root.setOperand(0, LHSI->getOperand(1));
1731
1732 // Make what used to be the LHS of the root be the user of the root...
1733 Value *ExtraOperand = TmpLHSI->getOperand(1);
1734 if (&Root == TmpLHSI) {
1735 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1736 return 0;
1737 }
1738 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1739 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1740 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1741 BasicBlock::iterator ARI = &Root; ++ARI;
1742 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1743 ARI = Root;
1744
1745 // Now propagate the ExtraOperand down the chain of instructions until we
1746 // get to LHSI.
1747 while (TmpLHSI != LHSI) {
1748 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1749 // Move the instruction to immediately before the chain we are
1750 // constructing to avoid breaking dominance properties.
1751 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1752 BB->getInstList().insert(ARI, NextLHSI);
1753 ARI = NextLHSI;
1754
1755 Value *NextOp = NextLHSI->getOperand(1);
1756 NextLHSI->setOperand(1, ExtraOperand);
1757 TmpLHSI = NextLHSI;
1758 ExtraOperand = NextOp;
1759 }
1760
1761 // Now that the instructions are reassociated, have the functor perform
1762 // the transformation...
1763 return F.apply(Root);
1764 }
1765
1766 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1767 }
1768 return 0;
1769}
1770
1771
1772// AddRHS - Implements: X + X --> X << 1
1773struct AddRHS {
1774 Value *RHS;
1775 AddRHS(Value *rhs) : RHS(rhs) {}
1776 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1777 Instruction *apply(BinaryOperator &Add) const {
1778 return BinaryOperator::createShl(Add.getOperand(0),
1779 ConstantInt::get(Add.getType(), 1));
1780 }
1781};
1782
1783// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1784// iff C1&C2 == 0
1785struct AddMaskingAnd {
1786 Constant *C2;
1787 AddMaskingAnd(Constant *c) : C2(c) {}
1788 bool shouldApply(Value *LHS) const {
1789 ConstantInt *C1;
1790 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1791 ConstantExpr::getAnd(C1, C2)->isNullValue();
1792 }
1793 Instruction *apply(BinaryOperator &Add) const {
1794 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1795 }
1796};
1797
1798static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1799 InstCombiner *IC) {
1800 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1801 if (Constant *SOC = dyn_cast<Constant>(SO))
1802 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1803
1804 return IC->InsertNewInstBefore(CastInst::create(
1805 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1806 }
1807
1808 // Figure out if the constant is the left or the right argument.
1809 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1810 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1811
1812 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1813 if (ConstIsRHS)
1814 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1815 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1816 }
1817
1818 Value *Op0 = SO, *Op1 = ConstOperand;
1819 if (!ConstIsRHS)
1820 std::swap(Op0, Op1);
1821 Instruction *New;
1822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1823 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1824 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1826 SO->getName()+".cmp");
1827 else {
1828 assert(0 && "Unknown binary instruction type!");
1829 abort();
1830 }
1831 return IC->InsertNewInstBefore(New, I);
1832}
1833
1834// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1835// constant as the other operand, try to fold the binary operator into the
1836// select arguments. This also works for Cast instructions, which obviously do
1837// not have a second operand.
1838static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1839 InstCombiner *IC) {
1840 // Don't modify shared select instructions
1841 if (!SI->hasOneUse()) return 0;
1842 Value *TV = SI->getOperand(1);
1843 Value *FV = SI->getOperand(2);
1844
1845 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1846 // Bool selects with constant operands can be folded to logical ops.
1847 if (SI->getType() == Type::Int1Ty) return 0;
1848
1849 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1850 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1851
1852 return new SelectInst(SI->getCondition(), SelectTrueVal,
1853 SelectFalseVal);
1854 }
1855 return 0;
1856}
1857
1858
1859/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1860/// node as operand #0, see if we can fold the instruction into the PHI (which
1861/// is only possible if all operands to the PHI are constants).
1862Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1863 PHINode *PN = cast<PHINode>(I.getOperand(0));
1864 unsigned NumPHIValues = PN->getNumIncomingValues();
1865 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1866
1867 // Check to see if all of the operands of the PHI are constants. If there is
1868 // one non-constant value, remember the BB it is. If there is more than one
1869 // or if *it* is a PHI, bail out.
1870 BasicBlock *NonConstBB = 0;
1871 for (unsigned i = 0; i != NumPHIValues; ++i)
1872 if (!isa<Constant>(PN->getIncomingValue(i))) {
1873 if (NonConstBB) return 0; // More than one non-const value.
1874 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1875 NonConstBB = PN->getIncomingBlock(i);
1876
1877 // If the incoming non-constant value is in I's block, we have an infinite
1878 // loop.
1879 if (NonConstBB == I.getParent())
1880 return 0;
1881 }
1882
1883 // If there is exactly one non-constant value, we can insert a copy of the
1884 // operation in that block. However, if this is a critical edge, we would be
1885 // inserting the computation one some other paths (e.g. inside a loop). Only
1886 // do this if the pred block is unconditionally branching into the phi block.
1887 if (NonConstBB) {
1888 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1889 if (!BI || !BI->isUnconditional()) return 0;
1890 }
1891
1892 // Okay, we can do the transformation: create the new PHI node.
1893 PHINode *NewPN = new PHINode(I.getType(), "");
1894 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1895 InsertNewInstBefore(NewPN, *PN);
1896 NewPN->takeName(PN);
1897
1898 // Next, add all of the operands to the PHI.
1899 if (I.getNumOperands() == 2) {
1900 Constant *C = cast<Constant>(I.getOperand(1));
1901 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001902 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1904 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1905 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1906 else
1907 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1908 } else {
1909 assert(PN->getIncomingBlock(i) == NonConstBB);
1910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1911 InV = BinaryOperator::create(BO->getOpcode(),
1912 PN->getIncomingValue(i), C, "phitmp",
1913 NonConstBB->getTerminator());
1914 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1915 InV = CmpInst::create(CI->getOpcode(),
1916 CI->getPredicate(),
1917 PN->getIncomingValue(i), C, "phitmp",
1918 NonConstBB->getTerminator());
1919 else
1920 assert(0 && "Unknown binop!");
1921
1922 AddToWorkList(cast<Instruction>(InV));
1923 }
1924 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1925 }
1926 } else {
1927 CastInst *CI = cast<CastInst>(&I);
1928 const Type *RetTy = CI->getType();
1929 for (unsigned i = 0; i != NumPHIValues; ++i) {
1930 Value *InV;
1931 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1932 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1933 } else {
1934 assert(PN->getIncomingBlock(i) == NonConstBB);
1935 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1936 I.getType(), "phitmp",
1937 NonConstBB->getTerminator());
1938 AddToWorkList(cast<Instruction>(InV));
1939 }
1940 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1941 }
1942 }
1943 return ReplaceInstUsesWith(I, NewPN);
1944}
1945
Chris Lattner55476162008-01-29 06:52:45 +00001946
1947/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1948/// value is never equal to -0.0.
1949///
1950/// Note that this function will need to be revisited when we support nondefault
1951/// rounding modes!
1952///
1953static bool CannotBeNegativeZero(const Value *V) {
1954 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1955 return !CFP->getValueAPF().isNegZero();
1956
1957 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1958 if (const Instruction *I = dyn_cast<Instruction>(V)) {
1959 if (I->getOpcode() == Instruction::Add &&
1960 isa<ConstantFP>(I->getOperand(1)) &&
1961 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1962 return true;
1963
1964 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1965 if (II->getIntrinsicID() == Intrinsic::sqrt)
1966 return CannotBeNegativeZero(II->getOperand(1));
1967
1968 if (const CallInst *CI = dyn_cast<CallInst>(I))
1969 if (const Function *F = CI->getCalledFunction()) {
1970 if (F->isDeclaration()) {
1971 switch (F->getNameLen()) {
1972 case 3: // abs(x) != -0.0
1973 if (!strcmp(F->getNameStart(), "abs")) return true;
1974 break;
1975 case 4: // abs[lf](x) != -0.0
1976 if (!strcmp(F->getNameStart(), "absf")) return true;
1977 if (!strcmp(F->getNameStart(), "absl")) return true;
1978 break;
1979 }
1980 }
1981 }
1982 }
1983
1984 return false;
1985}
1986
1987
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1989 bool Changed = SimplifyCommutative(I);
1990 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1991
1992 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1993 // X + undef -> undef
1994 if (isa<UndefValue>(RHS))
1995 return ReplaceInstUsesWith(I, RHS);
1996
1997 // X + 0 --> X
1998 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1999 if (RHSC->isNullValue())
2000 return ReplaceInstUsesWith(I, LHS);
2001 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002002 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2003 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 return ReplaceInstUsesWith(I, LHS);
2005 }
2006
2007 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2008 // X + (signbit) --> X ^ signbit
2009 const APInt& Val = CI->getValue();
2010 uint32_t BitWidth = Val.getBitWidth();
2011 if (Val == APInt::getSignBit(BitWidth))
2012 return BinaryOperator::createXor(LHS, RHS);
2013
2014 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2015 // (X & 254)+1 -> (X&254)|1
2016 if (!isa<VectorType>(I.getType())) {
2017 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2018 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2019 KnownZero, KnownOne))
2020 return &I;
2021 }
2022 }
2023
2024 if (isa<PHINode>(LHS))
2025 if (Instruction *NV = FoldOpIntoPhi(I))
2026 return NV;
2027
2028 ConstantInt *XorRHS = 0;
2029 Value *XorLHS = 0;
2030 if (isa<ConstantInt>(RHSC) &&
2031 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2032 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2033 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2034
2035 uint32_t Size = TySizeBits / 2;
2036 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2037 APInt CFF80Val(-C0080Val);
2038 do {
2039 if (TySizeBits > Size) {
2040 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2041 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2042 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2043 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2044 // This is a sign extend if the top bits are known zero.
2045 if (!MaskedValueIsZero(XorLHS,
2046 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2047 Size = 0; // Not a sign ext, but can't be any others either.
2048 break;
2049 }
2050 }
2051 Size >>= 1;
2052 C0080Val = APIntOps::lshr(C0080Val, Size);
2053 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2054 } while (Size >= 1);
2055
2056 // FIXME: This shouldn't be necessary. When the backends can handle types
2057 // with funny bit widths then this whole cascade of if statements should
2058 // be removed. It is just here to get the size of the "middle" type back
2059 // up to something that the back ends can handle.
2060 const Type *MiddleType = 0;
2061 switch (Size) {
2062 default: break;
2063 case 32: MiddleType = Type::Int32Ty; break;
2064 case 16: MiddleType = Type::Int16Ty; break;
2065 case 8: MiddleType = Type::Int8Ty; break;
2066 }
2067 if (MiddleType) {
2068 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2069 InsertNewInstBefore(NewTrunc, I);
2070 return new SExtInst(NewTrunc, I.getType(), I.getName());
2071 }
2072 }
2073 }
2074
2075 // X + X --> X << 1
2076 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2077 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2078
2079 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2080 if (RHSI->getOpcode() == Instruction::Sub)
2081 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2082 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2083 }
2084 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2085 if (LHSI->getOpcode() == Instruction::Sub)
2086 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2087 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2088 }
2089 }
2090
2091 // -A + B --> B - A
2092 if (Value *V = dyn_castNegVal(LHS))
2093 return BinaryOperator::createSub(RHS, V);
2094
2095 // A + -B --> A - B
2096 if (!isa<Constant>(RHS))
2097 if (Value *V = dyn_castNegVal(RHS))
2098 return BinaryOperator::createSub(LHS, V);
2099
2100
2101 ConstantInt *C2;
2102 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2103 if (X == RHS) // X*C + X --> X * (C+1)
2104 return BinaryOperator::createMul(RHS, AddOne(C2));
2105
2106 // X*C1 + X*C2 --> X * (C1+C2)
2107 ConstantInt *C1;
2108 if (X == dyn_castFoldableMul(RHS, C1))
2109 return BinaryOperator::createMul(X, Add(C1, C2));
2110 }
2111
2112 // X + X*C --> X * (C+1)
2113 if (dyn_castFoldableMul(RHS, C2) == LHS)
2114 return BinaryOperator::createMul(LHS, AddOne(C2));
2115
2116 // X + ~X --> -1 since ~X = -X-1
2117 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2118 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2119
2120
2121 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2122 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2123 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2124 return R;
2125
2126 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2127 Value *X = 0;
2128 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2129 return BinaryOperator::createSub(SubOne(CRHS), X);
2130
2131 // (X & FF00) + xx00 -> (X+xx00) & FF00
2132 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2133 Constant *Anded = And(CRHS, C2);
2134 if (Anded == CRHS) {
2135 // See if all bits from the first bit set in the Add RHS up are included
2136 // in the mask. First, get the rightmost bit.
2137 const APInt& AddRHSV = CRHS->getValue();
2138
2139 // Form a mask of all bits from the lowest bit added through the top.
2140 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2141
2142 // See if the and mask includes all of these bits.
2143 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2144
2145 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2146 // Okay, the xform is safe. Insert the new add pronto.
2147 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2148 LHS->getName()), I);
2149 return BinaryOperator::createAnd(NewAdd, C2);
2150 }
2151 }
2152 }
2153
2154 // Try to fold constant add into select arguments.
2155 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2156 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2157 return R;
2158 }
2159
2160 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002161 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162 {
2163 CastInst *CI = dyn_cast<CastInst>(LHS);
2164 Value *Other = RHS;
2165 if (!CI) {
2166 CI = dyn_cast<CastInst>(RHS);
2167 Other = LHS;
2168 }
2169 if (CI && CI->getType()->isSized() &&
2170 (CI->getType()->getPrimitiveSizeInBits() ==
2171 TD->getIntPtrType()->getPrimitiveSizeInBits())
2172 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002173 unsigned AS =
2174 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002175 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2176 PointerType::get(Type::Int8Ty, AS), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2178 return new PtrToIntInst(I2, CI->getType());
2179 }
2180 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002181
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002182 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002183 {
2184 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2185 Value *Other = RHS;
2186 if (!SI) {
2187 SI = dyn_cast<SelectInst>(RHS);
2188 Other = LHS;
2189 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002190 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002191 Value *TV = SI->getTrueValue();
2192 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002193 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002194
2195 // Can we fold the add into the argument of the select?
2196 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002197 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2198 A == Other) // Fold the add into the true select value.
2199 return new SelectInst(SI->getCondition(), N, A);
2200 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2201 A == Other) // Fold the add into the false select value.
2202 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002203 }
2204 }
Chris Lattner55476162008-01-29 06:52:45 +00002205
2206 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2207 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2208 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2209 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210
2211 return Changed ? &I : 0;
2212}
2213
2214// isSignBit - Return true if the value represented by the constant only has the
2215// highest order bit set.
2216static bool isSignBit(ConstantInt *CI) {
2217 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2218 return CI->getValue() == APInt::getSignBit(NumBits);
2219}
2220
2221Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2223
2224 if (Op0 == Op1) // sub X, X -> 0
2225 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2226
2227 // If this is a 'B = x-(-A)', change to B = x+A...
2228 if (Value *V = dyn_castNegVal(Op1))
2229 return BinaryOperator::createAdd(Op0, V);
2230
2231 if (isa<UndefValue>(Op0))
2232 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2233 if (isa<UndefValue>(Op1))
2234 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2235
2236 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2237 // Replace (-1 - A) with (~A)...
2238 if (C->isAllOnesValue())
2239 return BinaryOperator::createNot(Op1);
2240
2241 // C - ~X == X + (1+C)
2242 Value *X = 0;
2243 if (match(Op1, m_Not(m_Value(X))))
2244 return BinaryOperator::createAdd(X, AddOne(C));
2245
2246 // -(X >>u 31) -> (X >>s 31)
2247 // -(X >>s 31) -> (X >>u 31)
2248 if (C->isZero()) {
2249 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2250 if (SI->getOpcode() == Instruction::LShr) {
2251 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2252 // Check to see if we are shifting out everything but the sign bit.
2253 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2254 SI->getType()->getPrimitiveSizeInBits()-1) {
2255 // Ok, the transformation is safe. Insert AShr.
2256 return BinaryOperator::create(Instruction::AShr,
2257 SI->getOperand(0), CU, SI->getName());
2258 }
2259 }
2260 }
2261 else if (SI->getOpcode() == Instruction::AShr) {
2262 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2263 // Check to see if we are shifting out everything but the sign bit.
2264 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2265 SI->getType()->getPrimitiveSizeInBits()-1) {
2266 // Ok, the transformation is safe. Insert LShr.
2267 return BinaryOperator::createLShr(
2268 SI->getOperand(0), CU, SI->getName());
2269 }
2270 }
2271 }
2272 }
2273
2274 // Try to fold constant sub into select arguments.
2275 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2276 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2277 return R;
2278
2279 if (isa<PHINode>(Op0))
2280 if (Instruction *NV = FoldOpIntoPhi(I))
2281 return NV;
2282 }
2283
2284 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2285 if (Op1I->getOpcode() == Instruction::Add &&
2286 !Op0->getType()->isFPOrFPVector()) {
2287 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2288 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2289 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2290 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2291 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2292 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2293 // C1-(X+C2) --> (C1-C2)-X
2294 return BinaryOperator::createSub(Subtract(CI1, CI2),
2295 Op1I->getOperand(0));
2296 }
2297 }
2298
2299 if (Op1I->hasOneUse()) {
2300 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2301 // is not used by anyone else...
2302 //
2303 if (Op1I->getOpcode() == Instruction::Sub &&
2304 !Op1I->getType()->isFPOrFPVector()) {
2305 // Swap the two operands of the subexpr...
2306 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2307 Op1I->setOperand(0, IIOp1);
2308 Op1I->setOperand(1, IIOp0);
2309
2310 // Create the new top level add instruction...
2311 return BinaryOperator::createAdd(Op0, Op1);
2312 }
2313
2314 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2315 //
2316 if (Op1I->getOpcode() == Instruction::And &&
2317 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2318 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2319
2320 Value *NewNot =
2321 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2322 return BinaryOperator::createAnd(Op0, NewNot);
2323 }
2324
2325 // 0 - (X sdiv C) -> (X sdiv -C)
2326 if (Op1I->getOpcode() == Instruction::SDiv)
2327 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2328 if (CSI->isZero())
2329 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2330 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2331 ConstantExpr::getNeg(DivRHS));
2332
2333 // X - X*C --> X * (1-C)
2334 ConstantInt *C2 = 0;
2335 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2336 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2337 return BinaryOperator::createMul(Op0, CP1);
2338 }
Dan Gohmanda338742007-09-17 17:31:57 +00002339
2340 // X - ((X / Y) * Y) --> X % Y
2341 if (Op1I->getOpcode() == Instruction::Mul)
2342 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2343 if (Op0 == I->getOperand(0) &&
2344 Op1I->getOperand(1) == I->getOperand(1)) {
2345 if (I->getOpcode() == Instruction::SDiv)
2346 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2347 if (I->getOpcode() == Instruction::UDiv)
2348 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2349 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 }
2351 }
2352
2353 if (!Op0->getType()->isFPOrFPVector())
2354 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2355 if (Op0I->getOpcode() == Instruction::Add) {
2356 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2357 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2358 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2359 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2360 } else if (Op0I->getOpcode() == Instruction::Sub) {
2361 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2362 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2363 }
2364
2365 ConstantInt *C1;
2366 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2367 if (X == Op1) // X*C - X --> X * (C-1)
2368 return BinaryOperator::createMul(Op1, SubOne(C1));
2369
2370 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2371 if (X == dyn_castFoldableMul(Op1, C2))
2372 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2373 }
2374 return 0;
2375}
2376
2377/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2378/// comparison only checks the sign bit. If it only checks the sign bit, set
2379/// TrueIfSigned if the result of the comparison is true when the input value is
2380/// signed.
2381static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2382 bool &TrueIfSigned) {
2383 switch (pred) {
2384 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2385 TrueIfSigned = true;
2386 return RHS->isZero();
2387 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2388 TrueIfSigned = true;
2389 return RHS->isAllOnesValue();
2390 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2391 TrueIfSigned = false;
2392 return RHS->isAllOnesValue();
2393 case ICmpInst::ICMP_UGT:
2394 // True if LHS u> RHS and RHS == high-bit-mask - 1
2395 TrueIfSigned = true;
2396 return RHS->getValue() ==
2397 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2398 case ICmpInst::ICMP_UGE:
2399 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2400 TrueIfSigned = true;
2401 return RHS->getValue() ==
2402 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2403 default:
2404 return false;
2405 }
2406}
2407
2408Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2409 bool Changed = SimplifyCommutative(I);
2410 Value *Op0 = I.getOperand(0);
2411
2412 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2414
2415 // Simplify mul instructions with a constant RHS...
2416 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2417 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2418
2419 // ((X << C1)*C2) == (X * (C2 << C1))
2420 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2421 if (SI->getOpcode() == Instruction::Shl)
2422 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2423 return BinaryOperator::createMul(SI->getOperand(0),
2424 ConstantExpr::getShl(CI, ShOp));
2425
2426 if (CI->isZero())
2427 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2428 if (CI->equalsInt(1)) // X * 1 == X
2429 return ReplaceInstUsesWith(I, Op0);
2430 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2431 return BinaryOperator::createNeg(Op0, I.getName());
2432
2433 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2434 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2435 return BinaryOperator::createShl(Op0,
2436 ConstantInt::get(Op0->getType(), Val.logBase2()));
2437 }
2438 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2439 if (Op1F->isNullValue())
2440 return ReplaceInstUsesWith(I, Op1);
2441
2442 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2443 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002444 // We need a better interface for long double here.
2445 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2446 if (Op1F->isExactlyValue(1.0))
2447 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 }
2449
2450 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2451 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2452 isa<ConstantInt>(Op0I->getOperand(1))) {
2453 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2454 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2455 Op1, "tmp");
2456 InsertNewInstBefore(Add, I);
2457 Value *C1C2 = ConstantExpr::getMul(Op1,
2458 cast<Constant>(Op0I->getOperand(1)));
2459 return BinaryOperator::createAdd(Add, C1C2);
2460
2461 }
2462
2463 // Try to fold constant mul into select arguments.
2464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2466 return R;
2467
2468 if (isa<PHINode>(Op0))
2469 if (Instruction *NV = FoldOpIntoPhi(I))
2470 return NV;
2471 }
2472
2473 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2474 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2475 return BinaryOperator::createMul(Op0v, Op1v);
2476
2477 // If one of the operands of the multiply is a cast from a boolean value, then
2478 // we know the bool is either zero or one, so this is a 'masking' multiply.
2479 // See if we can simplify things based on how the boolean was originally
2480 // formed.
2481 CastInst *BoolCast = 0;
2482 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2483 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2484 BoolCast = CI;
2485 if (!BoolCast)
2486 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2487 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2488 BoolCast = CI;
2489 if (BoolCast) {
2490 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2491 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2492 const Type *SCOpTy = SCIOp0->getType();
2493 bool TIS = false;
2494
2495 // If the icmp is true iff the sign bit of X is set, then convert this
2496 // multiply into a shift/and combination.
2497 if (isa<ConstantInt>(SCIOp1) &&
2498 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2499 TIS) {
2500 // Shift the X value right to turn it into "all signbits".
2501 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2502 SCOpTy->getPrimitiveSizeInBits()-1);
2503 Value *V =
2504 InsertNewInstBefore(
2505 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2506 BoolCast->getOperand(0)->getName()+
2507 ".mask"), I);
2508
2509 // If the multiply type is not the same as the source type, sign extend
2510 // or truncate to the multiply type.
2511 if (I.getType() != V->getType()) {
2512 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2513 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2514 Instruction::CastOps opcode =
2515 (SrcBits == DstBits ? Instruction::BitCast :
2516 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2517 V = InsertCastBefore(opcode, V, I.getType(), I);
2518 }
2519
2520 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2521 return BinaryOperator::createAnd(V, OtherOp);
2522 }
2523 }
2524 }
2525
2526 return Changed ? &I : 0;
2527}
2528
2529/// This function implements the transforms on div instructions that work
2530/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2531/// used by the visitors to those instructions.
2532/// @brief Transforms common to all three div instructions
2533Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2535
2536 // undef / X -> 0
2537 if (isa<UndefValue>(Op0))
2538 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2539
2540 // X / undef -> undef
2541 if (isa<UndefValue>(Op1))
2542 return ReplaceInstUsesWith(I, Op1);
2543
Chris Lattner5be238b2008-01-28 00:58:18 +00002544 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2545 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002547 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2548 // the same basic block, then we replace the select with Y, and the
2549 // condition of the select with false (if the cond value is in the same BB).
2550 // If the select has uses other than the div, this allows them to be
2551 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2552 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553 if (ST->isNullValue()) {
2554 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2555 if (CondI && CondI->getParent() == I.getParent())
2556 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2557 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2558 I.setOperand(1, SI->getOperand(2));
2559 else
2560 UpdateValueUsesWith(SI, SI->getOperand(2));
2561 return &I;
2562 }
2563
Chris Lattner5be238b2008-01-28 00:58:18 +00002564 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2565 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 if (ST->isNullValue()) {
2567 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2568 if (CondI && CondI->getParent() == I.getParent())
2569 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2570 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2571 I.setOperand(1, SI->getOperand(1));
2572 else
2573 UpdateValueUsesWith(SI, SI->getOperand(1));
2574 return &I;
2575 }
2576 }
2577
2578 return 0;
2579}
2580
2581/// This function implements the transforms common to both integer division
2582/// instructions (udiv and sdiv). It is called by the visitors to those integer
2583/// division instructions.
2584/// @brief Common integer divide transforms
2585Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2586 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588 if (Instruction *Common = commonDivTransforms(I))
2589 return Common;
2590
2591 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2592 // div X, 1 == X
2593 if (RHS->equalsInt(1))
2594 return ReplaceInstUsesWith(I, Op0);
2595
2596 // (X / C1) / C2 -> X / (C1*C2)
2597 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2598 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2599 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2600 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2601 Multiply(RHS, LHSRHS));
2602 }
2603
2604 if (!RHS->isZero()) { // avoid X udiv 0
2605 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2606 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2607 return R;
2608 if (isa<PHINode>(Op0))
2609 if (Instruction *NV = FoldOpIntoPhi(I))
2610 return NV;
2611 }
2612 }
2613
2614 // 0 / X == 0, we don't need to preserve faults!
2615 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2616 if (LHS->equalsInt(0))
2617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2618
2619 return 0;
2620}
2621
2622Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2623 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2624
2625 // Handle the integer div common cases
2626 if (Instruction *Common = commonIDivTransforms(I))
2627 return Common;
2628
2629 // X udiv C^2 -> X >> C
2630 // Check to see if this is an unsigned division with an exact power of 2,
2631 // if so, convert to a right shift.
2632 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2633 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2634 return BinaryOperator::createLShr(Op0,
2635 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2636 }
2637
2638 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2639 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2640 if (RHSI->getOpcode() == Instruction::Shl &&
2641 isa<ConstantInt>(RHSI->getOperand(0))) {
2642 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2643 if (C1.isPowerOf2()) {
2644 Value *N = RHSI->getOperand(1);
2645 const Type *NTy = N->getType();
2646 if (uint32_t C2 = C1.logBase2()) {
2647 Constant *C2V = ConstantInt::get(NTy, C2);
2648 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2649 }
2650 return BinaryOperator::createLShr(Op0, N);
2651 }
2652 }
2653 }
2654
2655 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2656 // where C1&C2 are powers of two.
2657 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2658 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2659 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2660 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2661 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2662 // Compute the shift amounts
2663 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2664 // Construct the "on true" case of the select
2665 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2666 Instruction *TSI = BinaryOperator::createLShr(
2667 Op0, TC, SI->getName()+".t");
2668 TSI = InsertNewInstBefore(TSI, I);
2669
2670 // Construct the "on false" case of the select
2671 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2672 Instruction *FSI = BinaryOperator::createLShr(
2673 Op0, FC, SI->getName()+".f");
2674 FSI = InsertNewInstBefore(FSI, I);
2675
2676 // construct the select instruction and return it.
2677 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2678 }
2679 }
2680 return 0;
2681}
2682
2683Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2684 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2685
2686 // Handle the integer div common cases
2687 if (Instruction *Common = commonIDivTransforms(I))
2688 return Common;
2689
2690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2691 // sdiv X, -1 == -X
2692 if (RHS->isAllOnesValue())
2693 return BinaryOperator::createNeg(Op0);
2694
2695 // -X/C -> X/-C
2696 if (Value *LHSNeg = dyn_castNegVal(Op0))
2697 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2698 }
2699
2700 // If the sign bits of both operands are zero (i.e. we can prove they are
2701 // unsigned inputs), turn this into a udiv.
2702 if (I.getType()->isInteger()) {
2703 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2704 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002705 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2707 }
2708 }
2709
2710 return 0;
2711}
2712
2713Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2714 return commonDivTransforms(I);
2715}
2716
2717/// GetFactor - If we can prove that the specified value is at least a multiple
2718/// of some factor, return that factor.
2719static Constant *GetFactor(Value *V) {
2720 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2721 return CI;
2722
2723 // Unless we can be tricky, we know this is a multiple of 1.
2724 Constant *Result = ConstantInt::get(V->getType(), 1);
2725
2726 Instruction *I = dyn_cast<Instruction>(V);
2727 if (!I) return Result;
2728
2729 if (I->getOpcode() == Instruction::Mul) {
2730 // Handle multiplies by a constant, etc.
2731 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2732 GetFactor(I->getOperand(1)));
2733 } else if (I->getOpcode() == Instruction::Shl) {
2734 // (X<<C) -> X * (1 << C)
2735 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2736 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2737 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2738 }
2739 } else if (I->getOpcode() == Instruction::And) {
2740 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2741 // X & 0xFFF0 is known to be a multiple of 16.
2742 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnera03930e2007-11-23 22:35:18 +00002743 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002744 return ConstantExpr::getShl(Result,
2745 ConstantInt::get(Result->getType(), Zeros));
2746 }
2747 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2748 // Only handle int->int casts.
2749 if (!CI->isIntegerCast())
2750 return Result;
2751 Value *Op = CI->getOperand(0);
2752 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2753 }
2754 return Result;
2755}
2756
2757/// This function implements the transforms on rem instructions that work
2758/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2759/// is used by the visitors to those instructions.
2760/// @brief Transforms common to all three rem instructions
2761Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2763
2764 // 0 % X == 0, we don't need to preserve faults!
2765 if (Constant *LHS = dyn_cast<Constant>(Op0))
2766 if (LHS->isNullValue())
2767 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2768
2769 if (isa<UndefValue>(Op0)) // undef % X -> 0
2770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2771 if (isa<UndefValue>(Op1))
2772 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2773
2774 // Handle cases involving: rem X, (select Cond, Y, Z)
2775 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2776 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2777 // the same basic block, then we replace the select with Y, and the
2778 // condition of the select with false (if the cond value is in the same
2779 // BB). If the select has uses other than the div, this allows them to be
2780 // simplified also.
2781 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2782 if (ST->isNullValue()) {
2783 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2784 if (CondI && CondI->getParent() == I.getParent())
2785 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2786 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2787 I.setOperand(1, SI->getOperand(2));
2788 else
2789 UpdateValueUsesWith(SI, SI->getOperand(2));
2790 return &I;
2791 }
2792 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2793 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2794 if (ST->isNullValue()) {
2795 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2796 if (CondI && CondI->getParent() == I.getParent())
2797 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2798 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2799 I.setOperand(1, SI->getOperand(1));
2800 else
2801 UpdateValueUsesWith(SI, SI->getOperand(1));
2802 return &I;
2803 }
2804 }
2805
2806 return 0;
2807}
2808
2809/// This function implements the transforms common to both integer remainder
2810/// instructions (urem and srem). It is called by the visitors to those integer
2811/// remainder instructions.
2812/// @brief Common integer remainder transforms
2813Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2815
2816 if (Instruction *common = commonRemTransforms(I))
2817 return common;
2818
2819 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2820 // X % 0 == undef, we don't need to preserve faults!
2821 if (RHS->equalsInt(0))
2822 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2823
2824 if (RHS->equalsInt(1)) // X % 1 == 0
2825 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2826
2827 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2828 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2829 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2830 return R;
2831 } else if (isa<PHINode>(Op0I)) {
2832 if (Instruction *NV = FoldOpIntoPhi(I))
2833 return NV;
2834 }
2835 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2836 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2838 }
2839 }
2840
2841 return 0;
2842}
2843
2844Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2846
2847 if (Instruction *common = commonIRemTransforms(I))
2848 return common;
2849
2850 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2851 // X urem C^2 -> X and C
2852 // Check to see if this is an unsigned remainder with an exact power of 2,
2853 // if so, convert to a bitwise and.
2854 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2855 if (C->getValue().isPowerOf2())
2856 return BinaryOperator::createAnd(Op0, SubOne(C));
2857 }
2858
2859 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2860 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2861 if (RHSI->getOpcode() == Instruction::Shl &&
2862 isa<ConstantInt>(RHSI->getOperand(0))) {
2863 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2864 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2865 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2866 "tmp"), I);
2867 return BinaryOperator::createAnd(Op0, Add);
2868 }
2869 }
2870 }
2871
2872 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2873 // where C1&C2 are powers of two.
2874 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2875 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2876 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2877 // STO == 0 and SFO == 0 handled above.
2878 if ((STO->getValue().isPowerOf2()) &&
2879 (SFO->getValue().isPowerOf2())) {
2880 Value *TrueAnd = InsertNewInstBefore(
2881 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2882 Value *FalseAnd = InsertNewInstBefore(
2883 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2884 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2885 }
2886 }
2887 }
2888
2889 return 0;
2890}
2891
2892Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2894
Dan Gohmandb3dd962007-11-05 23:16:33 +00002895 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896 if (Instruction *common = commonIRemTransforms(I))
2897 return common;
2898
2899 if (Value *RHSNeg = dyn_castNegVal(Op1))
2900 if (!isa<ConstantInt>(RHSNeg) ||
2901 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2902 // X % -Y -> X % Y
2903 AddUsesToWorkList(I);
2904 I.setOperand(1, RHSNeg);
2905 return &I;
2906 }
2907
Dan Gohmandb3dd962007-11-05 23:16:33 +00002908 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002910 if (I.getType()->isInteger()) {
2911 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2912 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2913 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2914 return BinaryOperator::createURem(Op0, Op1, I.getName());
2915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 }
2917
2918 return 0;
2919}
2920
2921Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2922 return commonRemTransforms(I);
2923}
2924
2925// isMaxValueMinusOne - return true if this is Max-1
2926static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2927 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2928 if (!isSigned)
2929 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2930 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2931}
2932
2933// isMinValuePlusOne - return true if this is Min+1
2934static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2935 if (!isSigned)
2936 return C->getValue() == 1; // unsigned
2937
2938 // Calculate 1111111111000000000000
2939 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2940 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2941}
2942
2943// isOneBitSet - Return true if there is exactly one bit set in the specified
2944// constant.
2945static bool isOneBitSet(const ConstantInt *CI) {
2946 return CI->getValue().isPowerOf2();
2947}
2948
2949// isHighOnes - Return true if the constant is of the form 1+0+.
2950// This is the same as lowones(~X).
2951static bool isHighOnes(const ConstantInt *CI) {
2952 return (~CI->getValue() + 1).isPowerOf2();
2953}
2954
2955/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2956/// are carefully arranged to allow folding of expressions such as:
2957///
2958/// (A < B) | (A > B) --> (A != B)
2959///
2960/// Note that this is only valid if the first and second predicates have the
2961/// same sign. Is illegal to do: (A u< B) | (A s> B)
2962///
2963/// Three bits are used to represent the condition, as follows:
2964/// 0 A > B
2965/// 1 A == B
2966/// 2 A < B
2967///
2968/// <=> Value Definition
2969/// 000 0 Always false
2970/// 001 1 A > B
2971/// 010 2 A == B
2972/// 011 3 A >= B
2973/// 100 4 A < B
2974/// 101 5 A != B
2975/// 110 6 A <= B
2976/// 111 7 Always true
2977///
2978static unsigned getICmpCode(const ICmpInst *ICI) {
2979 switch (ICI->getPredicate()) {
2980 // False -> 0
2981 case ICmpInst::ICMP_UGT: return 1; // 001
2982 case ICmpInst::ICMP_SGT: return 1; // 001
2983 case ICmpInst::ICMP_EQ: return 2; // 010
2984 case ICmpInst::ICMP_UGE: return 3; // 011
2985 case ICmpInst::ICMP_SGE: return 3; // 011
2986 case ICmpInst::ICMP_ULT: return 4; // 100
2987 case ICmpInst::ICMP_SLT: return 4; // 100
2988 case ICmpInst::ICMP_NE: return 5; // 101
2989 case ICmpInst::ICMP_ULE: return 6; // 110
2990 case ICmpInst::ICMP_SLE: return 6; // 110
2991 // True -> 7
2992 default:
2993 assert(0 && "Invalid ICmp predicate!");
2994 return 0;
2995 }
2996}
2997
2998/// getICmpValue - This is the complement of getICmpCode, which turns an
2999/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003000/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001/// of predicate to use in new icmp instructions.
3002static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3003 switch (code) {
3004 default: assert(0 && "Illegal ICmp code!");
3005 case 0: return ConstantInt::getFalse();
3006 case 1:
3007 if (sign)
3008 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3009 else
3010 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3011 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3012 case 3:
3013 if (sign)
3014 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3015 else
3016 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3017 case 4:
3018 if (sign)
3019 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3020 else
3021 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3022 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3023 case 6:
3024 if (sign)
3025 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3026 else
3027 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3028 case 7: return ConstantInt::getTrue();
3029 }
3030}
3031
3032static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3033 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3034 (ICmpInst::isSignedPredicate(p1) &&
3035 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3036 (ICmpInst::isSignedPredicate(p2) &&
3037 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3038}
3039
3040namespace {
3041// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3042struct FoldICmpLogical {
3043 InstCombiner &IC;
3044 Value *LHS, *RHS;
3045 ICmpInst::Predicate pred;
3046 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3047 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3048 pred(ICI->getPredicate()) {}
3049 bool shouldApply(Value *V) const {
3050 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3051 if (PredicatesFoldable(pred, ICI->getPredicate()))
3052 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3053 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3054 return false;
3055 }
3056 Instruction *apply(Instruction &Log) const {
3057 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3058 if (ICI->getOperand(0) != LHS) {
3059 assert(ICI->getOperand(1) == LHS);
3060 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3061 }
3062
3063 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3064 unsigned LHSCode = getICmpCode(ICI);
3065 unsigned RHSCode = getICmpCode(RHSICI);
3066 unsigned Code;
3067 switch (Log.getOpcode()) {
3068 case Instruction::And: Code = LHSCode & RHSCode; break;
3069 case Instruction::Or: Code = LHSCode | RHSCode; break;
3070 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3071 default: assert(0 && "Illegal logical opcode!"); return 0;
3072 }
3073
3074 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3075 ICmpInst::isSignedPredicate(ICI->getPredicate());
3076
3077 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3078 if (Instruction *I = dyn_cast<Instruction>(RV))
3079 return I;
3080 // Otherwise, it's a constant boolean value...
3081 return IC.ReplaceInstUsesWith(Log, RV);
3082 }
3083};
3084} // end anonymous namespace
3085
3086// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3087// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3088// guaranteed to be a binary operator.
3089Instruction *InstCombiner::OptAndOp(Instruction *Op,
3090 ConstantInt *OpRHS,
3091 ConstantInt *AndRHS,
3092 BinaryOperator &TheAnd) {
3093 Value *X = Op->getOperand(0);
3094 Constant *Together = 0;
3095 if (!Op->isShift())
3096 Together = And(AndRHS, OpRHS);
3097
3098 switch (Op->getOpcode()) {
3099 case Instruction::Xor:
3100 if (Op->hasOneUse()) {
3101 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3102 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3103 InsertNewInstBefore(And, TheAnd);
3104 And->takeName(Op);
3105 return BinaryOperator::createXor(And, Together);
3106 }
3107 break;
3108 case Instruction::Or:
3109 if (Together == AndRHS) // (X | C) & C --> C
3110 return ReplaceInstUsesWith(TheAnd, AndRHS);
3111
3112 if (Op->hasOneUse() && Together != OpRHS) {
3113 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3114 Instruction *Or = BinaryOperator::createOr(X, Together);
3115 InsertNewInstBefore(Or, TheAnd);
3116 Or->takeName(Op);
3117 return BinaryOperator::createAnd(Or, AndRHS);
3118 }
3119 break;
3120 case Instruction::Add:
3121 if (Op->hasOneUse()) {
3122 // Adding a one to a single bit bit-field should be turned into an XOR
3123 // of the bit. First thing to check is to see if this AND is with a
3124 // single bit constant.
3125 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3126
3127 // If there is only one bit set...
3128 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3129 // Ok, at this point, we know that we are masking the result of the
3130 // ADD down to exactly one bit. If the constant we are adding has
3131 // no bits set below this bit, then we can eliminate the ADD.
3132 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3133
3134 // Check to see if any bits below the one bit set in AndRHSV are set.
3135 if ((AddRHS & (AndRHSV-1)) == 0) {
3136 // If not, the only thing that can effect the output of the AND is
3137 // the bit specified by AndRHSV. If that bit is set, the effect of
3138 // the XOR is to toggle the bit. If it is clear, then the ADD has
3139 // no effect.
3140 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3141 TheAnd.setOperand(0, X);
3142 return &TheAnd;
3143 } else {
3144 // Pull the XOR out of the AND.
3145 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3146 InsertNewInstBefore(NewAnd, TheAnd);
3147 NewAnd->takeName(Op);
3148 return BinaryOperator::createXor(NewAnd, AndRHS);
3149 }
3150 }
3151 }
3152 }
3153 break;
3154
3155 case Instruction::Shl: {
3156 // We know that the AND will not produce any of the bits shifted in, so if
3157 // the anded constant includes them, clear them now!
3158 //
3159 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3160 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3161 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3162 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3163
3164 if (CI->getValue() == ShlMask) {
3165 // Masking out bits that the shift already masks
3166 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3167 } else if (CI != AndRHS) { // Reducing bits set in and.
3168 TheAnd.setOperand(1, CI);
3169 return &TheAnd;
3170 }
3171 break;
3172 }
3173 case Instruction::LShr:
3174 {
3175 // We know that the AND will not produce any of the bits shifted in, so if
3176 // the anded constant includes them, clear them now! This only applies to
3177 // unsigned shifts, because a signed shr may bring in set bits!
3178 //
3179 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3180 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3181 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3182 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3183
3184 if (CI->getValue() == ShrMask) {
3185 // Masking out bits that the shift already masks.
3186 return ReplaceInstUsesWith(TheAnd, Op);
3187 } else if (CI != AndRHS) {
3188 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3189 return &TheAnd;
3190 }
3191 break;
3192 }
3193 case Instruction::AShr:
3194 // Signed shr.
3195 // See if this is shifting in some sign extension, then masking it out
3196 // with an and.
3197 if (Op->hasOneUse()) {
3198 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3199 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3200 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3201 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3202 if (C == AndRHS) { // Masking out bits shifted in.
3203 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3204 // Make the argument unsigned.
3205 Value *ShVal = Op->getOperand(0);
3206 ShVal = InsertNewInstBefore(
3207 BinaryOperator::createLShr(ShVal, OpRHS,
3208 Op->getName()), TheAnd);
3209 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3210 }
3211 }
3212 break;
3213 }
3214 return 0;
3215}
3216
3217
3218/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3219/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3220/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3221/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3222/// insert new instructions.
3223Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3224 bool isSigned, bool Inside,
3225 Instruction &IB) {
3226 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3227 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3228 "Lo is not <= Hi in range emission code!");
3229
3230 if (Inside) {
3231 if (Lo == Hi) // Trivially false.
3232 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3233
3234 // V >= Min && V < Hi --> V < Hi
3235 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3236 ICmpInst::Predicate pred = (isSigned ?
3237 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3238 return new ICmpInst(pred, V, Hi);
3239 }
3240
3241 // Emit V-Lo <u Hi-Lo
3242 Constant *NegLo = ConstantExpr::getNeg(Lo);
3243 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3244 InsertNewInstBefore(Add, IB);
3245 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3246 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3247 }
3248
3249 if (Lo == Hi) // Trivially true.
3250 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3251
3252 // V < Min || V >= Hi -> V > Hi-1
3253 Hi = SubOne(cast<ConstantInt>(Hi));
3254 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3255 ICmpInst::Predicate pred = (isSigned ?
3256 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3257 return new ICmpInst(pred, V, Hi);
3258 }
3259
3260 // Emit V-Lo >u Hi-1-Lo
3261 // Note that Hi has already had one subtracted from it, above.
3262 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3263 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3264 InsertNewInstBefore(Add, IB);
3265 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3266 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3267}
3268
3269// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3270// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3271// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3272// not, since all 1s are not contiguous.
3273static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3274 const APInt& V = Val->getValue();
3275 uint32_t BitWidth = Val->getType()->getBitWidth();
3276 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3277
3278 // look for the first zero bit after the run of ones
3279 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3280 // look for the first non-zero bit
3281 ME = V.getActiveBits();
3282 return true;
3283}
3284
3285/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3286/// where isSub determines whether the operator is a sub. If we can fold one of
3287/// the following xforms:
3288///
3289/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3290/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3291/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3292///
3293/// return (A +/- B).
3294///
3295Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3296 ConstantInt *Mask, bool isSub,
3297 Instruction &I) {
3298 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3299 if (!LHSI || LHSI->getNumOperands() != 2 ||
3300 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3301
3302 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3303
3304 switch (LHSI->getOpcode()) {
3305 default: return 0;
3306 case Instruction::And:
3307 if (And(N, Mask) == Mask) {
3308 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3309 if ((Mask->getValue().countLeadingZeros() +
3310 Mask->getValue().countPopulation()) ==
3311 Mask->getValue().getBitWidth())
3312 break;
3313
3314 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3315 // part, we don't need any explicit masks to take them out of A. If that
3316 // is all N is, ignore it.
3317 uint32_t MB = 0, ME = 0;
3318 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3319 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3320 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3321 if (MaskedValueIsZero(RHS, Mask))
3322 break;
3323 }
3324 }
3325 return 0;
3326 case Instruction::Or:
3327 case Instruction::Xor:
3328 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3329 if ((Mask->getValue().countLeadingZeros() +
3330 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3331 && And(N, Mask)->isZero())
3332 break;
3333 return 0;
3334 }
3335
3336 Instruction *New;
3337 if (isSub)
3338 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3339 else
3340 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3341 return InsertNewInstBefore(New, I);
3342}
3343
3344Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3345 bool Changed = SimplifyCommutative(I);
3346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3347
3348 if (isa<UndefValue>(Op1)) // X & undef -> 0
3349 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3350
3351 // and X, X = X
3352 if (Op0 == Op1)
3353 return ReplaceInstUsesWith(I, Op1);
3354
3355 // See if we can simplify any instructions used by the instruction whose sole
3356 // purpose is to compute bits we don't care about.
3357 if (!isa<VectorType>(I.getType())) {
3358 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3359 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3360 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3361 KnownZero, KnownOne))
3362 return &I;
3363 } else {
3364 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3365 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3366 return ReplaceInstUsesWith(I, I.getOperand(0));
3367 } else if (isa<ConstantAggregateZero>(Op1)) {
3368 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3369 }
3370 }
3371
3372 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3373 const APInt& AndRHSMask = AndRHS->getValue();
3374 APInt NotAndRHS(~AndRHSMask);
3375
3376 // Optimize a variety of ((val OP C1) & C2) combinations...
3377 if (isa<BinaryOperator>(Op0)) {
3378 Instruction *Op0I = cast<Instruction>(Op0);
3379 Value *Op0LHS = Op0I->getOperand(0);
3380 Value *Op0RHS = Op0I->getOperand(1);
3381 switch (Op0I->getOpcode()) {
3382 case Instruction::Xor:
3383 case Instruction::Or:
3384 // If the mask is only needed on one incoming arm, push it up.
3385 if (Op0I->hasOneUse()) {
3386 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3387 // Not masking anything out for the LHS, move to RHS.
3388 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3389 Op0RHS->getName()+".masked");
3390 InsertNewInstBefore(NewRHS, I);
3391 return BinaryOperator::create(
3392 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3393 }
3394 if (!isa<Constant>(Op0RHS) &&
3395 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3396 // Not masking anything out for the RHS, move to LHS.
3397 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3398 Op0LHS->getName()+".masked");
3399 InsertNewInstBefore(NewLHS, I);
3400 return BinaryOperator::create(
3401 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3402 }
3403 }
3404
3405 break;
3406 case Instruction::Add:
3407 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3408 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3409 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3410 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3411 return BinaryOperator::createAnd(V, AndRHS);
3412 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3413 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3414 break;
3415
3416 case Instruction::Sub:
3417 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3418 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3419 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3420 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3421 return BinaryOperator::createAnd(V, AndRHS);
3422 break;
3423 }
3424
3425 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3426 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3427 return Res;
3428 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3429 // If this is an integer truncation or change from signed-to-unsigned, and
3430 // if the source is an and/or with immediate, transform it. This
3431 // frequently occurs for bitfield accesses.
3432 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3433 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3434 CastOp->getNumOperands() == 2)
3435 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3436 if (CastOp->getOpcode() == Instruction::And) {
3437 // Change: and (cast (and X, C1) to T), C2
3438 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3439 // This will fold the two constants together, which may allow
3440 // other simplifications.
3441 Instruction *NewCast = CastInst::createTruncOrBitCast(
3442 CastOp->getOperand(0), I.getType(),
3443 CastOp->getName()+".shrunk");
3444 NewCast = InsertNewInstBefore(NewCast, I);
3445 // trunc_or_bitcast(C1)&C2
3446 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3447 C3 = ConstantExpr::getAnd(C3, AndRHS);
3448 return BinaryOperator::createAnd(NewCast, C3);
3449 } else if (CastOp->getOpcode() == Instruction::Or) {
3450 // Change: and (cast (or X, C1) to T), C2
3451 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3452 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3453 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3454 return ReplaceInstUsesWith(I, AndRHS);
3455 }
3456 }
3457 }
3458
3459 // Try to fold constant and into select arguments.
3460 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3461 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3462 return R;
3463 if (isa<PHINode>(Op0))
3464 if (Instruction *NV = FoldOpIntoPhi(I))
3465 return NV;
3466 }
3467
3468 Value *Op0NotVal = dyn_castNotVal(Op0);
3469 Value *Op1NotVal = dyn_castNotVal(Op1);
3470
3471 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3472 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3473
3474 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3475 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3476 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3477 I.getName()+".demorgan");
3478 InsertNewInstBefore(Or, I);
3479 return BinaryOperator::createNot(Or);
3480 }
3481
3482 {
3483 Value *A = 0, *B = 0, *C = 0, *D = 0;
3484 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3485 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3486 return ReplaceInstUsesWith(I, Op1);
3487
3488 // (A|B) & ~(A&B) -> A^B
3489 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3490 if ((A == C && B == D) || (A == D && B == C))
3491 return BinaryOperator::createXor(A, B);
3492 }
3493 }
3494
3495 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3496 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3497 return ReplaceInstUsesWith(I, Op0);
3498
3499 // ~(A&B) & (A|B) -> A^B
3500 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3501 if ((A == C && B == D) || (A == D && B == C))
3502 return BinaryOperator::createXor(A, B);
3503 }
3504 }
3505
3506 if (Op0->hasOneUse() &&
3507 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3508 if (A == Op1) { // (A^B)&A -> A&(A^B)
3509 I.swapOperands(); // Simplify below
3510 std::swap(Op0, Op1);
3511 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3512 cast<BinaryOperator>(Op0)->swapOperands();
3513 I.swapOperands(); // Simplify below
3514 std::swap(Op0, Op1);
3515 }
3516 }
3517 if (Op1->hasOneUse() &&
3518 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3519 if (B == Op0) { // B&(A^B) -> B&(B^A)
3520 cast<BinaryOperator>(Op1)->swapOperands();
3521 std::swap(A, B);
3522 }
3523 if (A == Op0) { // A&(A^B) -> A & ~B
3524 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3525 InsertNewInstBefore(NotB, I);
3526 return BinaryOperator::createAnd(A, NotB);
3527 }
3528 }
3529 }
3530
3531 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3532 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3533 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3534 return R;
3535
3536 Value *LHSVal, *RHSVal;
3537 ConstantInt *LHSCst, *RHSCst;
3538 ICmpInst::Predicate LHSCC, RHSCC;
3539 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3540 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3541 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3542 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3543 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3544 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3545 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003546 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3547
3548 // Don't try to fold ICMP_SLT + ICMP_ULT.
3549 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3550 ICmpInst::isSignedPredicate(LHSCC) ==
3551 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003553 ICmpInst::Predicate GT;
3554 if (ICmpInst::isSignedPredicate(LHSCC) ||
3555 (ICmpInst::isEquality(LHSCC) &&
3556 ICmpInst::isSignedPredicate(RHSCC)))
3557 GT = ICmpInst::ICMP_SGT;
3558 else
3559 GT = ICmpInst::ICMP_UGT;
3560
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003561 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3562 ICmpInst *LHS = cast<ICmpInst>(Op0);
3563 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3564 std::swap(LHS, RHS);
3565 std::swap(LHSCst, RHSCst);
3566 std::swap(LHSCC, RHSCC);
3567 }
3568
3569 // At this point, we know we have have two icmp instructions
3570 // comparing a value against two constants and and'ing the result
3571 // together. Because of the above check, we know that we only have
3572 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3573 // (from the FoldICmpLogical check above), that the two constants
3574 // are not equal and that the larger constant is on the RHS
3575 assert(LHSCst != RHSCst && "Compares not folded above?");
3576
3577 switch (LHSCC) {
3578 default: assert(0 && "Unknown integer condition code!");
3579 case ICmpInst::ICMP_EQ:
3580 switch (RHSCC) {
3581 default: assert(0 && "Unknown integer condition code!");
3582 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3583 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3584 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3585 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3586 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3587 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3588 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3589 return ReplaceInstUsesWith(I, LHS);
3590 }
3591 case ICmpInst::ICMP_NE:
3592 switch (RHSCC) {
3593 default: assert(0 && "Unknown integer condition code!");
3594 case ICmpInst::ICMP_ULT:
3595 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3596 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3597 break; // (X != 13 & X u< 15) -> no change
3598 case ICmpInst::ICMP_SLT:
3599 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3600 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3601 break; // (X != 13 & X s< 15) -> no change
3602 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3603 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3604 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3605 return ReplaceInstUsesWith(I, RHS);
3606 case ICmpInst::ICMP_NE:
3607 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3608 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3609 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3610 LHSVal->getName()+".off");
3611 InsertNewInstBefore(Add, I);
3612 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3613 ConstantInt::get(Add->getType(), 1));
3614 }
3615 break; // (X != 13 & X != 15) -> no change
3616 }
3617 break;
3618 case ICmpInst::ICMP_ULT:
3619 switch (RHSCC) {
3620 default: assert(0 && "Unknown integer condition code!");
3621 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3622 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3623 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3624 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3625 break;
3626 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3627 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3628 return ReplaceInstUsesWith(I, LHS);
3629 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3630 break;
3631 }
3632 break;
3633 case ICmpInst::ICMP_SLT:
3634 switch (RHSCC) {
3635 default: assert(0 && "Unknown integer condition code!");
3636 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3637 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3638 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3639 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3640 break;
3641 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3642 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3643 return ReplaceInstUsesWith(I, LHS);
3644 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3645 break;
3646 }
3647 break;
3648 case ICmpInst::ICMP_UGT:
3649 switch (RHSCC) {
3650 default: assert(0 && "Unknown integer condition code!");
3651 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3652 return ReplaceInstUsesWith(I, LHS);
3653 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3654 return ReplaceInstUsesWith(I, RHS);
3655 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3656 break;
3657 case ICmpInst::ICMP_NE:
3658 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3659 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3660 break; // (X u> 13 & X != 15) -> no change
3661 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3662 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3663 true, I);
3664 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3665 break;
3666 }
3667 break;
3668 case ICmpInst::ICMP_SGT:
3669 switch (RHSCC) {
3670 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003671 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003672 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3673 return ReplaceInstUsesWith(I, RHS);
3674 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3675 break;
3676 case ICmpInst::ICMP_NE:
3677 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3678 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3679 break; // (X s> 13 & X != 15) -> no change
3680 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3681 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3682 true, I);
3683 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3684 break;
3685 }
3686 break;
3687 }
3688 }
3689 }
3690
3691 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3693 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3694 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3695 const Type *SrcTy = Op0C->getOperand(0)->getType();
3696 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3697 // Only do this if the casts both really cause code to be generated.
3698 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3699 I.getType(), TD) &&
3700 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3701 I.getType(), TD)) {
3702 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3703 Op1C->getOperand(0),
3704 I.getName());
3705 InsertNewInstBefore(NewOp, I);
3706 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3707 }
3708 }
3709
3710 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3711 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3712 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3713 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3714 SI0->getOperand(1) == SI1->getOperand(1) &&
3715 (SI0->hasOneUse() || SI1->hasOneUse())) {
3716 Instruction *NewOp =
3717 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3718 SI1->getOperand(0),
3719 SI0->getName()), I);
3720 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3721 SI1->getOperand(1));
3722 }
3723 }
3724
Chris Lattner91882432007-10-24 05:38:08 +00003725 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3726 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3727 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3728 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3729 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3730 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3731 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3732 // If either of the constants are nans, then the whole thing returns
3733 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003734 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003735 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3736 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3737 RHS->getOperand(0));
3738 }
3739 }
3740 }
3741
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 return Changed ? &I : 0;
3743}
3744
3745/// CollectBSwapParts - Look to see if the specified value defines a single byte
3746/// in the result. If it does, and if the specified byte hasn't been filled in
3747/// yet, fill it in and return false.
3748static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3749 Instruction *I = dyn_cast<Instruction>(V);
3750 if (I == 0) return true;
3751
3752 // If this is an or instruction, it is an inner node of the bswap.
3753 if (I->getOpcode() == Instruction::Or)
3754 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3755 CollectBSwapParts(I->getOperand(1), ByteValues);
3756
3757 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3758 // If this is a shift by a constant int, and it is "24", then its operand
3759 // defines a byte. We only handle unsigned types here.
3760 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3761 // Not shifting the entire input by N-1 bytes?
3762 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3763 8*(ByteValues.size()-1))
3764 return true;
3765
3766 unsigned DestNo;
3767 if (I->getOpcode() == Instruction::Shl) {
3768 // X << 24 defines the top byte with the lowest of the input bytes.
3769 DestNo = ByteValues.size()-1;
3770 } else {
3771 // X >>u 24 defines the low byte with the highest of the input bytes.
3772 DestNo = 0;
3773 }
3774
3775 // If the destination byte value is already defined, the values are or'd
3776 // together, which isn't a bswap (unless it's an or of the same bits).
3777 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3778 return true;
3779 ByteValues[DestNo] = I->getOperand(0);
3780 return false;
3781 }
3782
3783 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3784 // don't have this.
3785 Value *Shift = 0, *ShiftLHS = 0;
3786 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3787 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3788 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3789 return true;
3790 Instruction *SI = cast<Instruction>(Shift);
3791
3792 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3793 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3794 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3795 return true;
3796
3797 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3798 unsigned DestByte;
3799 if (AndAmt->getValue().getActiveBits() > 64)
3800 return true;
3801 uint64_t AndAmtVal = AndAmt->getZExtValue();
3802 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3803 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3804 break;
3805 // Unknown mask for bswap.
3806 if (DestByte == ByteValues.size()) return true;
3807
3808 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3809 unsigned SrcByte;
3810 if (SI->getOpcode() == Instruction::Shl)
3811 SrcByte = DestByte - ShiftBytes;
3812 else
3813 SrcByte = DestByte + ShiftBytes;
3814
3815 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3816 if (SrcByte != ByteValues.size()-DestByte-1)
3817 return true;
3818
3819 // If the destination byte value is already defined, the values are or'd
3820 // together, which isn't a bswap (unless it's an or of the same bits).
3821 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3822 return true;
3823 ByteValues[DestByte] = SI->getOperand(0);
3824 return false;
3825}
3826
3827/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3828/// If so, insert the new bswap intrinsic and return it.
3829Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3830 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3831 if (!ITy || ITy->getBitWidth() % 16)
3832 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3833
3834 /// ByteValues - For each byte of the result, we keep track of which value
3835 /// defines each byte.
3836 SmallVector<Value*, 8> ByteValues;
3837 ByteValues.resize(ITy->getBitWidth()/8);
3838
3839 // Try to find all the pieces corresponding to the bswap.
3840 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3841 CollectBSwapParts(I.getOperand(1), ByteValues))
3842 return 0;
3843
3844 // Check to see if all of the bytes come from the same value.
3845 Value *V = ByteValues[0];
3846 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3847
3848 // Check to make sure that all of the bytes come from the same value.
3849 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3850 if (ByteValues[i] != V)
3851 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003852 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003854 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003855 return new CallInst(F, V);
3856}
3857
3858
3859Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3860 bool Changed = SimplifyCommutative(I);
3861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3862
3863 if (isa<UndefValue>(Op1)) // X | undef -> -1
3864 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3865
3866 // or X, X = X
3867 if (Op0 == Op1)
3868 return ReplaceInstUsesWith(I, Op0);
3869
3870 // See if we can simplify any instructions used by the instruction whose sole
3871 // purpose is to compute bits we don't care about.
3872 if (!isa<VectorType>(I.getType())) {
3873 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3874 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3875 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3876 KnownZero, KnownOne))
3877 return &I;
3878 } else if (isa<ConstantAggregateZero>(Op1)) {
3879 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3880 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3881 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3882 return ReplaceInstUsesWith(I, I.getOperand(1));
3883 }
3884
3885
3886
3887 // or X, -1 == -1
3888 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3889 ConstantInt *C1 = 0; Value *X = 0;
3890 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3891 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3892 Instruction *Or = BinaryOperator::createOr(X, RHS);
3893 InsertNewInstBefore(Or, I);
3894 Or->takeName(Op0);
3895 return BinaryOperator::createAnd(Or,
3896 ConstantInt::get(RHS->getValue() | C1->getValue()));
3897 }
3898
3899 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3900 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3901 Instruction *Or = BinaryOperator::createOr(X, RHS);
3902 InsertNewInstBefore(Or, I);
3903 Or->takeName(Op0);
3904 return BinaryOperator::createXor(Or,
3905 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3906 }
3907
3908 // Try to fold constant and into select arguments.
3909 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3910 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3911 return R;
3912 if (isa<PHINode>(Op0))
3913 if (Instruction *NV = FoldOpIntoPhi(I))
3914 return NV;
3915 }
3916
3917 Value *A = 0, *B = 0;
3918 ConstantInt *C1 = 0, *C2 = 0;
3919
3920 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3921 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3922 return ReplaceInstUsesWith(I, Op1);
3923 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3924 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3925 return ReplaceInstUsesWith(I, Op0);
3926
3927 // (A | B) | C and A | (B | C) -> bswap if possible.
3928 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3929 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3930 match(Op1, m_Or(m_Value(), m_Value())) ||
3931 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3932 match(Op1, m_Shift(m_Value(), m_Value())))) {
3933 if (Instruction *BSwap = MatchBSwap(I))
3934 return BSwap;
3935 }
3936
3937 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3938 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3939 MaskedValueIsZero(Op1, C1->getValue())) {
3940 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3941 InsertNewInstBefore(NOr, I);
3942 NOr->takeName(Op0);
3943 return BinaryOperator::createXor(NOr, C1);
3944 }
3945
3946 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3947 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3948 MaskedValueIsZero(Op0, C1->getValue())) {
3949 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3950 InsertNewInstBefore(NOr, I);
3951 NOr->takeName(Op0);
3952 return BinaryOperator::createXor(NOr, C1);
3953 }
3954
3955 // (A & C)|(B & D)
3956 Value *C = 0, *D = 0;
3957 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3958 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3959 Value *V1 = 0, *V2 = 0, *V3 = 0;
3960 C1 = dyn_cast<ConstantInt>(C);
3961 C2 = dyn_cast<ConstantInt>(D);
3962 if (C1 && C2) { // (A & C1)|(B & C2)
3963 // If we have: ((V + N) & C1) | (V & C2)
3964 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3965 // replace with V+N.
3966 if (C1->getValue() == ~C2->getValue()) {
3967 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3968 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3969 // Add commutes, try both ways.
3970 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3971 return ReplaceInstUsesWith(I, A);
3972 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3973 return ReplaceInstUsesWith(I, A);
3974 }
3975 // Or commutes, try both ways.
3976 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3977 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3978 // Add commutes, try both ways.
3979 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3980 return ReplaceInstUsesWith(I, B);
3981 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3982 return ReplaceInstUsesWith(I, B);
3983 }
3984 }
3985 V1 = 0; V2 = 0; V3 = 0;
3986 }
3987
3988 // Check to see if we have any common things being and'ed. If so, find the
3989 // terms for V1 & (V2|V3).
3990 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3991 if (A == B) // (A & C)|(A & D) == A & (C|D)
3992 V1 = A, V2 = C, V3 = D;
3993 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3994 V1 = A, V2 = B, V3 = C;
3995 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3996 V1 = C, V2 = A, V3 = D;
3997 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3998 V1 = C, V2 = A, V3 = B;
3999
4000 if (V1) {
4001 Value *Or =
4002 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4003 return BinaryOperator::createAnd(V1, Or);
4004 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004005 }
4006 }
4007
4008 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4009 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4010 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4011 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4012 SI0->getOperand(1) == SI1->getOperand(1) &&
4013 (SI0->hasOneUse() || SI1->hasOneUse())) {
4014 Instruction *NewOp =
4015 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4016 SI1->getOperand(0),
4017 SI0->getName()), I);
4018 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4019 SI1->getOperand(1));
4020 }
4021 }
4022
4023 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4024 if (A == Op1) // ~A | A == -1
4025 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4026 } else {
4027 A = 0;
4028 }
4029 // Note, A is still live here!
4030 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4031 if (Op0 == B)
4032 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4033
4034 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4035 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4036 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4037 I.getName()+".demorgan"), I);
4038 return BinaryOperator::createNot(And);
4039 }
4040 }
4041
4042 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4043 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4044 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4045 return R;
4046
4047 Value *LHSVal, *RHSVal;
4048 ConstantInt *LHSCst, *RHSCst;
4049 ICmpInst::Predicate LHSCC, RHSCC;
4050 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4051 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4052 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4053 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4054 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4055 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4056 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4057 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4058 // We can't fold (ugt x, C) | (sgt x, C2).
4059 PredicatesFoldable(LHSCC, RHSCC)) {
4060 // Ensure that the larger constant is on the RHS.
4061 ICmpInst *LHS = cast<ICmpInst>(Op0);
4062 bool NeedsSwap;
4063 if (ICmpInst::isSignedPredicate(LHSCC))
4064 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4065 else
4066 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4067
4068 if (NeedsSwap) {
4069 std::swap(LHS, RHS);
4070 std::swap(LHSCst, RHSCst);
4071 std::swap(LHSCC, RHSCC);
4072 }
4073
4074 // At this point, we know we have have two icmp instructions
4075 // comparing a value against two constants and or'ing the result
4076 // together. Because of the above check, we know that we only have
4077 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4078 // FoldICmpLogical check above), that the two constants are not
4079 // equal.
4080 assert(LHSCst != RHSCst && "Compares not folded above?");
4081
4082 switch (LHSCC) {
4083 default: assert(0 && "Unknown integer condition code!");
4084 case ICmpInst::ICMP_EQ:
4085 switch (RHSCC) {
4086 default: assert(0 && "Unknown integer condition code!");
4087 case ICmpInst::ICMP_EQ:
4088 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4089 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4090 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4091 LHSVal->getName()+".off");
4092 InsertNewInstBefore(Add, I);
4093 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4094 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4095 }
4096 break; // (X == 13 | X == 15) -> no change
4097 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4098 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4099 break;
4100 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4101 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4102 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4103 return ReplaceInstUsesWith(I, RHS);
4104 }
4105 break;
4106 case ICmpInst::ICMP_NE:
4107 switch (RHSCC) {
4108 default: assert(0 && "Unknown integer condition code!");
4109 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4110 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4111 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4112 return ReplaceInstUsesWith(I, LHS);
4113 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4114 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4115 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4116 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4117 }
4118 break;
4119 case ICmpInst::ICMP_ULT:
4120 switch (RHSCC) {
4121 default: assert(0 && "Unknown integer condition code!");
4122 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4123 break;
4124 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004125 // If RHSCst is [us]MAXINT, it is always false. Not handling
4126 // this can cause overflow.
4127 if (RHSCst->isMaxValue(false))
4128 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004129 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4130 false, I);
4131 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4132 break;
4133 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4134 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4135 return ReplaceInstUsesWith(I, RHS);
4136 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4137 break;
4138 }
4139 break;
4140 case ICmpInst::ICMP_SLT:
4141 switch (RHSCC) {
4142 default: assert(0 && "Unknown integer condition code!");
4143 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4144 break;
4145 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004146 // If RHSCst is [us]MAXINT, it is always false. Not handling
4147 // this can cause overflow.
4148 if (RHSCst->isMaxValue(true))
4149 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004150 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4151 false, I);
4152 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4153 break;
4154 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4155 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4156 return ReplaceInstUsesWith(I, RHS);
4157 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4158 break;
4159 }
4160 break;
4161 case ICmpInst::ICMP_UGT:
4162 switch (RHSCC) {
4163 default: assert(0 && "Unknown integer condition code!");
4164 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4165 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4166 return ReplaceInstUsesWith(I, LHS);
4167 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4168 break;
4169 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4170 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4171 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4172 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4173 break;
4174 }
4175 break;
4176 case ICmpInst::ICMP_SGT:
4177 switch (RHSCC) {
4178 default: assert(0 && "Unknown integer condition code!");
4179 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4180 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4181 return ReplaceInstUsesWith(I, LHS);
4182 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4183 break;
4184 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4185 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4186 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4187 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4188 break;
4189 }
4190 break;
4191 }
4192 }
4193 }
4194
4195 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004196 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004197 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4198 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4199 const Type *SrcTy = Op0C->getOperand(0)->getType();
4200 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4201 // Only do this if the casts both really cause code to be generated.
4202 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4203 I.getType(), TD) &&
4204 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4205 I.getType(), TD)) {
4206 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4207 Op1C->getOperand(0),
4208 I.getName());
4209 InsertNewInstBefore(NewOp, I);
4210 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4211 }
4212 }
Chris Lattner91882432007-10-24 05:38:08 +00004213 }
4214
4215
4216 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4217 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4218 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4219 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4220 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4221 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4222 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4223 // If either of the constants are nans, then the whole thing returns
4224 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004225 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004226 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4227
4228 // Otherwise, no need to compare the two constants, compare the
4229 // rest.
4230 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4231 RHS->getOperand(0));
4232 }
4233 }
4234 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235
4236 return Changed ? &I : 0;
4237}
4238
4239// XorSelf - Implements: X ^ X --> 0
4240struct XorSelf {
4241 Value *RHS;
4242 XorSelf(Value *rhs) : RHS(rhs) {}
4243 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4244 Instruction *apply(BinaryOperator &Xor) const {
4245 return &Xor;
4246 }
4247};
4248
4249
4250Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4251 bool Changed = SimplifyCommutative(I);
4252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4253
4254 if (isa<UndefValue>(Op1))
4255 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4256
4257 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4258 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004259 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4261 }
4262
4263 // See if we can simplify any instructions used by the instruction whose sole
4264 // purpose is to compute bits we don't care about.
4265 if (!isa<VectorType>(I.getType())) {
4266 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4267 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4268 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4269 KnownZero, KnownOne))
4270 return &I;
4271 } else if (isa<ConstantAggregateZero>(Op1)) {
4272 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4273 }
4274
4275 // Is this a ~ operation?
4276 if (Value *NotOp = dyn_castNotVal(&I)) {
4277 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4278 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4279 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4280 if (Op0I->getOpcode() == Instruction::And ||
4281 Op0I->getOpcode() == Instruction::Or) {
4282 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4283 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4284 Instruction *NotY =
4285 BinaryOperator::createNot(Op0I->getOperand(1),
4286 Op0I->getOperand(1)->getName()+".not");
4287 InsertNewInstBefore(NotY, I);
4288 if (Op0I->getOpcode() == Instruction::And)
4289 return BinaryOperator::createOr(Op0NotVal, NotY);
4290 else
4291 return BinaryOperator::createAnd(Op0NotVal, NotY);
4292 }
4293 }
4294 }
4295 }
4296
4297
4298 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004299 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4300 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4301 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004302 return new ICmpInst(ICI->getInversePredicate(),
4303 ICI->getOperand(0), ICI->getOperand(1));
4304
Nick Lewycky1405e922007-08-06 20:04:16 +00004305 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4306 return new FCmpInst(FCI->getInversePredicate(),
4307 FCI->getOperand(0), FCI->getOperand(1));
4308 }
4309
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4311 // ~(c-X) == X-c-1 == X+(-c-1)
4312 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4313 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4314 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4315 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4316 ConstantInt::get(I.getType(), 1));
4317 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4318 }
4319
4320 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4321 if (Op0I->getOpcode() == Instruction::Add) {
4322 // ~(X-c) --> (-c-1)-X
4323 if (RHS->isAllOnesValue()) {
4324 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4325 return BinaryOperator::createSub(
4326 ConstantExpr::getSub(NegOp0CI,
4327 ConstantInt::get(I.getType(), 1)),
4328 Op0I->getOperand(0));
4329 } else if (RHS->getValue().isSignBit()) {
4330 // (X + C) ^ signbit -> (X + C + signbit)
4331 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4332 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4333
4334 }
4335 } else if (Op0I->getOpcode() == Instruction::Or) {
4336 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4337 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4338 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4339 // Anything in both C1 and C2 is known to be zero, remove it from
4340 // NewRHS.
4341 Constant *CommonBits = And(Op0CI, RHS);
4342 NewRHS = ConstantExpr::getAnd(NewRHS,
4343 ConstantExpr::getNot(CommonBits));
4344 AddToWorkList(Op0I);
4345 I.setOperand(0, Op0I->getOperand(0));
4346 I.setOperand(1, NewRHS);
4347 return &I;
4348 }
4349 }
4350 }
4351
4352 // Try to fold constant and into select arguments.
4353 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4354 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4355 return R;
4356 if (isa<PHINode>(Op0))
4357 if (Instruction *NV = FoldOpIntoPhi(I))
4358 return NV;
4359 }
4360
4361 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4362 if (X == Op1)
4363 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4364
4365 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4366 if (X == Op0)
4367 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4368
4369
4370 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4371 if (Op1I) {
4372 Value *A, *B;
4373 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4374 if (A == Op0) { // B^(B|A) == (A|B)^B
4375 Op1I->swapOperands();
4376 I.swapOperands();
4377 std::swap(Op0, Op1);
4378 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4379 I.swapOperands(); // Simplified below.
4380 std::swap(Op0, Op1);
4381 }
4382 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4383 if (Op0 == A) // A^(A^B) == B
4384 return ReplaceInstUsesWith(I, B);
4385 else if (Op0 == B) // A^(B^A) == B
4386 return ReplaceInstUsesWith(I, A);
4387 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4388 if (A == Op0) { // A^(A&B) -> A^(B&A)
4389 Op1I->swapOperands();
4390 std::swap(A, B);
4391 }
4392 if (B == Op0) { // A^(B&A) -> (B&A)^A
4393 I.swapOperands(); // Simplified below.
4394 std::swap(Op0, Op1);
4395 }
4396 }
4397 }
4398
4399 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4400 if (Op0I) {
4401 Value *A, *B;
4402 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4403 if (A == Op1) // (B|A)^B == (A|B)^B
4404 std::swap(A, B);
4405 if (B == Op1) { // (A|B)^B == A & ~B
4406 Instruction *NotB =
4407 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4408 return BinaryOperator::createAnd(A, NotB);
4409 }
4410 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4411 if (Op1 == A) // (A^B)^A == B
4412 return ReplaceInstUsesWith(I, B);
4413 else if (Op1 == B) // (B^A)^A == B
4414 return ReplaceInstUsesWith(I, A);
4415 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4416 if (A == Op1) // (A&B)^A -> (B&A)^A
4417 std::swap(A, B);
4418 if (B == Op1 && // (B&A)^A == ~B & A
4419 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4420 Instruction *N =
4421 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4422 return BinaryOperator::createAnd(N, Op1);
4423 }
4424 }
4425 }
4426
4427 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4428 if (Op0I && Op1I && Op0I->isShift() &&
4429 Op0I->getOpcode() == Op1I->getOpcode() &&
4430 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4431 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4432 Instruction *NewOp =
4433 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4434 Op1I->getOperand(0),
4435 Op0I->getName()), I);
4436 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4437 Op1I->getOperand(1));
4438 }
4439
4440 if (Op0I && Op1I) {
4441 Value *A, *B, *C, *D;
4442 // (A & B)^(A | B) -> A ^ B
4443 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4444 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4445 if ((A == C && B == D) || (A == D && B == C))
4446 return BinaryOperator::createXor(A, B);
4447 }
4448 // (A | B)^(A & B) -> A ^ B
4449 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4450 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4451 if ((A == C && B == D) || (A == D && B == C))
4452 return BinaryOperator::createXor(A, B);
4453 }
4454
4455 // (A & B)^(C & D)
4456 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4457 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4458 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4459 // (X & Y)^(X & Y) -> (Y^Z) & X
4460 Value *X = 0, *Y = 0, *Z = 0;
4461 if (A == C)
4462 X = A, Y = B, Z = D;
4463 else if (A == D)
4464 X = A, Y = B, Z = C;
4465 else if (B == C)
4466 X = B, Y = A, Z = D;
4467 else if (B == D)
4468 X = B, Y = A, Z = C;
4469
4470 if (X) {
4471 Instruction *NewOp =
4472 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4473 return BinaryOperator::createAnd(NewOp, X);
4474 }
4475 }
4476 }
4477
4478 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4479 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4480 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4481 return R;
4482
4483 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004484 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004485 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4486 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4487 const Type *SrcTy = Op0C->getOperand(0)->getType();
4488 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4489 // Only do this if the casts both really cause code to be generated.
4490 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4491 I.getType(), TD) &&
4492 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4493 I.getType(), TD)) {
4494 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4495 Op1C->getOperand(0),
4496 I.getName());
4497 InsertNewInstBefore(NewOp, I);
4498 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4499 }
4500 }
Chris Lattner91882432007-10-24 05:38:08 +00004501 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502 return Changed ? &I : 0;
4503}
4504
4505/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4506/// overflowed for this type.
4507static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4508 ConstantInt *In2, bool IsSigned = false) {
4509 Result = cast<ConstantInt>(Add(In1, In2));
4510
4511 if (IsSigned)
4512 if (In2->getValue().isNegative())
4513 return Result->getValue().sgt(In1->getValue());
4514 else
4515 return Result->getValue().slt(In1->getValue());
4516 else
4517 return Result->getValue().ult(In1->getValue());
4518}
4519
4520/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4521/// code necessary to compute the offset from the base pointer (without adding
4522/// in the base pointer). Return the result as a signed integer of intptr size.
4523static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4524 TargetData &TD = IC.getTargetData();
4525 gep_type_iterator GTI = gep_type_begin(GEP);
4526 const Type *IntPtrTy = TD.getIntPtrType();
4527 Value *Result = Constant::getNullValue(IntPtrTy);
4528
4529 // Build a mask for high order bits.
4530 unsigned IntPtrWidth = TD.getPointerSize()*8;
4531 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4532
4533 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4534 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004535 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004536 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4537 if (OpC->isZero()) continue;
4538
4539 // Handle a struct index, which adds its field offset to the pointer.
4540 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4541 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4542
4543 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4544 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4545 else
4546 Result = IC.InsertNewInstBefore(
4547 BinaryOperator::createAdd(Result,
4548 ConstantInt::get(IntPtrTy, Size),
4549 GEP->getName()+".offs"), I);
4550 continue;
4551 }
4552
4553 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4554 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4555 Scale = ConstantExpr::getMul(OC, Scale);
4556 if (Constant *RC = dyn_cast<Constant>(Result))
4557 Result = ConstantExpr::getAdd(RC, Scale);
4558 else {
4559 // Emit an add instruction.
4560 Result = IC.InsertNewInstBefore(
4561 BinaryOperator::createAdd(Result, Scale,
4562 GEP->getName()+".offs"), I);
4563 }
4564 continue;
4565 }
4566 // Convert to correct type.
4567 if (Op->getType() != IntPtrTy) {
4568 if (Constant *OpC = dyn_cast<Constant>(Op))
4569 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4570 else
4571 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4572 Op->getName()+".c"), I);
4573 }
4574 if (Size != 1) {
4575 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4576 if (Constant *OpC = dyn_cast<Constant>(Op))
4577 Op = ConstantExpr::getMul(OpC, Scale);
4578 else // We'll let instcombine(mul) convert this to a shl if possible.
4579 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4580 GEP->getName()+".idx"), I);
4581 }
4582
4583 // Emit an add instruction.
4584 if (isa<Constant>(Op) && isa<Constant>(Result))
4585 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4586 cast<Constant>(Result));
4587 else
4588 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4589 GEP->getName()+".offs"), I);
4590 }
4591 return Result;
4592}
4593
4594/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4595/// else. At this point we know that the GEP is on the LHS of the comparison.
4596Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4597 ICmpInst::Predicate Cond,
4598 Instruction &I) {
4599 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4600
4601 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4602 if (isa<PointerType>(CI->getOperand(0)->getType()))
4603 RHS = CI->getOperand(0);
4604
4605 Value *PtrBase = GEPLHS->getOperand(0);
4606 if (PtrBase == RHS) {
4607 // As an optimization, we don't actually have to compute the actual value of
4608 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4609 // each index is zero or not.
4610 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4611 Instruction *InVal = 0;
4612 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4613 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4614 bool EmitIt = true;
4615 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4616 if (isa<UndefValue>(C)) // undef index -> undef.
4617 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4618 if (C->isNullValue())
4619 EmitIt = false;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004620 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004621 EmitIt = false; // This is indexing into a zero sized array?
4622 } else if (isa<ConstantInt>(C))
4623 return ReplaceInstUsesWith(I, // No comparison is needed here.
4624 ConstantInt::get(Type::Int1Ty,
4625 Cond == ICmpInst::ICMP_NE));
4626 }
4627
4628 if (EmitIt) {
4629 Instruction *Comp =
4630 new ICmpInst(Cond, GEPLHS->getOperand(i),
4631 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4632 if (InVal == 0)
4633 InVal = Comp;
4634 else {
4635 InVal = InsertNewInstBefore(InVal, I);
4636 InsertNewInstBefore(Comp, I);
4637 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4638 InVal = BinaryOperator::createOr(InVal, Comp);
4639 else // True if all are equal
4640 InVal = BinaryOperator::createAnd(InVal, Comp);
4641 }
4642 }
4643 }
4644
4645 if (InVal)
4646 return InVal;
4647 else
4648 // No comparison is needed here, all indexes = 0
4649 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4650 Cond == ICmpInst::ICMP_EQ));
4651 }
4652
4653 // Only lower this if the icmp is the only user of the GEP or if we expect
4654 // the result to fold to a constant!
4655 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4656 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4657 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4658 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4659 Constant::getNullValue(Offset->getType()));
4660 }
4661 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4662 // If the base pointers are different, but the indices are the same, just
4663 // compare the base pointer.
4664 if (PtrBase != GEPRHS->getOperand(0)) {
4665 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4666 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4667 GEPRHS->getOperand(0)->getType();
4668 if (IndicesTheSame)
4669 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4670 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4671 IndicesTheSame = false;
4672 break;
4673 }
4674
4675 // If all indices are the same, just compare the base pointers.
4676 if (IndicesTheSame)
4677 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4678 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4679
4680 // Otherwise, the base pointers are different and the indices are
4681 // different, bail out.
4682 return 0;
4683 }
4684
4685 // If one of the GEPs has all zero indices, recurse.
4686 bool AllZeros = true;
4687 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4688 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4689 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4690 AllZeros = false;
4691 break;
4692 }
4693 if (AllZeros)
4694 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4695 ICmpInst::getSwappedPredicate(Cond), I);
4696
4697 // If the other GEP has all zero indices, recurse.
4698 AllZeros = true;
4699 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4700 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4701 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4702 AllZeros = false;
4703 break;
4704 }
4705 if (AllZeros)
4706 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4707
4708 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4709 // If the GEPs only differ by one index, compare it.
4710 unsigned NumDifferences = 0; // Keep track of # differences.
4711 unsigned DiffOperand = 0; // The operand that differs.
4712 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4713 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4714 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4715 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4716 // Irreconcilable differences.
4717 NumDifferences = 2;
4718 break;
4719 } else {
4720 if (NumDifferences++) break;
4721 DiffOperand = i;
4722 }
4723 }
4724
4725 if (NumDifferences == 0) // SAME GEP?
4726 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004727 ConstantInt::get(Type::Int1Ty,
4728 isTrueWhenEqual(Cond)));
4729
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004730 else if (NumDifferences == 1) {
4731 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4732 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4733 // Make sure we do a signed comparison here.
4734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4735 }
4736 }
4737
4738 // Only lower this if the icmp is the only user of the GEP or if we expect
4739 // the result to fold to a constant!
4740 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4741 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4742 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4743 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4744 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4745 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4746 }
4747 }
4748 return 0;
4749}
4750
4751Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4752 bool Changed = SimplifyCompare(I);
4753 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4754
4755 // Fold trivial predicates.
4756 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4757 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4758 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4759 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4760
4761 // Simplify 'fcmp pred X, X'
4762 if (Op0 == Op1) {
4763 switch (I.getPredicate()) {
4764 default: assert(0 && "Unknown predicate!");
4765 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4766 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4767 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4768 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4769 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4770 case FCmpInst::FCMP_OLT: // True if ordered and less than
4771 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4772 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4773
4774 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4775 case FCmpInst::FCMP_ULT: // True if unordered or less than
4776 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4777 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4778 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4779 I.setPredicate(FCmpInst::FCMP_UNO);
4780 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4781 return &I;
4782
4783 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4784 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4785 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4786 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4787 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4788 I.setPredicate(FCmpInst::FCMP_ORD);
4789 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4790 return &I;
4791 }
4792 }
4793
4794 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4795 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4796
4797 // Handle fcmp with constant RHS
4798 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4799 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4800 switch (LHSI->getOpcode()) {
4801 case Instruction::PHI:
4802 if (Instruction *NV = FoldOpIntoPhi(I))
4803 return NV;
4804 break;
4805 case Instruction::Select:
4806 // If either operand of the select is a constant, we can fold the
4807 // comparison into the select arms, which will cause one to be
4808 // constant folded and the select turned into a bitwise or.
4809 Value *Op1 = 0, *Op2 = 0;
4810 if (LHSI->hasOneUse()) {
4811 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4812 // Fold the known value into the constant operand.
4813 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4814 // Insert a new FCmp of the other select operand.
4815 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4816 LHSI->getOperand(2), RHSC,
4817 I.getName()), I);
4818 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4819 // Fold the known value into the constant operand.
4820 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4821 // Insert a new FCmp of the other select operand.
4822 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4823 LHSI->getOperand(1), RHSC,
4824 I.getName()), I);
4825 }
4826 }
4827
4828 if (Op1)
4829 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4830 break;
4831 }
4832 }
4833
4834 return Changed ? &I : 0;
4835}
4836
4837Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4838 bool Changed = SimplifyCompare(I);
4839 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4840 const Type *Ty = Op0->getType();
4841
4842 // icmp X, X
4843 if (Op0 == Op1)
4844 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4845 isTrueWhenEqual(I)));
4846
4847 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4848 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00004849
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004850 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4851 // addresses never equal each other! We already know that Op0 != Op1.
4852 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4853 isa<ConstantPointerNull>(Op0)) &&
4854 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4855 isa<ConstantPointerNull>(Op1)))
4856 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4857 !isTrueWhenEqual(I)));
4858
4859 // icmp's with boolean values can always be turned into bitwise operations
4860 if (Ty == Type::Int1Ty) {
4861 switch (I.getPredicate()) {
4862 default: assert(0 && "Invalid icmp instruction!");
4863 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4864 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4865 InsertNewInstBefore(Xor, I);
4866 return BinaryOperator::createNot(Xor);
4867 }
4868 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4869 return BinaryOperator::createXor(Op0, Op1);
4870
4871 case ICmpInst::ICMP_UGT:
4872 case ICmpInst::ICMP_SGT:
4873 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4874 // FALL THROUGH
4875 case ICmpInst::ICMP_ULT:
4876 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4877 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4878 InsertNewInstBefore(Not, I);
4879 return BinaryOperator::createAnd(Not, Op1);
4880 }
4881 case ICmpInst::ICMP_UGE:
4882 case ICmpInst::ICMP_SGE:
4883 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4884 // FALL THROUGH
4885 case ICmpInst::ICMP_ULE:
4886 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4887 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4888 InsertNewInstBefore(Not, I);
4889 return BinaryOperator::createOr(Not, Op1);
4890 }
4891 }
4892 }
4893
4894 // See if we are doing a comparison between a constant and an instruction that
4895 // can be folded into the comparison.
4896 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00004897 Value *A, *B;
4898
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00004899 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4900 if (I.isEquality() && CI->isNullValue() &&
4901 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4902 // (icmp cond A B) if cond is equality
4903 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00004904 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00004905
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004906 switch (I.getPredicate()) {
4907 default: break;
4908 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4909 if (CI->isMinValue(false))
4910 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4911 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4912 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4913 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4914 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4915 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4916 if (CI->isMinValue(true))
4917 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4918 ConstantInt::getAllOnesValue(Op0->getType()));
4919
4920 break;
4921
4922 case ICmpInst::ICMP_SLT:
4923 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4924 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4925 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4926 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4927 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4928 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4929 break;
4930
4931 case ICmpInst::ICMP_UGT:
4932 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4933 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4934 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4935 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4936 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4938
4939 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4940 if (CI->isMaxValue(true))
4941 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4942 ConstantInt::getNullValue(Op0->getType()));
4943 break;
4944
4945 case ICmpInst::ICMP_SGT:
4946 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4947 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4948 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4949 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4950 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4951 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4952 break;
4953
4954 case ICmpInst::ICMP_ULE:
4955 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4956 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4957 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4958 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4959 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4961 break;
4962
4963 case ICmpInst::ICMP_SLE:
4964 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4965 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4966 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4967 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4968 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4969 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4970 break;
4971
4972 case ICmpInst::ICMP_UGE:
4973 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4974 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4975 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4976 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4977 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4978 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4979 break;
4980
4981 case ICmpInst::ICMP_SGE:
4982 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4983 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4984 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4985 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4986 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4987 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4988 break;
4989 }
4990
4991 // If we still have a icmp le or icmp ge instruction, turn it into the
4992 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4993 // already been handled above, this requires little checking.
4994 //
4995 switch (I.getPredicate()) {
4996 default: break;
4997 case ICmpInst::ICMP_ULE:
4998 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4999 case ICmpInst::ICMP_SLE:
5000 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5001 case ICmpInst::ICMP_UGE:
5002 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5003 case ICmpInst::ICMP_SGE:
5004 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5005 }
5006
5007 // See if we can fold the comparison based on bits known to be zero or one
5008 // in the input. If this comparison is a normal comparison, it demands all
5009 // bits, if it is a sign bit comparison, it only demands the sign bit.
5010
5011 bool UnusedBit;
5012 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5013
5014 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5015 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5016 if (SimplifyDemandedBits(Op0,
5017 isSignBit ? APInt::getSignBit(BitWidth)
5018 : APInt::getAllOnesValue(BitWidth),
5019 KnownZero, KnownOne, 0))
5020 return &I;
5021
5022 // Given the known and unknown bits, compute a range that the LHS could be
5023 // in.
5024 if ((KnownOne | KnownZero) != 0) {
5025 // Compute the Min, Max and RHS values based on the known bits. For the
5026 // EQ and NE we use unsigned values.
5027 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5028 const APInt& RHSVal = CI->getValue();
5029 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5030 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5031 Max);
5032 } else {
5033 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5034 Max);
5035 }
5036 switch (I.getPredicate()) { // LE/GE have been folded already.
5037 default: assert(0 && "Unknown icmp opcode!");
5038 case ICmpInst::ICMP_EQ:
5039 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5040 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5041 break;
5042 case ICmpInst::ICMP_NE:
5043 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5044 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5045 break;
5046 case ICmpInst::ICMP_ULT:
5047 if (Max.ult(RHSVal))
5048 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5049 if (Min.uge(RHSVal))
5050 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5051 break;
5052 case ICmpInst::ICMP_UGT:
5053 if (Min.ugt(RHSVal))
5054 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5055 if (Max.ule(RHSVal))
5056 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5057 break;
5058 case ICmpInst::ICMP_SLT:
5059 if (Max.slt(RHSVal))
5060 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5061 if (Min.sgt(RHSVal))
5062 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5063 break;
5064 case ICmpInst::ICMP_SGT:
5065 if (Min.sgt(RHSVal))
5066 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5067 if (Max.sle(RHSVal))
5068 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5069 break;
5070 }
5071 }
5072
5073 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5074 // instruction, see if that instruction also has constants so that the
5075 // instruction can be folded into the icmp
5076 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5077 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5078 return Res;
5079 }
5080
5081 // Handle icmp with constant (but not simple integer constant) RHS
5082 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5083 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5084 switch (LHSI->getOpcode()) {
5085 case Instruction::GetElementPtr:
5086 if (RHSC->isNullValue()) {
5087 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5088 bool isAllZeros = true;
5089 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5090 if (!isa<Constant>(LHSI->getOperand(i)) ||
5091 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5092 isAllZeros = false;
5093 break;
5094 }
5095 if (isAllZeros)
5096 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5097 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5098 }
5099 break;
5100
5101 case Instruction::PHI:
5102 if (Instruction *NV = FoldOpIntoPhi(I))
5103 return NV;
5104 break;
5105 case Instruction::Select: {
5106 // If either operand of the select is a constant, we can fold the
5107 // comparison into the select arms, which will cause one to be
5108 // constant folded and the select turned into a bitwise or.
5109 Value *Op1 = 0, *Op2 = 0;
5110 if (LHSI->hasOneUse()) {
5111 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5112 // Fold the known value into the constant operand.
5113 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5114 // Insert a new ICmp of the other select operand.
5115 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5116 LHSI->getOperand(2), RHSC,
5117 I.getName()), I);
5118 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5119 // Fold the known value into the constant operand.
5120 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5121 // Insert a new ICmp of the other select operand.
5122 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5123 LHSI->getOperand(1), RHSC,
5124 I.getName()), I);
5125 }
5126 }
5127
5128 if (Op1)
5129 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5130 break;
5131 }
5132 case Instruction::Malloc:
5133 // If we have (malloc != null), and if the malloc has a single use, we
5134 // can assume it is successful and remove the malloc.
5135 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5136 AddToWorkList(LHSI);
5137 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5138 !isTrueWhenEqual(I)));
5139 }
5140 break;
5141 }
5142 }
5143
5144 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5145 if (User *GEP = dyn_castGetElementPtr(Op0))
5146 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5147 return NI;
5148 if (User *GEP = dyn_castGetElementPtr(Op1))
5149 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5150 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5151 return NI;
5152
5153 // Test to see if the operands of the icmp are casted versions of other
5154 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5155 // now.
5156 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5157 if (isa<PointerType>(Op0->getType()) &&
5158 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5159 // We keep moving the cast from the left operand over to the right
5160 // operand, where it can often be eliminated completely.
5161 Op0 = CI->getOperand(0);
5162
5163 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5164 // so eliminate it as well.
5165 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5166 Op1 = CI2->getOperand(0);
5167
5168 // If Op1 is a constant, we can fold the cast into the constant.
5169 if (Op0->getType() != Op1->getType())
5170 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5171 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5172 } else {
5173 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005174 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175 }
5176 return new ICmpInst(I.getPredicate(), Op0, Op1);
5177 }
5178 }
5179
5180 if (isa<CastInst>(Op0)) {
5181 // Handle the special case of: icmp (cast bool to X), <cst>
5182 // This comes up when you have code like
5183 // int X = A < B;
5184 // if (X) ...
5185 // For generality, we handle any zero-extension of any operand comparison
5186 // with a constant or another cast from the same type.
5187 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5188 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5189 return R;
5190 }
5191
5192 if (I.isEquality()) {
5193 Value *A, *B, *C, *D;
5194 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5195 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5196 Value *OtherVal = A == Op1 ? B : A;
5197 return new ICmpInst(I.getPredicate(), OtherVal,
5198 Constant::getNullValue(A->getType()));
5199 }
5200
5201 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5202 // A^c1 == C^c2 --> A == C^(c1^c2)
5203 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5204 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5205 if (Op1->hasOneUse()) {
5206 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5207 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5208 return new ICmpInst(I.getPredicate(), A,
5209 InsertNewInstBefore(Xor, I));
5210 }
5211
5212 // A^B == A^D -> B == D
5213 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5214 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5215 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5216 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5217 }
5218 }
5219
5220 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5221 (A == Op0 || B == Op0)) {
5222 // A == (A^B) -> B == 0
5223 Value *OtherVal = A == Op0 ? B : A;
5224 return new ICmpInst(I.getPredicate(), OtherVal,
5225 Constant::getNullValue(A->getType()));
5226 }
5227 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5228 // (A-B) == A -> B == 0
5229 return new ICmpInst(I.getPredicate(), B,
5230 Constant::getNullValue(B->getType()));
5231 }
5232 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5233 // A == (A-B) -> B == 0
5234 return new ICmpInst(I.getPredicate(), B,
5235 Constant::getNullValue(B->getType()));
5236 }
5237
5238 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5239 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5240 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5241 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5242 Value *X = 0, *Y = 0, *Z = 0;
5243
5244 if (A == C) {
5245 X = B; Y = D; Z = A;
5246 } else if (A == D) {
5247 X = B; Y = C; Z = A;
5248 } else if (B == C) {
5249 X = A; Y = D; Z = B;
5250 } else if (B == D) {
5251 X = A; Y = C; Z = B;
5252 }
5253
5254 if (X) { // Build (X^Y) & Z
5255 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5256 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5257 I.setOperand(0, Op1);
5258 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5259 return &I;
5260 }
5261 }
5262 }
5263 return Changed ? &I : 0;
5264}
5265
5266
5267/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5268/// and CmpRHS are both known to be integer constants.
5269Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5270 ConstantInt *DivRHS) {
5271 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5272 const APInt &CmpRHSV = CmpRHS->getValue();
5273
5274 // FIXME: If the operand types don't match the type of the divide
5275 // then don't attempt this transform. The code below doesn't have the
5276 // logic to deal with a signed divide and an unsigned compare (and
5277 // vice versa). This is because (x /s C1) <s C2 produces different
5278 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5279 // (x /u C1) <u C2. Simply casting the operands and result won't
5280 // work. :( The if statement below tests that condition and bails
5281 // if it finds it.
5282 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5283 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5284 return 0;
5285 if (DivRHS->isZero())
5286 return 0; // The ProdOV computation fails on divide by zero.
5287
5288 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5289 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5290 // C2 (CI). By solving for X we can turn this into a range check
5291 // instead of computing a divide.
5292 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5293
5294 // Determine if the product overflows by seeing if the product is
5295 // not equal to the divide. Make sure we do the same kind of divide
5296 // as in the LHS instruction that we're folding.
5297 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5298 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5299
5300 // Get the ICmp opcode
5301 ICmpInst::Predicate Pred = ICI.getPredicate();
5302
5303 // Figure out the interval that is being checked. For example, a comparison
5304 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5305 // Compute this interval based on the constants involved and the signedness of
5306 // the compare/divide. This computes a half-open interval, keeping track of
5307 // whether either value in the interval overflows. After analysis each
5308 // overflow variable is set to 0 if it's corresponding bound variable is valid
5309 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5310 int LoOverflow = 0, HiOverflow = 0;
5311 ConstantInt *LoBound = 0, *HiBound = 0;
5312
5313
5314 if (!DivIsSigned) { // udiv
5315 // e.g. X/5 op 3 --> [15, 20)
5316 LoBound = Prod;
5317 HiOverflow = LoOverflow = ProdOV;
5318 if (!HiOverflow)
5319 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5320 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5321 if (CmpRHSV == 0) { // (X / pos) op 0
5322 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5323 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5324 HiBound = DivRHS;
5325 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
5326 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5327 HiOverflow = LoOverflow = ProdOV;
5328 if (!HiOverflow)
5329 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5330 } else { // (X / pos) op neg
5331 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5332 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5333 LoOverflow = AddWithOverflow(LoBound, Prod,
5334 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5335 HiBound = AddOne(Prod);
5336 HiOverflow = ProdOV ? -1 : 0;
5337 }
5338 } else { // Divisor is < 0.
5339 if (CmpRHSV == 0) { // (X / neg) op 0
5340 // e.g. X/-5 op 0 --> [-4, 5)
5341 LoBound = AddOne(DivRHS);
5342 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5343 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5344 HiOverflow = 1; // [INTMIN+1, overflow)
5345 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5346 }
5347 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
5348 // e.g. X/-5 op 3 --> [-19, -14)
5349 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5350 if (!LoOverflow)
5351 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5352 HiBound = AddOne(Prod);
5353 } else { // (X / neg) op neg
5354 // e.g. X/-5 op -3 --> [15, 20)
5355 LoBound = Prod;
5356 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5357 HiBound = Subtract(Prod, DivRHS);
5358 }
5359
5360 // Dividing by a negative swaps the condition. LT <-> GT
5361 Pred = ICmpInst::getSwappedPredicate(Pred);
5362 }
5363
5364 Value *X = DivI->getOperand(0);
5365 switch (Pred) {
5366 default: assert(0 && "Unhandled icmp opcode!");
5367 case ICmpInst::ICMP_EQ:
5368 if (LoOverflow && HiOverflow)
5369 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5370 else if (HiOverflow)
5371 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5372 ICmpInst::ICMP_UGE, X, LoBound);
5373 else if (LoOverflow)
5374 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5375 ICmpInst::ICMP_ULT, X, HiBound);
5376 else
5377 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5378 case ICmpInst::ICMP_NE:
5379 if (LoOverflow && HiOverflow)
5380 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5381 else if (HiOverflow)
5382 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5383 ICmpInst::ICMP_ULT, X, LoBound);
5384 else if (LoOverflow)
5385 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5386 ICmpInst::ICMP_UGE, X, HiBound);
5387 else
5388 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5389 case ICmpInst::ICMP_ULT:
5390 case ICmpInst::ICMP_SLT:
5391 if (LoOverflow == +1) // Low bound is greater than input range.
5392 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5393 if (LoOverflow == -1) // Low bound is less than input range.
5394 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5395 return new ICmpInst(Pred, X, LoBound);
5396 case ICmpInst::ICMP_UGT:
5397 case ICmpInst::ICMP_SGT:
5398 if (HiOverflow == +1) // High bound greater than input range.
5399 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5400 else if (HiOverflow == -1) // High bound less than input range.
5401 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5402 if (Pred == ICmpInst::ICMP_UGT)
5403 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5404 else
5405 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5406 }
5407}
5408
5409
5410/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5411///
5412Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5413 Instruction *LHSI,
5414 ConstantInt *RHS) {
5415 const APInt &RHSV = RHS->getValue();
5416
5417 switch (LHSI->getOpcode()) {
5418 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5419 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5420 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5421 // fold the xor.
5422 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5423 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5424 Value *CompareVal = LHSI->getOperand(0);
5425
5426 // If the sign bit of the XorCST is not set, there is no change to
5427 // the operation, just stop using the Xor.
5428 if (!XorCST->getValue().isNegative()) {
5429 ICI.setOperand(0, CompareVal);
5430 AddToWorkList(LHSI);
5431 return &ICI;
5432 }
5433
5434 // Was the old condition true if the operand is positive?
5435 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5436
5437 // If so, the new one isn't.
5438 isTrueIfPositive ^= true;
5439
5440 if (isTrueIfPositive)
5441 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5442 else
5443 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5444 }
5445 }
5446 break;
5447 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5448 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5449 LHSI->getOperand(0)->hasOneUse()) {
5450 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5451
5452 // If the LHS is an AND of a truncating cast, we can widen the
5453 // and/compare to be the input width without changing the value
5454 // produced, eliminating a cast.
5455 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5456 // We can do this transformation if either the AND constant does not
5457 // have its sign bit set or if it is an equality comparison.
5458 // Extending a relational comparison when we're checking the sign
5459 // bit would not work.
5460 if (Cast->hasOneUse() &&
5461 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5462 RHSV.isPositive())) {
5463 uint32_t BitWidth =
5464 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5465 APInt NewCST = AndCST->getValue();
5466 NewCST.zext(BitWidth);
5467 APInt NewCI = RHSV;
5468 NewCI.zext(BitWidth);
5469 Instruction *NewAnd =
5470 BinaryOperator::createAnd(Cast->getOperand(0),
5471 ConstantInt::get(NewCST),LHSI->getName());
5472 InsertNewInstBefore(NewAnd, ICI);
5473 return new ICmpInst(ICI.getPredicate(), NewAnd,
5474 ConstantInt::get(NewCI));
5475 }
5476 }
5477
5478 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5479 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5480 // happens a LOT in code produced by the C front-end, for bitfield
5481 // access.
5482 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5483 if (Shift && !Shift->isShift())
5484 Shift = 0;
5485
5486 ConstantInt *ShAmt;
5487 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5488 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5489 const Type *AndTy = AndCST->getType(); // Type of the and.
5490
5491 // We can fold this as long as we can't shift unknown bits
5492 // into the mask. This can only happen with signed shift
5493 // rights, as they sign-extend.
5494 if (ShAmt) {
5495 bool CanFold = Shift->isLogicalShift();
5496 if (!CanFold) {
5497 // To test for the bad case of the signed shr, see if any
5498 // of the bits shifted in could be tested after the mask.
5499 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5500 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5501
5502 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5503 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5504 AndCST->getValue()) == 0)
5505 CanFold = true;
5506 }
5507
5508 if (CanFold) {
5509 Constant *NewCst;
5510 if (Shift->getOpcode() == Instruction::Shl)
5511 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5512 else
5513 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5514
5515 // Check to see if we are shifting out any of the bits being
5516 // compared.
5517 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5518 // If we shifted bits out, the fold is not going to work out.
5519 // As a special case, check to see if this means that the
5520 // result is always true or false now.
5521 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5522 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5523 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5524 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5525 } else {
5526 ICI.setOperand(1, NewCst);
5527 Constant *NewAndCST;
5528 if (Shift->getOpcode() == Instruction::Shl)
5529 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5530 else
5531 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5532 LHSI->setOperand(1, NewAndCST);
5533 LHSI->setOperand(0, Shift->getOperand(0));
5534 AddToWorkList(Shift); // Shift is dead.
5535 AddUsesToWorkList(ICI);
5536 return &ICI;
5537 }
5538 }
5539 }
5540
5541 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5542 // preferable because it allows the C<<Y expression to be hoisted out
5543 // of a loop if Y is invariant and X is not.
5544 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5545 ICI.isEquality() && !Shift->isArithmeticShift() &&
5546 isa<Instruction>(Shift->getOperand(0))) {
5547 // Compute C << Y.
5548 Value *NS;
5549 if (Shift->getOpcode() == Instruction::LShr) {
5550 NS = BinaryOperator::createShl(AndCST,
5551 Shift->getOperand(1), "tmp");
5552 } else {
5553 // Insert a logical shift.
5554 NS = BinaryOperator::createLShr(AndCST,
5555 Shift->getOperand(1), "tmp");
5556 }
5557 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5558
5559 // Compute X & (C << Y).
5560 Instruction *NewAnd =
5561 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5562 InsertNewInstBefore(NewAnd, ICI);
5563
5564 ICI.setOperand(0, NewAnd);
5565 return &ICI;
5566 }
5567 }
5568 break;
5569
5570 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5571 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5572 if (!ShAmt) break;
5573
5574 uint32_t TypeBits = RHSV.getBitWidth();
5575
5576 // Check that the shift amount is in range. If not, don't perform
5577 // undefined shifts. When the shift is visited it will be
5578 // simplified.
5579 if (ShAmt->uge(TypeBits))
5580 break;
5581
5582 if (ICI.isEquality()) {
5583 // If we are comparing against bits always shifted out, the
5584 // comparison cannot succeed.
5585 Constant *Comp =
5586 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5587 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5588 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5589 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5590 return ReplaceInstUsesWith(ICI, Cst);
5591 }
5592
5593 if (LHSI->hasOneUse()) {
5594 // Otherwise strength reduce the shift into an and.
5595 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5596 Constant *Mask =
5597 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5598
5599 Instruction *AndI =
5600 BinaryOperator::createAnd(LHSI->getOperand(0),
5601 Mask, LHSI->getName()+".mask");
5602 Value *And = InsertNewInstBefore(AndI, ICI);
5603 return new ICmpInst(ICI.getPredicate(), And,
5604 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5605 }
5606 }
5607
5608 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5609 bool TrueIfSigned = false;
5610 if (LHSI->hasOneUse() &&
5611 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5612 // (X << 31) <s 0 --> (X&1) != 0
5613 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5614 (TypeBits-ShAmt->getZExtValue()-1));
5615 Instruction *AndI =
5616 BinaryOperator::createAnd(LHSI->getOperand(0),
5617 Mask, LHSI->getName()+".mask");
5618 Value *And = InsertNewInstBefore(AndI, ICI);
5619
5620 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5621 And, Constant::getNullValue(And->getType()));
5622 }
5623 break;
5624 }
5625
5626 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5627 case Instruction::AShr: {
5628 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5629 if (!ShAmt) break;
5630
5631 if (ICI.isEquality()) {
5632 // Check that the shift amount is in range. If not, don't perform
5633 // undefined shifts. When the shift is visited it will be
5634 // simplified.
5635 uint32_t TypeBits = RHSV.getBitWidth();
5636 if (ShAmt->uge(TypeBits))
5637 break;
5638 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5639
5640 // If we are comparing against bits always shifted out, the
5641 // comparison cannot succeed.
5642 APInt Comp = RHSV << ShAmtVal;
5643 if (LHSI->getOpcode() == Instruction::LShr)
5644 Comp = Comp.lshr(ShAmtVal);
5645 else
5646 Comp = Comp.ashr(ShAmtVal);
5647
5648 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5649 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5650 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5651 return ReplaceInstUsesWith(ICI, Cst);
5652 }
5653
5654 if (LHSI->hasOneUse() || RHSV == 0) {
5655 // Otherwise strength reduce the shift into an and.
5656 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5657 Constant *Mask = ConstantInt::get(Val);
5658
5659 Instruction *AndI =
5660 BinaryOperator::createAnd(LHSI->getOperand(0),
5661 Mask, LHSI->getName()+".mask");
5662 Value *And = InsertNewInstBefore(AndI, ICI);
5663 return new ICmpInst(ICI.getPredicate(), And,
5664 ConstantExpr::getShl(RHS, ShAmt));
5665 }
5666 }
5667 break;
5668 }
5669
5670 case Instruction::SDiv:
5671 case Instruction::UDiv:
5672 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5673 // Fold this div into the comparison, producing a range check.
5674 // Determine, based on the divide type, what the range is being
5675 // checked. If there is an overflow on the low or high side, remember
5676 // it, otherwise compute the range [low, hi) bounding the new value.
5677 // See: InsertRangeTest above for the kinds of replacements possible.
5678 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5679 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5680 DivRHS))
5681 return R;
5682 break;
5683 }
5684
5685 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5686 if (ICI.isEquality()) {
5687 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5688
5689 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5690 // the second operand is a constant, simplify a bit.
5691 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5692 switch (BO->getOpcode()) {
5693 case Instruction::SRem:
5694 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5695 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5696 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5697 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5698 Instruction *NewRem =
5699 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5700 BO->getName());
5701 InsertNewInstBefore(NewRem, ICI);
5702 return new ICmpInst(ICI.getPredicate(), NewRem,
5703 Constant::getNullValue(BO->getType()));
5704 }
5705 }
5706 break;
5707 case Instruction::Add:
5708 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5709 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5710 if (BO->hasOneUse())
5711 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5712 Subtract(RHS, BOp1C));
5713 } else if (RHSV == 0) {
5714 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5715 // efficiently invertible, or if the add has just this one use.
5716 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5717
5718 if (Value *NegVal = dyn_castNegVal(BOp1))
5719 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5720 else if (Value *NegVal = dyn_castNegVal(BOp0))
5721 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5722 else if (BO->hasOneUse()) {
5723 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5724 InsertNewInstBefore(Neg, ICI);
5725 Neg->takeName(BO);
5726 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5727 }
5728 }
5729 break;
5730 case Instruction::Xor:
5731 // For the xor case, we can xor two constants together, eliminating
5732 // the explicit xor.
5733 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5734 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5735 ConstantExpr::getXor(RHS, BOC));
5736
5737 // FALLTHROUGH
5738 case Instruction::Sub:
5739 // Replace (([sub|xor] A, B) != 0) with (A != B)
5740 if (RHSV == 0)
5741 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5742 BO->getOperand(1));
5743 break;
5744
5745 case Instruction::Or:
5746 // If bits are being or'd in that are not present in the constant we
5747 // are comparing against, then the comparison could never succeed!
5748 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5749 Constant *NotCI = ConstantExpr::getNot(RHS);
5750 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5751 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5752 isICMP_NE));
5753 }
5754 break;
5755
5756 case Instruction::And:
5757 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5758 // If bits are being compared against that are and'd out, then the
5759 // comparison can never succeed!
5760 if ((RHSV & ~BOC->getValue()) != 0)
5761 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5762 isICMP_NE));
5763
5764 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5765 if (RHS == BOC && RHSV.isPowerOf2())
5766 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5767 ICmpInst::ICMP_NE, LHSI,
5768 Constant::getNullValue(RHS->getType()));
5769
5770 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5771 if (isSignBit(BOC)) {
5772 Value *X = BO->getOperand(0);
5773 Constant *Zero = Constant::getNullValue(X->getType());
5774 ICmpInst::Predicate pred = isICMP_NE ?
5775 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5776 return new ICmpInst(pred, X, Zero);
5777 }
5778
5779 // ((X & ~7) == 0) --> X < 8
5780 if (RHSV == 0 && isHighOnes(BOC)) {
5781 Value *X = BO->getOperand(0);
5782 Constant *NegX = ConstantExpr::getNeg(BOC);
5783 ICmpInst::Predicate pred = isICMP_NE ?
5784 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5785 return new ICmpInst(pred, X, NegX);
5786 }
5787 }
5788 default: break;
5789 }
5790 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5791 // Handle icmp {eq|ne} <intrinsic>, intcst.
5792 if (II->getIntrinsicID() == Intrinsic::bswap) {
5793 AddToWorkList(II);
5794 ICI.setOperand(0, II->getOperand(1));
5795 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5796 return &ICI;
5797 }
5798 }
5799 } else { // Not a ICMP_EQ/ICMP_NE
5800 // If the LHS is a cast from an integral value of the same size,
5801 // then since we know the RHS is a constant, try to simlify.
5802 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5803 Value *CastOp = Cast->getOperand(0);
5804 const Type *SrcTy = CastOp->getType();
5805 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5806 if (SrcTy->isInteger() &&
5807 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5808 // If this is an unsigned comparison, try to make the comparison use
5809 // smaller constant values.
5810 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5811 // X u< 128 => X s> -1
5812 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5813 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5814 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5815 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5816 // X u> 127 => X s< 0
5817 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5818 Constant::getNullValue(SrcTy));
5819 }
5820 }
5821 }
5822 }
5823 return 0;
5824}
5825
5826/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5827/// We only handle extending casts so far.
5828///
5829Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5830 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5831 Value *LHSCIOp = LHSCI->getOperand(0);
5832 const Type *SrcTy = LHSCIOp->getType();
5833 const Type *DestTy = LHSCI->getType();
5834 Value *RHSCIOp;
5835
5836 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5837 // integer type is the same size as the pointer type.
5838 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5839 getTargetData().getPointerSizeInBits() ==
5840 cast<IntegerType>(DestTy)->getBitWidth()) {
5841 Value *RHSOp = 0;
5842 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5843 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5844 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5845 RHSOp = RHSC->getOperand(0);
5846 // If the pointer types don't match, insert a bitcast.
5847 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005848 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005849 }
5850
5851 if (RHSOp)
5852 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5853 }
5854
5855 // The code below only handles extension cast instructions, so far.
5856 // Enforce this.
5857 if (LHSCI->getOpcode() != Instruction::ZExt &&
5858 LHSCI->getOpcode() != Instruction::SExt)
5859 return 0;
5860
5861 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5862 bool isSignedCmp = ICI.isSignedPredicate();
5863
5864 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5865 // Not an extension from the same type?
5866 RHSCIOp = CI->getOperand(0);
5867 if (RHSCIOp->getType() != LHSCIOp->getType())
5868 return 0;
5869
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005870 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005871 // and the other is a zext), then we can't handle this.
5872 if (CI->getOpcode() != LHSCI->getOpcode())
5873 return 0;
5874
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005875 // Deal with equality cases early.
5876 if (ICI.isEquality())
5877 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5878
5879 // A signed comparison of sign extended values simplifies into a
5880 // signed comparison.
5881 if (isSignedCmp && isSignedExt)
5882 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5883
5884 // The other three cases all fold into an unsigned comparison.
5885 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005886 }
5887
5888 // If we aren't dealing with a constant on the RHS, exit early
5889 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5890 if (!CI)
5891 return 0;
5892
5893 // Compute the constant that would happen if we truncated to SrcTy then
5894 // reextended to DestTy.
5895 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5896 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5897
5898 // If the re-extended constant didn't change...
5899 if (Res2 == CI) {
5900 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5901 // For example, we might have:
5902 // %A = sext short %X to uint
5903 // %B = icmp ugt uint %A, 1330
5904 // It is incorrect to transform this into
5905 // %B = icmp ugt short %X, 1330
5906 // because %A may have negative value.
5907 //
5908 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5909 // OR operation is EQ/NE.
5910 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5911 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5912 else
5913 return 0;
5914 }
5915
5916 // The re-extended constant changed so the constant cannot be represented
5917 // in the shorter type. Consequently, we cannot emit a simple comparison.
5918
5919 // First, handle some easy cases. We know the result cannot be equal at this
5920 // point so handle the ICI.isEquality() cases
5921 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5922 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5923 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5924 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5925
5926 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5927 // should have been folded away previously and not enter in here.
5928 Value *Result;
5929 if (isSignedCmp) {
5930 // We're performing a signed comparison.
5931 if (cast<ConstantInt>(CI)->getValue().isNegative())
5932 Result = ConstantInt::getFalse(); // X < (small) --> false
5933 else
5934 Result = ConstantInt::getTrue(); // X < (large) --> true
5935 } else {
5936 // We're performing an unsigned comparison.
5937 if (isSignedExt) {
5938 // We're performing an unsigned comp with a sign extended value.
5939 // This is true if the input is >= 0. [aka >s -1]
5940 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5941 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5942 NegOne, ICI.getName()), ICI);
5943 } else {
5944 // Unsigned extend & unsigned compare -> always true.
5945 Result = ConstantInt::getTrue();
5946 }
5947 }
5948
5949 // Finally, return the value computed.
5950 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5951 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5952 return ReplaceInstUsesWith(ICI, Result);
5953 } else {
5954 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5955 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5956 "ICmp should be folded!");
5957 if (Constant *CI = dyn_cast<Constant>(Result))
5958 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5959 else
5960 return BinaryOperator::createNot(Result);
5961 }
5962}
5963
5964Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5965 return commonShiftTransforms(I);
5966}
5967
5968Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5969 return commonShiftTransforms(I);
5970}
5971
5972Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00005973 if (Instruction *R = commonShiftTransforms(I))
5974 return R;
5975
5976 Value *Op0 = I.getOperand(0);
5977
5978 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5979 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5980 if (CSI->isAllOnesValue())
5981 return ReplaceInstUsesWith(I, CSI);
5982
5983 // See if we can turn a signed shr into an unsigned shr.
5984 if (MaskedValueIsZero(Op0,
5985 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5986 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5987
5988 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005989}
5990
5991Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5992 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5994
5995 // shl X, 0 == X and shr X, 0 == X
5996 // shl 0, X == 0 and shr 0, X == 0
5997 if (Op1 == Constant::getNullValue(Op1->getType()) ||
5998 Op0 == Constant::getNullValue(Op0->getType()))
5999 return ReplaceInstUsesWith(I, Op0);
6000
6001 if (isa<UndefValue>(Op0)) {
6002 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6003 return ReplaceInstUsesWith(I, Op0);
6004 else // undef << X -> 0, undef >>u X -> 0
6005 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6006 }
6007 if (isa<UndefValue>(Op1)) {
6008 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6009 return ReplaceInstUsesWith(I, Op0);
6010 else // X << undef, X >>u undef -> 0
6011 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6012 }
6013
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014 // Try to fold constant and into select arguments.
6015 if (isa<Constant>(Op0))
6016 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6017 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6018 return R;
6019
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006020 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6021 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6022 return Res;
6023 return 0;
6024}
6025
6026Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6027 BinaryOperator &I) {
6028 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6029
6030 // See if we can simplify any instructions used by the instruction whose sole
6031 // purpose is to compute bits we don't care about.
6032 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6033 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6034 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6035 KnownZero, KnownOne))
6036 return &I;
6037
6038 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6039 // of a signed value.
6040 //
6041 if (Op1->uge(TypeBits)) {
6042 if (I.getOpcode() != Instruction::AShr)
6043 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6044 else {
6045 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6046 return &I;
6047 }
6048 }
6049
6050 // ((X*C1) << C2) == (X * (C1 << C2))
6051 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6052 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6053 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6054 return BinaryOperator::createMul(BO->getOperand(0),
6055 ConstantExpr::getShl(BOOp, Op1));
6056
6057 // Try to fold constant and into select arguments.
6058 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6059 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6060 return R;
6061 if (isa<PHINode>(Op0))
6062 if (Instruction *NV = FoldOpIntoPhi(I))
6063 return NV;
6064
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006065 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6066 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6067 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6068 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6069 // place. Don't try to do this transformation in this case. Also, we
6070 // require that the input operand is a shift-by-constant so that we have
6071 // confidence that the shifts will get folded together. We could do this
6072 // xform in more cases, but it is unlikely to be profitable.
6073 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6074 isa<ConstantInt>(TrOp->getOperand(1))) {
6075 // Okay, we'll do this xform. Make the shift of shift.
6076 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6077 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6078 I.getName());
6079 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6080
6081 // For logical shifts, the truncation has the effect of making the high
6082 // part of the register be zeros. Emulate this by inserting an AND to
6083 // clear the top bits as needed. This 'and' will usually be zapped by
6084 // other xforms later if dead.
6085 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6086 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6087 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6088
6089 // The mask we constructed says what the trunc would do if occurring
6090 // between the shifts. We want to know the effect *after* the second
6091 // shift. We know that it is a logical shift by a constant, so adjust the
6092 // mask as appropriate.
6093 if (I.getOpcode() == Instruction::Shl)
6094 MaskV <<= Op1->getZExtValue();
6095 else {
6096 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6097 MaskV = MaskV.lshr(Op1->getZExtValue());
6098 }
6099
6100 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6101 TI->getName());
6102 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6103
6104 // Return the value truncated to the interesting size.
6105 return new TruncInst(And, I.getType());
6106 }
6107 }
6108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006109 if (Op0->hasOneUse()) {
6110 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6111 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6112 Value *V1, *V2;
6113 ConstantInt *CC;
6114 switch (Op0BO->getOpcode()) {
6115 default: break;
6116 case Instruction::Add:
6117 case Instruction::And:
6118 case Instruction::Or:
6119 case Instruction::Xor: {
6120 // These operators commute.
6121 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6122 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6123 match(Op0BO->getOperand(1),
6124 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6125 Instruction *YS = BinaryOperator::createShl(
6126 Op0BO->getOperand(0), Op1,
6127 Op0BO->getName());
6128 InsertNewInstBefore(YS, I); // (Y << C)
6129 Instruction *X =
6130 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6131 Op0BO->getOperand(1)->getName());
6132 InsertNewInstBefore(X, I); // (X + (Y << C))
6133 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6134 return BinaryOperator::createAnd(X, ConstantInt::get(
6135 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6136 }
6137
6138 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6139 Value *Op0BOOp1 = Op0BO->getOperand(1);
6140 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6141 match(Op0BOOp1,
6142 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6143 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6144 V2 == Op1) {
6145 Instruction *YS = BinaryOperator::createShl(
6146 Op0BO->getOperand(0), Op1,
6147 Op0BO->getName());
6148 InsertNewInstBefore(YS, I); // (Y << C)
6149 Instruction *XM =
6150 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6151 V1->getName()+".mask");
6152 InsertNewInstBefore(XM, I); // X & (CC << C)
6153
6154 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6155 }
6156 }
6157
6158 // FALL THROUGH.
6159 case Instruction::Sub: {
6160 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6161 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6162 match(Op0BO->getOperand(0),
6163 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6164 Instruction *YS = BinaryOperator::createShl(
6165 Op0BO->getOperand(1), Op1,
6166 Op0BO->getName());
6167 InsertNewInstBefore(YS, I); // (Y << C)
6168 Instruction *X =
6169 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6170 Op0BO->getOperand(0)->getName());
6171 InsertNewInstBefore(X, I); // (X + (Y << C))
6172 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6173 return BinaryOperator::createAnd(X, ConstantInt::get(
6174 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6175 }
6176
6177 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6178 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6179 match(Op0BO->getOperand(0),
6180 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6181 m_ConstantInt(CC))) && V2 == Op1 &&
6182 cast<BinaryOperator>(Op0BO->getOperand(0))
6183 ->getOperand(0)->hasOneUse()) {
6184 Instruction *YS = BinaryOperator::createShl(
6185 Op0BO->getOperand(1), Op1,
6186 Op0BO->getName());
6187 InsertNewInstBefore(YS, I); // (Y << C)
6188 Instruction *XM =
6189 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6190 V1->getName()+".mask");
6191 InsertNewInstBefore(XM, I); // X & (CC << C)
6192
6193 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6194 }
6195
6196 break;
6197 }
6198 }
6199
6200
6201 // If the operand is an bitwise operator with a constant RHS, and the
6202 // shift is the only use, we can pull it out of the shift.
6203 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6204 bool isValid = true; // Valid only for And, Or, Xor
6205 bool highBitSet = false; // Transform if high bit of constant set?
6206
6207 switch (Op0BO->getOpcode()) {
6208 default: isValid = false; break; // Do not perform transform!
6209 case Instruction::Add:
6210 isValid = isLeftShift;
6211 break;
6212 case Instruction::Or:
6213 case Instruction::Xor:
6214 highBitSet = false;
6215 break;
6216 case Instruction::And:
6217 highBitSet = true;
6218 break;
6219 }
6220
6221 // If this is a signed shift right, and the high bit is modified
6222 // by the logical operation, do not perform the transformation.
6223 // The highBitSet boolean indicates the value of the high bit of
6224 // the constant which would cause it to be modified for this
6225 // operation.
6226 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006227 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006228 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006229
6230 if (isValid) {
6231 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6232
6233 Instruction *NewShift =
6234 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6235 InsertNewInstBefore(NewShift, I);
6236 NewShift->takeName(Op0BO);
6237
6238 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6239 NewRHS);
6240 }
6241 }
6242 }
6243 }
6244
6245 // Find out if this is a shift of a shift by a constant.
6246 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6247 if (ShiftOp && !ShiftOp->isShift())
6248 ShiftOp = 0;
6249
6250 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6251 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6252 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6253 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6254 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6255 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6256 Value *X = ShiftOp->getOperand(0);
6257
6258 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6259 if (AmtSum > TypeBits)
6260 AmtSum = TypeBits;
6261
6262 const IntegerType *Ty = cast<IntegerType>(I.getType());
6263
6264 // Check for (X << c1) << c2 and (X >> c1) >> c2
6265 if (I.getOpcode() == ShiftOp->getOpcode()) {
6266 return BinaryOperator::create(I.getOpcode(), X,
6267 ConstantInt::get(Ty, AmtSum));
6268 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6269 I.getOpcode() == Instruction::AShr) {
6270 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6271 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6272 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6273 I.getOpcode() == Instruction::LShr) {
6274 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6275 Instruction *Shift =
6276 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6277 InsertNewInstBefore(Shift, I);
6278
6279 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6280 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6281 }
6282
6283 // Okay, if we get here, one shift must be left, and the other shift must be
6284 // right. See if the amounts are equal.
6285 if (ShiftAmt1 == ShiftAmt2) {
6286 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6287 if (I.getOpcode() == Instruction::Shl) {
6288 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6289 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6290 }
6291 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6292 if (I.getOpcode() == Instruction::LShr) {
6293 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6294 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6295 }
6296 // We can simplify ((X << C) >>s C) into a trunc + sext.
6297 // NOTE: we could do this for any C, but that would make 'unusual' integer
6298 // types. For now, just stick to ones well-supported by the code
6299 // generators.
6300 const Type *SExtType = 0;
6301 switch (Ty->getBitWidth() - ShiftAmt1) {
6302 case 1 :
6303 case 8 :
6304 case 16 :
6305 case 32 :
6306 case 64 :
6307 case 128:
6308 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6309 break;
6310 default: break;
6311 }
6312 if (SExtType) {
6313 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6314 InsertNewInstBefore(NewTrunc, I);
6315 return new SExtInst(NewTrunc, Ty);
6316 }
6317 // Otherwise, we can't handle it yet.
6318 } else if (ShiftAmt1 < ShiftAmt2) {
6319 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6320
6321 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6322 if (I.getOpcode() == Instruction::Shl) {
6323 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6324 ShiftOp->getOpcode() == Instruction::AShr);
6325 Instruction *Shift =
6326 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6327 InsertNewInstBefore(Shift, I);
6328
6329 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6330 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6331 }
6332
6333 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6334 if (I.getOpcode() == Instruction::LShr) {
6335 assert(ShiftOp->getOpcode() == Instruction::Shl);
6336 Instruction *Shift =
6337 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6338 InsertNewInstBefore(Shift, I);
6339
6340 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6341 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6342 }
6343
6344 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6345 } else {
6346 assert(ShiftAmt2 < ShiftAmt1);
6347 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6348
6349 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6350 if (I.getOpcode() == Instruction::Shl) {
6351 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6352 ShiftOp->getOpcode() == Instruction::AShr);
6353 Instruction *Shift =
6354 BinaryOperator::create(ShiftOp->getOpcode(), X,
6355 ConstantInt::get(Ty, ShiftDiff));
6356 InsertNewInstBefore(Shift, I);
6357
6358 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6359 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6360 }
6361
6362 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6363 if (I.getOpcode() == Instruction::LShr) {
6364 assert(ShiftOp->getOpcode() == Instruction::Shl);
6365 Instruction *Shift =
6366 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6367 InsertNewInstBefore(Shift, I);
6368
6369 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6370 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6371 }
6372
6373 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6374 }
6375 }
6376 return 0;
6377}
6378
6379
6380/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6381/// expression. If so, decompose it, returning some value X, such that Val is
6382/// X*Scale+Offset.
6383///
6384static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6385 int &Offset) {
6386 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6387 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6388 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006389 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006390 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006391 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6392 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6393 if (I->getOpcode() == Instruction::Shl) {
6394 // This is a value scaled by '1 << the shift amt'.
6395 Scale = 1U << RHS->getZExtValue();
6396 Offset = 0;
6397 return I->getOperand(0);
6398 } else if (I->getOpcode() == Instruction::Mul) {
6399 // This value is scaled by 'RHS'.
6400 Scale = RHS->getZExtValue();
6401 Offset = 0;
6402 return I->getOperand(0);
6403 } else if (I->getOpcode() == Instruction::Add) {
6404 // We have X+C. Check to see if we really have (X*C2)+C1,
6405 // where C1 is divisible by C2.
6406 unsigned SubScale;
6407 Value *SubVal =
6408 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6409 Offset += RHS->getZExtValue();
6410 Scale = SubScale;
6411 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006412 }
6413 }
6414 }
6415
6416 // Otherwise, we can't look past this.
6417 Scale = 1;
6418 Offset = 0;
6419 return Val;
6420}
6421
6422
6423/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6424/// try to eliminate the cast by moving the type information into the alloc.
6425Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6426 AllocationInst &AI) {
6427 const PointerType *PTy = cast<PointerType>(CI.getType());
6428
6429 // Remove any uses of AI that are dead.
6430 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6431
6432 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6433 Instruction *User = cast<Instruction>(*UI++);
6434 if (isInstructionTriviallyDead(User)) {
6435 while (UI != E && *UI == User)
6436 ++UI; // If this instruction uses AI more than once, don't break UI.
6437
6438 ++NumDeadInst;
6439 DOUT << "IC: DCE: " << *User;
6440 EraseInstFromFunction(*User);
6441 }
6442 }
6443
6444 // Get the type really allocated and the type casted to.
6445 const Type *AllocElTy = AI.getAllocatedType();
6446 const Type *CastElTy = PTy->getElementType();
6447 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6448
6449 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6450 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6451 if (CastElTyAlign < AllocElTyAlign) return 0;
6452
6453 // If the allocation has multiple uses, only promote it if we are strictly
6454 // increasing the alignment of the resultant allocation. If we keep it the
6455 // same, we open the door to infinite loops of various kinds.
6456 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6457
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006458 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6459 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006460 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6461
6462 // See if we can satisfy the modulus by pulling a scale out of the array
6463 // size argument.
6464 unsigned ArraySizeScale;
6465 int ArrayOffset;
6466 Value *NumElements = // See if the array size is a decomposable linear expr.
6467 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6468
6469 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6470 // do the xform.
6471 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6472 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6473
6474 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6475 Value *Amt = 0;
6476 if (Scale == 1) {
6477 Amt = NumElements;
6478 } else {
6479 // If the allocation size is constant, form a constant mul expression
6480 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6481 if (isa<ConstantInt>(NumElements))
6482 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6483 // otherwise multiply the amount and the number of elements
6484 else if (Scale != 1) {
6485 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6486 Amt = InsertNewInstBefore(Tmp, AI);
6487 }
6488 }
6489
6490 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6491 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6492 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6493 Amt = InsertNewInstBefore(Tmp, AI);
6494 }
6495
6496 AllocationInst *New;
6497 if (isa<MallocInst>(AI))
6498 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6499 else
6500 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6501 InsertNewInstBefore(New, AI);
6502 New->takeName(&AI);
6503
6504 // If the allocation has multiple uses, insert a cast and change all things
6505 // that used it to use the new cast. This will also hack on CI, but it will
6506 // die soon.
6507 if (!AI.hasOneUse()) {
6508 AddUsesToWorkList(AI);
6509 // New is the allocation instruction, pointer typed. AI is the original
6510 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6511 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6512 InsertNewInstBefore(NewCast, AI);
6513 AI.replaceAllUsesWith(NewCast);
6514 }
6515 return ReplaceInstUsesWith(CI, New);
6516}
6517
6518/// CanEvaluateInDifferentType - Return true if we can take the specified value
6519/// and return it as type Ty without inserting any new casts and without
6520/// changing the computed value. This is used by code that tries to decide
6521/// whether promoting or shrinking integer operations to wider or smaller types
6522/// will allow us to eliminate a truncate or extend.
6523///
6524/// This is a truncation operation if Ty is smaller than V->getType(), or an
6525/// extension operation if Ty is larger.
6526static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006527 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006528 // We can always evaluate constants in another type.
6529 if (isa<ConstantInt>(V))
6530 return true;
6531
6532 Instruction *I = dyn_cast<Instruction>(V);
6533 if (!I) return false;
6534
6535 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6536
Chris Lattneref70bb82007-08-02 06:11:14 +00006537 // If this is an extension or truncate, we can often eliminate it.
6538 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6539 // If this is a cast from the destination type, we can trivially eliminate
6540 // it, and this will remove a cast overall.
6541 if (I->getOperand(0)->getType() == Ty) {
6542 // If the first operand is itself a cast, and is eliminable, do not count
6543 // this as an eliminable cast. We would prefer to eliminate those two
6544 // casts first.
6545 if (!isa<CastInst>(I->getOperand(0)))
6546 ++NumCastsRemoved;
6547 return true;
6548 }
6549 }
6550
6551 // We can't extend or shrink something that has multiple uses: doing so would
6552 // require duplicating the instruction in general, which isn't profitable.
6553 if (!I->hasOneUse()) return false;
6554
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006555 switch (I->getOpcode()) {
6556 case Instruction::Add:
6557 case Instruction::Sub:
6558 case Instruction::And:
6559 case Instruction::Or:
6560 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006561 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006562 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6563 NumCastsRemoved) &&
6564 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6565 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006567 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006568 // A multiply can be truncated by truncating its operands.
6569 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6570 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6571 NumCastsRemoved) &&
6572 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6573 NumCastsRemoved);
6574
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006575 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006576 // If we are truncating the result of this SHL, and if it's a shift of a
6577 // constant amount, we can always perform a SHL in a smaller type.
6578 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6579 uint32_t BitWidth = Ty->getBitWidth();
6580 if (BitWidth < OrigTy->getBitWidth() &&
6581 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006582 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6583 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006584 }
6585 break;
6586 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006587 // If this is a truncate of a logical shr, we can truncate it to a smaller
6588 // lshr iff we know that the bits we would otherwise be shifting in are
6589 // already zeros.
6590 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6591 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6592 uint32_t BitWidth = Ty->getBitWidth();
6593 if (BitWidth < OrigBitWidth &&
6594 MaskedValueIsZero(I->getOperand(0),
6595 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6596 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006597 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6598 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006599 }
6600 }
6601 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 case Instruction::ZExt:
6603 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006604 case Instruction::Trunc:
6605 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006606 // can safely replace it. Note that replacing it does not reduce the number
6607 // of casts in the input.
6608 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006609 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006610
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006611 break;
6612 default:
6613 // TODO: Can handle more cases here.
6614 break;
6615 }
6616
6617 return false;
6618}
6619
6620/// EvaluateInDifferentType - Given an expression that
6621/// CanEvaluateInDifferentType returns true for, actually insert the code to
6622/// evaluate the expression.
6623Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6624 bool isSigned) {
6625 if (Constant *C = dyn_cast<Constant>(V))
6626 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6627
6628 // Otherwise, it must be an instruction.
6629 Instruction *I = cast<Instruction>(V);
6630 Instruction *Res = 0;
6631 switch (I->getOpcode()) {
6632 case Instruction::Add:
6633 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006634 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006635 case Instruction::And:
6636 case Instruction::Or:
6637 case Instruction::Xor:
6638 case Instruction::AShr:
6639 case Instruction::LShr:
6640 case Instruction::Shl: {
6641 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6642 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6643 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6644 LHS, RHS, I->getName());
6645 break;
6646 }
6647 case Instruction::Trunc:
6648 case Instruction::ZExt:
6649 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006650 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006651 // just return the source. There's no need to insert it because it is not
6652 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 if (I->getOperand(0)->getType() == Ty)
6654 return I->getOperand(0);
6655
Chris Lattneref70bb82007-08-02 06:11:14 +00006656 // Otherwise, must be the same type of case, so just reinsert a new one.
6657 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6658 Ty, I->getName());
6659 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 default:
6661 // TODO: Can handle more cases here.
6662 assert(0 && "Unreachable!");
6663 break;
6664 }
6665
6666 return InsertNewInstBefore(Res, *I);
6667}
6668
6669/// @brief Implement the transforms common to all CastInst visitors.
6670Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6671 Value *Src = CI.getOperand(0);
6672
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6674 // eliminate it now.
6675 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6676 if (Instruction::CastOps opc =
6677 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6678 // The first cast (CSrc) is eliminable so we need to fix up or replace
6679 // the second cast (CI). CSrc will then have a good chance of being dead.
6680 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6681 }
6682 }
6683
6684 // If we are casting a select then fold the cast into the select
6685 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6686 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6687 return NV;
6688
6689 // If we are casting a PHI then fold the cast into the PHI
6690 if (isa<PHINode>(Src))
6691 if (Instruction *NV = FoldOpIntoPhi(CI))
6692 return NV;
6693
6694 return 0;
6695}
6696
6697/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6698Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6699 Value *Src = CI.getOperand(0);
6700
6701 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6702 // If casting the result of a getelementptr instruction with no offset, turn
6703 // this into a cast of the original pointer!
6704 if (GEP->hasAllZeroIndices()) {
6705 // Changing the cast operand is usually not a good idea but it is safe
6706 // here because the pointer operand is being replaced with another
6707 // pointer operand so the opcode doesn't need to change.
6708 AddToWorkList(GEP);
6709 CI.setOperand(0, GEP->getOperand(0));
6710 return &CI;
6711 }
6712
6713 // If the GEP has a single use, and the base pointer is a bitcast, and the
6714 // GEP computes a constant offset, see if we can convert these three
6715 // instructions into fewer. This typically happens with unions and other
6716 // non-type-safe code.
6717 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6718 if (GEP->hasAllConstantIndices()) {
6719 // We are guaranteed to get a constant from EmitGEPOffset.
6720 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6721 int64_t Offset = OffsetV->getSExtValue();
6722
6723 // Get the base pointer input of the bitcast, and the type it points to.
6724 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6725 const Type *GEPIdxTy =
6726 cast<PointerType>(OrigBase->getType())->getElementType();
6727 if (GEPIdxTy->isSized()) {
6728 SmallVector<Value*, 8> NewIndices;
6729
6730 // Start with the index over the outer type. Note that the type size
6731 // might be zero (even if the offset isn't zero) if the indexed type
6732 // is something like [0 x {int, int}]
6733 const Type *IntPtrTy = TD->getIntPtrType();
6734 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006735 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006736 FirstIdx = Offset/TySize;
6737 Offset %= TySize;
6738
6739 // Handle silly modulus not returning values values [0..TySize).
6740 if (Offset < 0) {
6741 --FirstIdx;
6742 Offset += TySize;
6743 assert(Offset >= 0);
6744 }
6745 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6746 }
6747
6748 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6749
6750 // Index into the types. If we fail, set OrigBase to null.
6751 while (Offset) {
6752 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6753 const StructLayout *SL = TD->getStructLayout(STy);
6754 if (Offset < (int64_t)SL->getSizeInBytes()) {
6755 unsigned Elt = SL->getElementContainingOffset(Offset);
6756 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6757
6758 Offset -= SL->getElementOffset(Elt);
6759 GEPIdxTy = STy->getElementType(Elt);
6760 } else {
6761 // Otherwise, we can't index into this, bail out.
6762 Offset = 0;
6763 OrigBase = 0;
6764 }
6765 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6766 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006767 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006768 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6769 Offset %= EltSize;
6770 } else {
6771 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6772 }
6773 GEPIdxTy = STy->getElementType();
6774 } else {
6775 // Otherwise, we can't index into this, bail out.
6776 Offset = 0;
6777 OrigBase = 0;
6778 }
6779 }
6780 if (OrigBase) {
6781 // If we were able to index down into an element, create the GEP
6782 // and bitcast the result. This eliminates one bitcast, potentially
6783 // two.
David Greene393be882007-09-04 15:46:09 +00006784 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6785 NewIndices.begin(),
6786 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006787 InsertNewInstBefore(NGEP, CI);
6788 NGEP->takeName(GEP);
6789
6790 if (isa<BitCastInst>(CI))
6791 return new BitCastInst(NGEP, CI.getType());
6792 assert(isa<PtrToIntInst>(CI));
6793 return new PtrToIntInst(NGEP, CI.getType());
6794 }
6795 }
6796 }
6797 }
6798 }
6799
6800 return commonCastTransforms(CI);
6801}
6802
6803
6804
6805/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6806/// integer types. This function implements the common transforms for all those
6807/// cases.
6808/// @brief Implement the transforms common to CastInst with integer operands
6809Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6810 if (Instruction *Result = commonCastTransforms(CI))
6811 return Result;
6812
6813 Value *Src = CI.getOperand(0);
6814 const Type *SrcTy = Src->getType();
6815 const Type *DestTy = CI.getType();
6816 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6817 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6818
6819 // See if we can simplify any instructions used by the LHS whose sole
6820 // purpose is to compute bits we don't care about.
6821 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6822 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6823 KnownZero, KnownOne))
6824 return &CI;
6825
6826 // If the source isn't an instruction or has more than one use then we
6827 // can't do anything more.
6828 Instruction *SrcI = dyn_cast<Instruction>(Src);
6829 if (!SrcI || !Src->hasOneUse())
6830 return 0;
6831
6832 // Attempt to propagate the cast into the instruction for int->int casts.
6833 int NumCastsRemoved = 0;
6834 if (!isa<BitCastInst>(CI) &&
6835 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006836 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006837 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006838 // eliminates the cast, so it is always a win. If this is a zero-extension,
6839 // we need to do an AND to maintain the clear top-part of the computation,
6840 // so we require that the input have eliminated at least one cast. If this
6841 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842 // require that two casts have been eliminated.
6843 bool DoXForm;
6844 switch (CI.getOpcode()) {
6845 default:
6846 // All the others use floating point so we shouldn't actually
6847 // get here because of the check above.
6848 assert(0 && "Unknown cast type");
6849 case Instruction::Trunc:
6850 DoXForm = true;
6851 break;
6852 case Instruction::ZExt:
6853 DoXForm = NumCastsRemoved >= 1;
6854 break;
6855 case Instruction::SExt:
6856 DoXForm = NumCastsRemoved >= 2;
6857 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006858 }
6859
6860 if (DoXForm) {
6861 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6862 CI.getOpcode() == Instruction::SExt);
6863 assert(Res->getType() == DestTy);
6864 switch (CI.getOpcode()) {
6865 default: assert(0 && "Unknown cast type!");
6866 case Instruction::Trunc:
6867 case Instruction::BitCast:
6868 // Just replace this cast with the result.
6869 return ReplaceInstUsesWith(CI, Res);
6870 case Instruction::ZExt: {
6871 // We need to emit an AND to clear the high bits.
6872 assert(SrcBitSize < DestBitSize && "Not a zext?");
6873 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6874 SrcBitSize));
6875 return BinaryOperator::createAnd(Res, C);
6876 }
6877 case Instruction::SExt:
6878 // We need to emit a cast to truncate, then a cast to sext.
6879 return CastInst::create(Instruction::SExt,
6880 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6881 CI), DestTy);
6882 }
6883 }
6884 }
6885
6886 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6887 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6888
6889 switch (SrcI->getOpcode()) {
6890 case Instruction::Add:
6891 case Instruction::Mul:
6892 case Instruction::And:
6893 case Instruction::Or:
6894 case Instruction::Xor:
6895 // If we are discarding information, rewrite.
6896 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6897 // Don't insert two casts if they cannot be eliminated. We allow
6898 // two casts to be inserted if the sizes are the same. This could
6899 // only be converting signedness, which is a noop.
6900 if (DestBitSize == SrcBitSize ||
6901 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6902 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6903 Instruction::CastOps opcode = CI.getOpcode();
6904 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6905 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6906 return BinaryOperator::create(
6907 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6908 }
6909 }
6910
6911 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6912 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6913 SrcI->getOpcode() == Instruction::Xor &&
6914 Op1 == ConstantInt::getTrue() &&
6915 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6916 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6917 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6918 }
6919 break;
6920 case Instruction::SDiv:
6921 case Instruction::UDiv:
6922 case Instruction::SRem:
6923 case Instruction::URem:
6924 // If we are just changing the sign, rewrite.
6925 if (DestBitSize == SrcBitSize) {
6926 // Don't insert two casts if they cannot be eliminated. We allow
6927 // two casts to be inserted if the sizes are the same. This could
6928 // only be converting signedness, which is a noop.
6929 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6930 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6931 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6932 Op0, DestTy, SrcI);
6933 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6934 Op1, DestTy, SrcI);
6935 return BinaryOperator::create(
6936 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6937 }
6938 }
6939 break;
6940
6941 case Instruction::Shl:
6942 // Allow changing the sign of the source operand. Do not allow
6943 // changing the size of the shift, UNLESS the shift amount is a
6944 // constant. We must not change variable sized shifts to a smaller
6945 // size, because it is undefined to shift more bits out than exist
6946 // in the value.
6947 if (DestBitSize == SrcBitSize ||
6948 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6949 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6950 Instruction::BitCast : Instruction::Trunc);
6951 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6952 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6953 return BinaryOperator::createShl(Op0c, Op1c);
6954 }
6955 break;
6956 case Instruction::AShr:
6957 // If this is a signed shr, and if all bits shifted in are about to be
6958 // truncated off, turn it into an unsigned shr to allow greater
6959 // simplifications.
6960 if (DestBitSize < SrcBitSize &&
6961 isa<ConstantInt>(Op1)) {
6962 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6963 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6964 // Insert the new logical shift right.
6965 return BinaryOperator::createLShr(Op0, Op1);
6966 }
6967 }
6968 break;
6969 }
6970 return 0;
6971}
6972
6973Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6974 if (Instruction *Result = commonIntCastTransforms(CI))
6975 return Result;
6976
6977 Value *Src = CI.getOperand(0);
6978 const Type *Ty = CI.getType();
6979 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6980 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6981
6982 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6983 switch (SrcI->getOpcode()) {
6984 default: break;
6985 case Instruction::LShr:
6986 // We can shrink lshr to something smaller if we know the bits shifted in
6987 // are already zeros.
6988 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6989 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6990
6991 // Get a mask for the bits shifting in.
6992 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6993 Value* SrcIOp0 = SrcI->getOperand(0);
6994 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6995 if (ShAmt >= DestBitWidth) // All zeros.
6996 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6997
6998 // Okay, we can shrink this. Truncate the input, then return a new
6999 // shift.
7000 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7001 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7002 Ty, CI);
7003 return BinaryOperator::createLShr(V1, V2);
7004 }
7005 } else { // This is a variable shr.
7006
7007 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7008 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7009 // loop-invariant and CSE'd.
7010 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7011 Value *One = ConstantInt::get(SrcI->getType(), 1);
7012
7013 Value *V = InsertNewInstBefore(
7014 BinaryOperator::createShl(One, SrcI->getOperand(1),
7015 "tmp"), CI);
7016 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7017 SrcI->getOperand(0),
7018 "tmp"), CI);
7019 Value *Zero = Constant::getNullValue(V->getType());
7020 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7021 }
7022 }
7023 break;
7024 }
7025 }
7026
7027 return 0;
7028}
7029
7030Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7031 // If one of the common conversion will work ..
7032 if (Instruction *Result = commonIntCastTransforms(CI))
7033 return Result;
7034
7035 Value *Src = CI.getOperand(0);
7036
7037 // If this is a cast of a cast
7038 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7039 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7040 // types and if the sizes are just right we can convert this into a logical
7041 // 'and' which will be much cheaper than the pair of casts.
7042 if (isa<TruncInst>(CSrc)) {
7043 // Get the sizes of the types involved
7044 Value *A = CSrc->getOperand(0);
7045 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7046 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7047 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7048 // If we're actually extending zero bits and the trunc is a no-op
7049 if (MidSize < DstSize && SrcSize == DstSize) {
7050 // Replace both of the casts with an And of the type mask.
7051 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7052 Constant *AndConst = ConstantInt::get(AndValue);
7053 Instruction *And =
7054 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7055 // Unfortunately, if the type changed, we need to cast it back.
7056 if (And->getType() != CI.getType()) {
7057 And->setName(CSrc->getName()+".mask");
7058 InsertNewInstBefore(And, CI);
7059 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7060 }
7061 return And;
7062 }
7063 }
7064 }
7065
7066 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7067 // If we are just checking for a icmp eq of a single bit and zext'ing it
7068 // to an integer, then shift the bit to the appropriate place and then
7069 // cast to integer to avoid the comparison.
7070 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7071 const APInt &Op1CV = Op1C->getValue();
7072
7073 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7074 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7075 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7076 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7077 Value *In = ICI->getOperand(0);
7078 Value *Sh = ConstantInt::get(In->getType(),
7079 In->getType()->getPrimitiveSizeInBits()-1);
7080 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7081 In->getName()+".lobit"),
7082 CI);
7083 if (In->getType() != CI.getType())
7084 In = CastInst::createIntegerCast(In, CI.getType(),
7085 false/*ZExt*/, "tmp", &CI);
7086
7087 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7088 Constant *One = ConstantInt::get(In->getType(), 1);
7089 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7090 In->getName()+".not"),
7091 CI);
7092 }
7093
7094 return ReplaceInstUsesWith(CI, In);
7095 }
7096
7097
7098
7099 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7100 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7101 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7102 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7103 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7104 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7105 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7106 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7107 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7108 // This only works for EQ and NE
7109 ICI->isEquality()) {
7110 // If Op1C some other power of two, convert:
7111 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7112 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7113 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7114 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7115
7116 APInt KnownZeroMask(~KnownZero);
7117 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7118 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7119 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7120 // (X&4) == 2 --> false
7121 // (X&4) != 2 --> true
7122 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7123 Res = ConstantExpr::getZExt(Res, CI.getType());
7124 return ReplaceInstUsesWith(CI, Res);
7125 }
7126
7127 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7128 Value *In = ICI->getOperand(0);
7129 if (ShiftAmt) {
7130 // Perform a logical shr by shiftamt.
7131 // Insert the shift to put the result in the low bit.
7132 In = InsertNewInstBefore(
7133 BinaryOperator::createLShr(In,
7134 ConstantInt::get(In->getType(), ShiftAmt),
7135 In->getName()+".lobit"), CI);
7136 }
7137
7138 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7139 Constant *One = ConstantInt::get(In->getType(), 1);
7140 In = BinaryOperator::createXor(In, One, "tmp");
7141 InsertNewInstBefore(cast<Instruction>(In), CI);
7142 }
7143
7144 if (CI.getType() == In->getType())
7145 return ReplaceInstUsesWith(CI, In);
7146 else
7147 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7148 }
7149 }
7150 }
7151 }
7152 return 0;
7153}
7154
7155Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7156 if (Instruction *I = commonIntCastTransforms(CI))
7157 return I;
7158
7159 Value *Src = CI.getOperand(0);
7160
7161 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7162 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7163 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7164 // If we are just checking for a icmp eq of a single bit and zext'ing it
7165 // to an integer, then shift the bit to the appropriate place and then
7166 // cast to integer to avoid the comparison.
7167 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7168 const APInt &Op1CV = Op1C->getValue();
7169
7170 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7171 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7172 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7173 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7174 Value *In = ICI->getOperand(0);
7175 Value *Sh = ConstantInt::get(In->getType(),
7176 In->getType()->getPrimitiveSizeInBits()-1);
7177 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7178 In->getName()+".lobit"),
7179 CI);
7180 if (In->getType() != CI.getType())
7181 In = CastInst::createIntegerCast(In, CI.getType(),
7182 true/*SExt*/, "tmp", &CI);
7183
7184 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7185 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7186 In->getName()+".not"), CI);
7187
7188 return ReplaceInstUsesWith(CI, In);
7189 }
7190 }
7191 }
7192
7193 return 0;
7194}
7195
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007196/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7197/// in the specified FP type without changing its value.
7198static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7199 const fltSemantics &Sem) {
7200 APFloat F = CFP->getValueAPF();
7201 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7202 return ConstantFP::get(FPTy, F);
7203 return 0;
7204}
7205
7206/// LookThroughFPExtensions - If this is an fp extension instruction, look
7207/// through it until we get the source value.
7208static Value *LookThroughFPExtensions(Value *V) {
7209 if (Instruction *I = dyn_cast<Instruction>(V))
7210 if (I->getOpcode() == Instruction::FPExt)
7211 return LookThroughFPExtensions(I->getOperand(0));
7212
7213 // If this value is a constant, return the constant in the smallest FP type
7214 // that can accurately represent it. This allows us to turn
7215 // (float)((double)X+2.0) into x+2.0f.
7216 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7217 if (CFP->getType() == Type::PPC_FP128Ty)
7218 return V; // No constant folding of this.
7219 // See if the value can be truncated to float and then reextended.
7220 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7221 return V;
7222 if (CFP->getType() == Type::DoubleTy)
7223 return V; // Won't shrink.
7224 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7225 return V;
7226 // Don't try to shrink to various long double types.
7227 }
7228
7229 return V;
7230}
7231
7232Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7233 if (Instruction *I = commonCastTransforms(CI))
7234 return I;
7235
7236 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7237 // smaller than the destination type, we can eliminate the truncate by doing
7238 // the add as the smaller type. This applies to add/sub/mul/div as well as
7239 // many builtins (sqrt, etc).
7240 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7241 if (OpI && OpI->hasOneUse()) {
7242 switch (OpI->getOpcode()) {
7243 default: break;
7244 case Instruction::Add:
7245 case Instruction::Sub:
7246 case Instruction::Mul:
7247 case Instruction::FDiv:
7248 case Instruction::FRem:
7249 const Type *SrcTy = OpI->getType();
7250 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7251 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7252 if (LHSTrunc->getType() != SrcTy &&
7253 RHSTrunc->getType() != SrcTy) {
7254 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7255 // If the source types were both smaller than the destination type of
7256 // the cast, do this xform.
7257 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7258 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7259 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7260 CI.getType(), CI);
7261 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7262 CI.getType(), CI);
7263 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7264 }
7265 }
7266 break;
7267 }
7268 }
7269 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270}
7271
7272Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7273 return commonCastTransforms(CI);
7274}
7275
7276Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7277 return commonCastTransforms(CI);
7278}
7279
7280Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7281 return commonCastTransforms(CI);
7282}
7283
7284Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7285 return commonCastTransforms(CI);
7286}
7287
7288Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7289 return commonCastTransforms(CI);
7290}
7291
7292Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7293 return commonPointerCastTransforms(CI);
7294}
7295
Chris Lattner7c1626482008-01-08 07:23:51 +00007296Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7297 if (Instruction *I = commonCastTransforms(CI))
7298 return I;
7299
7300 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7301 if (!DestPointee->isSized()) return 0;
7302
7303 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7304 ConstantInt *Cst;
7305 Value *X;
7306 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7307 m_ConstantInt(Cst)))) {
7308 // If the source and destination operands have the same type, see if this
7309 // is a single-index GEP.
7310 if (X->getType() == CI.getType()) {
7311 // Get the size of the pointee type.
7312 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7313
7314 // Convert the constant to intptr type.
7315 APInt Offset = Cst->getValue();
7316 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7317
7318 // If Offset is evenly divisible by Size, we can do this xform.
7319 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7320 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7321 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7322 }
7323 }
7324 // TODO: Could handle other cases, e.g. where add is indexing into field of
7325 // struct etc.
7326 } else if (CI.getOperand(0)->hasOneUse() &&
7327 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7328 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7329 // "inttoptr+GEP" instead of "add+intptr".
7330
7331 // Get the size of the pointee type.
7332 uint64_t Size = TD->getABITypeSize(DestPointee);
7333
7334 // Convert the constant to intptr type.
7335 APInt Offset = Cst->getValue();
7336 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7337
7338 // If Offset is evenly divisible by Size, we can do this xform.
7339 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7340 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7341
7342 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7343 "tmp"), CI);
7344 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7345 }
7346 }
7347 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007348}
7349
7350Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7351 // If the operands are integer typed then apply the integer transforms,
7352 // otherwise just apply the common ones.
7353 Value *Src = CI.getOperand(0);
7354 const Type *SrcTy = Src->getType();
7355 const Type *DestTy = CI.getType();
7356
7357 if (SrcTy->isInteger() && DestTy->isInteger()) {
7358 if (Instruction *Result = commonIntCastTransforms(CI))
7359 return Result;
7360 } else if (isa<PointerType>(SrcTy)) {
7361 if (Instruction *I = commonPointerCastTransforms(CI))
7362 return I;
7363 } else {
7364 if (Instruction *Result = commonCastTransforms(CI))
7365 return Result;
7366 }
7367
7368
7369 // Get rid of casts from one type to the same type. These are useless and can
7370 // be replaced by the operand.
7371 if (DestTy == Src->getType())
7372 return ReplaceInstUsesWith(CI, Src);
7373
7374 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7375 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7376 const Type *DstElTy = DstPTy->getElementType();
7377 const Type *SrcElTy = SrcPTy->getElementType();
7378
7379 // If we are casting a malloc or alloca to a pointer to a type of the same
7380 // size, rewrite the allocation instruction to allocate the "right" type.
7381 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7382 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7383 return V;
7384
7385 // If the source and destination are pointers, and this cast is equivalent
7386 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7387 // This can enhance SROA and other transforms that want type-safe pointers.
7388 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7389 unsigned NumZeros = 0;
7390 while (SrcElTy != DstElTy &&
7391 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7392 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7393 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7394 ++NumZeros;
7395 }
7396
7397 // If we found a path from the src to dest, create the getelementptr now.
7398 if (SrcElTy == DstElTy) {
7399 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007400 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7401 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007402 }
7403 }
7404
7405 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7406 if (SVI->hasOneUse()) {
7407 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7408 // a bitconvert to a vector with the same # elts.
7409 if (isa<VectorType>(DestTy) &&
7410 cast<VectorType>(DestTy)->getNumElements() ==
7411 SVI->getType()->getNumElements()) {
7412 CastInst *Tmp;
7413 // If either of the operands is a cast from CI.getType(), then
7414 // evaluating the shuffle in the casted destination's type will allow
7415 // us to eliminate at least one cast.
7416 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7417 Tmp->getOperand(0)->getType() == DestTy) ||
7418 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7419 Tmp->getOperand(0)->getType() == DestTy)) {
7420 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7421 SVI->getOperand(0), DestTy, &CI);
7422 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7423 SVI->getOperand(1), DestTy, &CI);
7424 // Return a new shuffle vector. Use the same element ID's, as we
7425 // know the vector types match #elts.
7426 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7427 }
7428 }
7429 }
7430 }
7431 return 0;
7432}
7433
7434/// GetSelectFoldableOperands - We want to turn code that looks like this:
7435/// %C = or %A, %B
7436/// %D = select %cond, %C, %A
7437/// into:
7438/// %C = select %cond, %B, 0
7439/// %D = or %A, %C
7440///
7441/// Assuming that the specified instruction is an operand to the select, return
7442/// a bitmask indicating which operands of this instruction are foldable if they
7443/// equal the other incoming value of the select.
7444///
7445static unsigned GetSelectFoldableOperands(Instruction *I) {
7446 switch (I->getOpcode()) {
7447 case Instruction::Add:
7448 case Instruction::Mul:
7449 case Instruction::And:
7450 case Instruction::Or:
7451 case Instruction::Xor:
7452 return 3; // Can fold through either operand.
7453 case Instruction::Sub: // Can only fold on the amount subtracted.
7454 case Instruction::Shl: // Can only fold on the shift amount.
7455 case Instruction::LShr:
7456 case Instruction::AShr:
7457 return 1;
7458 default:
7459 return 0; // Cannot fold
7460 }
7461}
7462
7463/// GetSelectFoldableConstant - For the same transformation as the previous
7464/// function, return the identity constant that goes into the select.
7465static Constant *GetSelectFoldableConstant(Instruction *I) {
7466 switch (I->getOpcode()) {
7467 default: assert(0 && "This cannot happen!"); abort();
7468 case Instruction::Add:
7469 case Instruction::Sub:
7470 case Instruction::Or:
7471 case Instruction::Xor:
7472 case Instruction::Shl:
7473 case Instruction::LShr:
7474 case Instruction::AShr:
7475 return Constant::getNullValue(I->getType());
7476 case Instruction::And:
7477 return Constant::getAllOnesValue(I->getType());
7478 case Instruction::Mul:
7479 return ConstantInt::get(I->getType(), 1);
7480 }
7481}
7482
7483/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7484/// have the same opcode and only one use each. Try to simplify this.
7485Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7486 Instruction *FI) {
7487 if (TI->getNumOperands() == 1) {
7488 // If this is a non-volatile load or a cast from the same type,
7489 // merge.
7490 if (TI->isCast()) {
7491 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7492 return 0;
7493 } else {
7494 return 0; // unknown unary op.
7495 }
7496
7497 // Fold this by inserting a select from the input values.
7498 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7499 FI->getOperand(0), SI.getName()+".v");
7500 InsertNewInstBefore(NewSI, SI);
7501 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7502 TI->getType());
7503 }
7504
7505 // Only handle binary operators here.
7506 if (!isa<BinaryOperator>(TI))
7507 return 0;
7508
7509 // Figure out if the operations have any operands in common.
7510 Value *MatchOp, *OtherOpT, *OtherOpF;
7511 bool MatchIsOpZero;
7512 if (TI->getOperand(0) == FI->getOperand(0)) {
7513 MatchOp = TI->getOperand(0);
7514 OtherOpT = TI->getOperand(1);
7515 OtherOpF = FI->getOperand(1);
7516 MatchIsOpZero = true;
7517 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7518 MatchOp = TI->getOperand(1);
7519 OtherOpT = TI->getOperand(0);
7520 OtherOpF = FI->getOperand(0);
7521 MatchIsOpZero = false;
7522 } else if (!TI->isCommutative()) {
7523 return 0;
7524 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7525 MatchOp = TI->getOperand(0);
7526 OtherOpT = TI->getOperand(1);
7527 OtherOpF = FI->getOperand(0);
7528 MatchIsOpZero = true;
7529 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7530 MatchOp = TI->getOperand(1);
7531 OtherOpT = TI->getOperand(0);
7532 OtherOpF = FI->getOperand(1);
7533 MatchIsOpZero = true;
7534 } else {
7535 return 0;
7536 }
7537
7538 // If we reach here, they do have operations in common.
7539 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7540 OtherOpF, SI.getName()+".v");
7541 InsertNewInstBefore(NewSI, SI);
7542
7543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7544 if (MatchIsOpZero)
7545 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7546 else
7547 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7548 }
7549 assert(0 && "Shouldn't get here");
7550 return 0;
7551}
7552
7553Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7554 Value *CondVal = SI.getCondition();
7555 Value *TrueVal = SI.getTrueValue();
7556 Value *FalseVal = SI.getFalseValue();
7557
7558 // select true, X, Y -> X
7559 // select false, X, Y -> Y
7560 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7561 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7562
7563 // select C, X, X -> X
7564 if (TrueVal == FalseVal)
7565 return ReplaceInstUsesWith(SI, TrueVal);
7566
7567 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7568 return ReplaceInstUsesWith(SI, FalseVal);
7569 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7570 return ReplaceInstUsesWith(SI, TrueVal);
7571 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7572 if (isa<Constant>(TrueVal))
7573 return ReplaceInstUsesWith(SI, TrueVal);
7574 else
7575 return ReplaceInstUsesWith(SI, FalseVal);
7576 }
7577
7578 if (SI.getType() == Type::Int1Ty) {
7579 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7580 if (C->getZExtValue()) {
7581 // Change: A = select B, true, C --> A = or B, C
7582 return BinaryOperator::createOr(CondVal, FalseVal);
7583 } else {
7584 // Change: A = select B, false, C --> A = and !B, C
7585 Value *NotCond =
7586 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7587 "not."+CondVal->getName()), SI);
7588 return BinaryOperator::createAnd(NotCond, FalseVal);
7589 }
7590 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7591 if (C->getZExtValue() == false) {
7592 // Change: A = select B, C, false --> A = and B, C
7593 return BinaryOperator::createAnd(CondVal, TrueVal);
7594 } else {
7595 // Change: A = select B, C, true --> A = or !B, C
7596 Value *NotCond =
7597 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7598 "not."+CondVal->getName()), SI);
7599 return BinaryOperator::createOr(NotCond, TrueVal);
7600 }
7601 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007602
7603 // select a, b, a -> a&b
7604 // select a, a, b -> a|b
7605 if (CondVal == TrueVal)
7606 return BinaryOperator::createOr(CondVal, FalseVal);
7607 else if (CondVal == FalseVal)
7608 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007609 }
7610
7611 // Selecting between two integer constants?
7612 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7613 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7614 // select C, 1, 0 -> zext C to int
7615 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7616 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7617 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7618 // select C, 0, 1 -> zext !C to int
7619 Value *NotCond =
7620 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7621 "not."+CondVal->getName()), SI);
7622 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7623 }
7624
7625 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7626
7627 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7628
7629 // (x <s 0) ? -1 : 0 -> ashr x, 31
7630 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7631 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7632 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7633 // The comparison constant and the result are not neccessarily the
7634 // same width. Make an all-ones value by inserting a AShr.
7635 Value *X = IC->getOperand(0);
7636 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7637 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7638 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7639 ShAmt, "ones");
7640 InsertNewInstBefore(SRA, SI);
7641
7642 // Finally, convert to the type of the select RHS. We figure out
7643 // if this requires a SExt, Trunc or BitCast based on the sizes.
7644 Instruction::CastOps opc = Instruction::BitCast;
7645 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7646 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7647 if (SRASize < SISize)
7648 opc = Instruction::SExt;
7649 else if (SRASize > SISize)
7650 opc = Instruction::Trunc;
7651 return CastInst::create(opc, SRA, SI.getType());
7652 }
7653 }
7654
7655
7656 // If one of the constants is zero (we know they can't both be) and we
7657 // have an icmp instruction with zero, and we have an 'and' with the
7658 // non-constant value, eliminate this whole mess. This corresponds to
7659 // cases like this: ((X & 27) ? 27 : 0)
7660 if (TrueValC->isZero() || FalseValC->isZero())
7661 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7662 cast<Constant>(IC->getOperand(1))->isNullValue())
7663 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7664 if (ICA->getOpcode() == Instruction::And &&
7665 isa<ConstantInt>(ICA->getOperand(1)) &&
7666 (ICA->getOperand(1) == TrueValC ||
7667 ICA->getOperand(1) == FalseValC) &&
7668 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7669 // Okay, now we know that everything is set up, we just don't
7670 // know whether we have a icmp_ne or icmp_eq and whether the
7671 // true or false val is the zero.
7672 bool ShouldNotVal = !TrueValC->isZero();
7673 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7674 Value *V = ICA;
7675 if (ShouldNotVal)
7676 V = InsertNewInstBefore(BinaryOperator::create(
7677 Instruction::Xor, V, ICA->getOperand(1)), SI);
7678 return ReplaceInstUsesWith(SI, V);
7679 }
7680 }
7681 }
7682
7683 // See if we are selecting two values based on a comparison of the two values.
7684 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7685 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7686 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007687 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7688 // This is not safe in general for floating point:
7689 // consider X== -0, Y== +0.
7690 // It becomes safe if either operand is a nonzero constant.
7691 ConstantFP *CFPt, *CFPf;
7692 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7693 !CFPt->getValueAPF().isZero()) ||
7694 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7695 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007697 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007698 // Transform (X != Y) ? X : Y -> X
7699 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7700 return ReplaceInstUsesWith(SI, TrueVal);
7701 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7702
7703 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7704 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007705 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7706 // This is not safe in general for floating point:
7707 // consider X== -0, Y== +0.
7708 // It becomes safe if either operand is a nonzero constant.
7709 ConstantFP *CFPt, *CFPf;
7710 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7711 !CFPt->getValueAPF().isZero()) ||
7712 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7713 !CFPf->getValueAPF().isZero()))
7714 return ReplaceInstUsesWith(SI, FalseVal);
7715 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 // Transform (X != Y) ? Y : X -> Y
7717 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7718 return ReplaceInstUsesWith(SI, TrueVal);
7719 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7720 }
7721 }
7722
7723 // See if we are selecting two values based on a comparison of the two values.
7724 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7725 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7726 // Transform (X == Y) ? X : Y -> Y
7727 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7728 return ReplaceInstUsesWith(SI, FalseVal);
7729 // Transform (X != Y) ? X : Y -> X
7730 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7731 return ReplaceInstUsesWith(SI, TrueVal);
7732 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7733
7734 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7735 // Transform (X == Y) ? Y : X -> X
7736 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7737 return ReplaceInstUsesWith(SI, FalseVal);
7738 // Transform (X != Y) ? Y : X -> Y
7739 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7740 return ReplaceInstUsesWith(SI, TrueVal);
7741 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7742 }
7743 }
7744
7745 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7746 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7747 if (TI->hasOneUse() && FI->hasOneUse()) {
7748 Instruction *AddOp = 0, *SubOp = 0;
7749
7750 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7751 if (TI->getOpcode() == FI->getOpcode())
7752 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7753 return IV;
7754
7755 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7756 // even legal for FP.
7757 if (TI->getOpcode() == Instruction::Sub &&
7758 FI->getOpcode() == Instruction::Add) {
7759 AddOp = FI; SubOp = TI;
7760 } else if (FI->getOpcode() == Instruction::Sub &&
7761 TI->getOpcode() == Instruction::Add) {
7762 AddOp = TI; SubOp = FI;
7763 }
7764
7765 if (AddOp) {
7766 Value *OtherAddOp = 0;
7767 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7768 OtherAddOp = AddOp->getOperand(1);
7769 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7770 OtherAddOp = AddOp->getOperand(0);
7771 }
7772
7773 if (OtherAddOp) {
7774 // So at this point we know we have (Y -> OtherAddOp):
7775 // select C, (add X, Y), (sub X, Z)
7776 Value *NegVal; // Compute -Z
7777 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7778 NegVal = ConstantExpr::getNeg(C);
7779 } else {
7780 NegVal = InsertNewInstBefore(
7781 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7782 }
7783
7784 Value *NewTrueOp = OtherAddOp;
7785 Value *NewFalseOp = NegVal;
7786 if (AddOp != TI)
7787 std::swap(NewTrueOp, NewFalseOp);
7788 Instruction *NewSel =
7789 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7790
7791 NewSel = InsertNewInstBefore(NewSel, SI);
7792 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7793 }
7794 }
7795 }
7796
7797 // See if we can fold the select into one of our operands.
7798 if (SI.getType()->isInteger()) {
7799 // See the comment above GetSelectFoldableOperands for a description of the
7800 // transformation we are doing here.
7801 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7802 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7803 !isa<Constant>(FalseVal))
7804 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7805 unsigned OpToFold = 0;
7806 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7807 OpToFold = 1;
7808 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7809 OpToFold = 2;
7810 }
7811
7812 if (OpToFold) {
7813 Constant *C = GetSelectFoldableConstant(TVI);
7814 Instruction *NewSel =
7815 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7816 InsertNewInstBefore(NewSel, SI);
7817 NewSel->takeName(TVI);
7818 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7819 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7820 else {
7821 assert(0 && "Unknown instruction!!");
7822 }
7823 }
7824 }
7825
7826 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7827 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7828 !isa<Constant>(TrueVal))
7829 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7830 unsigned OpToFold = 0;
7831 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7832 OpToFold = 1;
7833 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7834 OpToFold = 2;
7835 }
7836
7837 if (OpToFold) {
7838 Constant *C = GetSelectFoldableConstant(FVI);
7839 Instruction *NewSel =
7840 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7841 InsertNewInstBefore(NewSel, SI);
7842 NewSel->takeName(FVI);
7843 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7844 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7845 else
7846 assert(0 && "Unknown instruction!!");
7847 }
7848 }
7849 }
7850
7851 if (BinaryOperator::isNot(CondVal)) {
7852 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7853 SI.setOperand(1, FalseVal);
7854 SI.setOperand(2, TrueVal);
7855 return &SI;
7856 }
7857
7858 return 0;
7859}
7860
Chris Lattner47cf3452007-08-09 19:05:49 +00007861/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7862/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7863/// and it is more than the alignment of the ultimate object, see if we can
7864/// increase the alignment of the ultimate object, making this check succeed.
7865static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7866 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007867 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7868 unsigned Align = GV->getAlignment();
Andrew Lenharthdae02012007-11-08 18:45:15 +00007869 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007870 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007871
7872 // If there is a large requested alignment and we can, bump up the alignment
7873 // of the global.
7874 if (PrefAlign > Align && GV->hasInitializer()) {
7875 GV->setAlignment(PrefAlign);
7876 Align = PrefAlign;
7877 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007878 return Align;
7879 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7880 unsigned Align = AI->getAlignment();
7881 if (Align == 0 && TD) {
7882 if (isa<AllocaInst>(AI))
7883 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7884 else if (isa<MallocInst>(AI)) {
7885 // Malloc returns maximally aligned memory.
7886 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7887 Align =
7888 std::max(Align,
7889 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7890 Align =
7891 std::max(Align,
7892 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7893 }
7894 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007895
7896 // If there is a requested alignment and if this is an alloca, round up. We
7897 // don't do this for malloc, because some systems can't respect the request.
7898 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7899 AI->setAlignment(PrefAlign);
7900 Align = PrefAlign;
7901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902 return Align;
7903 } else if (isa<BitCastInst>(V) ||
7904 (isa<ConstantExpr>(V) &&
7905 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007906 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7907 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007908 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007909 // If all indexes are zero, it is just the alignment of the base pointer.
7910 bool AllZeroOperands = true;
7911 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7912 if (!isa<Constant>(GEPI->getOperand(i)) ||
7913 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7914 AllZeroOperands = false;
7915 break;
7916 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007917
7918 if (AllZeroOperands) {
7919 // Treat this like a bitcast.
7920 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7921 }
7922
7923 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7924 if (BaseAlignment == 0) return 0;
7925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007926 // Otherwise, if the base alignment is >= the alignment we expect for the
7927 // base pointer type, then we know that the resultant pointer is aligned at
7928 // least as much as its type requires.
7929 if (!TD) return 0;
7930
7931 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7932 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007933 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7934 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 const Type *GEPTy = GEPI->getType();
7936 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007937 Align = std::min(Align, (unsigned)
7938 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7939 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940 }
7941 return 0;
7942 }
7943 return 0;
7944}
7945
Chris Lattner00ae5132008-01-13 23:50:23 +00007946Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7947 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7948 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7949 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7950 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7951
7952 if (CopyAlign < MinAlign) {
7953 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7954 return MI;
7955 }
7956
7957 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7958 // load/store.
7959 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7960 if (MemOpLength == 0) return 0;
7961
Chris Lattnerc669fb62008-01-14 00:28:35 +00007962 // Source and destination pointer types are always "i8*" for intrinsic. See
7963 // if the size is something we can handle with a single primitive load/store.
7964 // A single load+store correctly handles overlapping memory in the memmove
7965 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00007966 unsigned Size = MemOpLength->getZExtValue();
7967 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00007968 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00007969
Chris Lattnerc669fb62008-01-14 00:28:35 +00007970 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00007971 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00007972
7973 // Memcpy forces the use of i8* for the source and destination. That means
7974 // that if you're using memcpy to move one double around, you'll get a cast
7975 // from double* to i8*. We'd much rather use a double load+store rather than
7976 // an i64 load+store, here because this improves the odds that the source or
7977 // dest address will be promotable. See if we can find a better type than the
7978 // integer datatype.
7979 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7980 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7981 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7982 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
7983 // down through these levels if so.
7984 while (!SrcETy->isFirstClassType()) {
7985 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
7986 if (STy->getNumElements() == 1)
7987 SrcETy = STy->getElementType(0);
7988 else
7989 break;
7990 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
7991 if (ATy->getNumElements() == 1)
7992 SrcETy = ATy->getElementType();
7993 else
7994 break;
7995 } else
7996 break;
7997 }
7998
7999 if (SrcETy->isFirstClassType())
8000 NewPtrTy = PointerType::getUnqual(SrcETy);
8001 }
8002 }
8003
8004
Chris Lattner00ae5132008-01-13 23:50:23 +00008005 // If the memcpy/memmove provides better alignment info than we can
8006 // infer, use it.
8007 SrcAlign = std::max(SrcAlign, CopyAlign);
8008 DstAlign = std::max(DstAlign, CopyAlign);
8009
8010 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8011 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008012 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8013 InsertNewInstBefore(L, *MI);
8014 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8015
8016 // Set the size of the copy to 0, it will be deleted on the next iteration.
8017 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8018 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008019}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008020
8021/// visitCallInst - CallInst simplification. This mostly only handles folding
8022/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8023/// the heavy lifting.
8024///
8025Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8026 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8027 if (!II) return visitCallSite(&CI);
8028
8029 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8030 // visitCallSite.
8031 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8032 bool Changed = false;
8033
8034 // memmove/cpy/set of zero bytes is a noop.
8035 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8036 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8037
8038 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8039 if (CI->getZExtValue() == 1) {
8040 // Replace the instruction with just byte operations. We would
8041 // transform other cases to loads/stores, but we don't know if
8042 // alignment is sufficient.
8043 }
8044 }
8045
8046 // If we have a memmove and the source operation is a constant global,
8047 // then the source and dest pointers can't alias, so we can change this
8048 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008049 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008050 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8051 if (GVSrc->isConstant()) {
8052 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008053 Intrinsic::ID MemCpyID;
8054 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8055 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008056 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008057 MemCpyID = Intrinsic::memcpy_i64;
8058 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008059 Changed = true;
8060 }
8061 }
8062
8063 // If we can determine a pointer alignment that is bigger than currently
8064 // set, update the alignment.
8065 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008066 if (Instruction *I = SimplifyMemTransfer(MI))
8067 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008068 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008069 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008070 if (MI->getAlignment()->getZExtValue() < Alignment) {
8071 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8072 Changed = true;
8073 }
8074 }
8075
8076 if (Changed) return II;
8077 } else {
8078 switch (II->getIntrinsicID()) {
8079 default: break;
8080 case Intrinsic::ppc_altivec_lvx:
8081 case Intrinsic::ppc_altivec_lvxl:
8082 case Intrinsic::x86_sse_loadu_ps:
8083 case Intrinsic::x86_sse2_loadu_pd:
8084 case Intrinsic::x86_sse2_loadu_dq:
8085 // Turn PPC lvx -> load if the pointer is known aligned.
8086 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008087 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008088 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8089 PointerType::getUnqual(II->getType()),
8090 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008091 return new LoadInst(Ptr);
8092 }
8093 break;
8094 case Intrinsic::ppc_altivec_stvx:
8095 case Intrinsic::ppc_altivec_stvxl:
8096 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008097 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008098 const Type *OpPtrTy =
8099 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008100 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008101 return new StoreInst(II->getOperand(1), Ptr);
8102 }
8103 break;
8104 case Intrinsic::x86_sse_storeu_ps:
8105 case Intrinsic::x86_sse2_storeu_pd:
8106 case Intrinsic::x86_sse2_storeu_dq:
8107 case Intrinsic::x86_sse2_storel_dq:
8108 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008109 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008110 const Type *OpPtrTy =
8111 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008112 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008113 return new StoreInst(II->getOperand(2), Ptr);
8114 }
8115 break;
8116
8117 case Intrinsic::x86_sse_cvttss2si: {
8118 // These intrinsics only demands the 0th element of its input vector. If
8119 // we can simplify the input based on that, do so now.
8120 uint64_t UndefElts;
8121 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8122 UndefElts)) {
8123 II->setOperand(1, V);
8124 return II;
8125 }
8126 break;
8127 }
8128
8129 case Intrinsic::ppc_altivec_vperm:
8130 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8131 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8132 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8133
8134 // Check that all of the elements are integer constants or undefs.
8135 bool AllEltsOk = true;
8136 for (unsigned i = 0; i != 16; ++i) {
8137 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8138 !isa<UndefValue>(Mask->getOperand(i))) {
8139 AllEltsOk = false;
8140 break;
8141 }
8142 }
8143
8144 if (AllEltsOk) {
8145 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008146 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8147 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008148 Value *Result = UndefValue::get(Op0->getType());
8149
8150 // Only extract each element once.
8151 Value *ExtractedElts[32];
8152 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8153
8154 for (unsigned i = 0; i != 16; ++i) {
8155 if (isa<UndefValue>(Mask->getOperand(i)))
8156 continue;
8157 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8158 Idx &= 31; // Match the hardware behavior.
8159
8160 if (ExtractedElts[Idx] == 0) {
8161 Instruction *Elt =
8162 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8163 InsertNewInstBefore(Elt, CI);
8164 ExtractedElts[Idx] = Elt;
8165 }
8166
8167 // Insert this value into the result vector.
8168 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8169 InsertNewInstBefore(cast<Instruction>(Result), CI);
8170 }
8171 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8172 }
8173 }
8174 break;
8175
8176 case Intrinsic::stackrestore: {
8177 // If the save is right next to the restore, remove the restore. This can
8178 // happen when variable allocas are DCE'd.
8179 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8180 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8181 BasicBlock::iterator BI = SS;
8182 if (&*++BI == II)
8183 return EraseInstFromFunction(CI);
8184 }
8185 }
8186
8187 // If the stack restore is in a return/unwind block and if there are no
8188 // allocas or calls between the restore and the return, nuke the restore.
8189 TerminatorInst *TI = II->getParent()->getTerminator();
8190 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8191 BasicBlock::iterator BI = II;
8192 bool CannotRemove = false;
8193 for (++BI; &*BI != TI; ++BI) {
8194 if (isa<AllocaInst>(BI) ||
8195 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8196 CannotRemove = true;
8197 break;
8198 }
8199 }
8200 if (!CannotRemove)
8201 return EraseInstFromFunction(CI);
8202 }
8203 break;
8204 }
8205 }
8206 }
8207
8208 return visitCallSite(II);
8209}
8210
8211// InvokeInst simplification
8212//
8213Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8214 return visitCallSite(&II);
8215}
8216
8217// visitCallSite - Improvements for call and invoke instructions.
8218//
8219Instruction *InstCombiner::visitCallSite(CallSite CS) {
8220 bool Changed = false;
8221
8222 // If the callee is a constexpr cast of a function, attempt to move the cast
8223 // to the arguments of the call/invoke.
8224 if (transformConstExprCastCall(CS)) return 0;
8225
8226 Value *Callee = CS.getCalledValue();
8227
8228 if (Function *CalleeF = dyn_cast<Function>(Callee))
8229 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8230 Instruction *OldCall = CS.getInstruction();
8231 // If the call and callee calling conventions don't match, this call must
8232 // be unreachable, as the call is undefined.
8233 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008234 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8235 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008236 if (!OldCall->use_empty())
8237 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8238 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8239 return EraseInstFromFunction(*OldCall);
8240 return 0;
8241 }
8242
8243 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8244 // This instruction is not reachable, just remove it. We insert a store to
8245 // undef so that we know that this code is not reachable, despite the fact
8246 // that we can't modify the CFG here.
8247 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008248 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008249 CS.getInstruction());
8250
8251 if (!CS.getInstruction()->use_empty())
8252 CS.getInstruction()->
8253 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8254
8255 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8256 // Don't break the CFG, insert a dummy cond branch.
8257 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8258 ConstantInt::getTrue(), II);
8259 }
8260 return EraseInstFromFunction(*CS.getInstruction());
8261 }
8262
Duncan Sands74833f22007-09-17 10:26:40 +00008263 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8264 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8265 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8266 return transformCallThroughTrampoline(CS);
8267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008268 const PointerType *PTy = cast<PointerType>(Callee->getType());
8269 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8270 if (FTy->isVarArg()) {
8271 // See if we can optimize any arguments passed through the varargs area of
8272 // the call.
8273 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8274 E = CS.arg_end(); I != E; ++I)
8275 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8276 // If this cast does not effect the value passed through the varargs
8277 // area, we can eliminate the use of the cast.
8278 Value *Op = CI->getOperand(0);
8279 if (CI->isLosslessCast()) {
8280 *I = Op;
8281 Changed = true;
8282 }
8283 }
8284 }
8285
Duncan Sands2937e352007-12-19 21:13:37 +00008286 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008287 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008288 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008289 Changed = true;
8290 }
8291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008292 return Changed ? CS.getInstruction() : 0;
8293}
8294
8295// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8296// attempt to move the cast to the arguments of the call/invoke.
8297//
8298bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8299 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8300 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8301 if (CE->getOpcode() != Instruction::BitCast ||
8302 !isa<Function>(CE->getOperand(0)))
8303 return false;
8304 Function *Callee = cast<Function>(CE->getOperand(0));
8305 Instruction *Caller = CS.getInstruction();
Duncan Sandsc849e662008-01-06 18:27:01 +00008306 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008307
8308 // Okay, this is a cast from a function to a different type. Unless doing so
8309 // would cause a type conversion of one of our arguments, change this call to
8310 // be a direct call with arguments casted to the appropriate types.
8311 //
8312 const FunctionType *FT = Callee->getFunctionType();
8313 const Type *OldRetTy = Caller->getType();
8314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008315 // Check to see if we are changing the return type...
8316 if (OldRetTy != FT->getReturnType()) {
8317 if (Callee->isDeclaration() && !Caller->use_empty() &&
8318 // Conversion is ok if changing from pointer to int of same size.
8319 !(isa<PointerType>(FT->getReturnType()) &&
8320 TD->getIntPtrType() == OldRetTy))
8321 return false; // Cannot transform this return value.
8322
Duncan Sands5c489582008-01-06 10:12:28 +00008323 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008324 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008325 FT->getReturnType() != Type::VoidTy &&
8326 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008327 return false; // Cannot transform this return value.
8328
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008329 if (CallerPAL && !Caller->use_empty()) {
8330 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8331 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8332 return false; // Attribute not compatible with transformed value.
8333 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008334
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008335 // If the callsite is an invoke instruction, and the return value is used by
8336 // a PHI node in a successor, we cannot change the return type of the call
8337 // because there is no place to put the cast instruction (without breaking
8338 // the critical edge). Bail out in this case.
8339 if (!Caller->use_empty())
8340 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8341 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8342 UI != E; ++UI)
8343 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8344 if (PN->getParent() == II->getNormalDest() ||
8345 PN->getParent() == II->getUnwindDest())
8346 return false;
8347 }
8348
8349 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8350 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8351
8352 CallSite::arg_iterator AI = CS.arg_begin();
8353 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8354 const Type *ParamTy = FT->getParamType(i);
8355 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008356
8357 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008358 return false; // Cannot transform this parameter value.
8359
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008360 if (CallerPAL) {
8361 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8362 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8363 return false; // Attribute not compatible with transformed value.
8364 }
Duncan Sands5c489582008-01-06 10:12:28 +00008365
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008367 // Some conversions are safe even if we do not have a body.
8368 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369 bool isConvertible = ActTy == ParamTy ||
8370 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8371 (ParamTy->isInteger() && ActTy->isInteger() &&
8372 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8373 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8374 && c->getValue().isStrictlyPositive());
8375 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008376 }
8377
8378 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8379 Callee->isDeclaration())
8380 return false; // Do not delete arguments unless we have a function body...
8381
Duncan Sands4ced1f82008-01-13 08:02:44 +00008382 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsc849e662008-01-06 18:27:01 +00008383 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008384 // won't be dropping them. Check that these extra arguments have attributes
8385 // that are compatible with being a vararg call argument.
8386 for (unsigned i = CallerPAL->size(); i; --i) {
8387 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8388 break;
8389 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8390 if (PAttrs & ParamAttr::VarArgsIncompatible)
8391 return false;
8392 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008393
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008394 // Okay, we decided that this is a safe thing to do: go ahead and start
8395 // inserting cast instructions as necessary...
8396 std::vector<Value*> Args;
8397 Args.reserve(NumActualArgs);
Duncan Sandsc849e662008-01-06 18:27:01 +00008398 ParamAttrsVector attrVec;
8399 attrVec.reserve(NumCommonArgs);
8400
8401 // Get any return attributes.
8402 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8403
8404 // If the return value is not being used, the type may not be compatible
8405 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008406 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008407
8408 // Add the new return attributes.
8409 if (RAttrs)
8410 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008411
8412 AI = CS.arg_begin();
8413 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8414 const Type *ParamTy = FT->getParamType(i);
8415 if ((*AI)->getType() == ParamTy) {
8416 Args.push_back(*AI);
8417 } else {
8418 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8419 false, ParamTy, false);
8420 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8421 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8422 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008423
8424 // Add any parameter attributes.
8425 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8426 if (PAttrs)
8427 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008428 }
8429
8430 // If the function takes more arguments than the call was taking, add them
8431 // now...
8432 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8433 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8434
8435 // If we are removing arguments to the function, emit an obnoxious warning...
8436 if (FT->getNumParams() < NumActualArgs)
8437 if (!FT->isVarArg()) {
8438 cerr << "WARNING: While resolving call to function '"
8439 << Callee->getName() << "' arguments were dropped!\n";
8440 } else {
8441 // Add all of the arguments in their promoted form to the arg list...
8442 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8443 const Type *PTy = getPromotedType((*AI)->getType());
8444 if (PTy != (*AI)->getType()) {
8445 // Must promote to pass through va_arg area!
8446 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8447 PTy, false);
8448 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8449 InsertNewInstBefore(Cast, *Caller);
8450 Args.push_back(Cast);
8451 } else {
8452 Args.push_back(*AI);
8453 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008454
Duncan Sands4ced1f82008-01-13 08:02:44 +00008455 // Add any parameter attributes.
8456 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8457 if (PAttrs)
8458 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008460 }
8461
8462 if (FT->getReturnType() == Type::VoidTy)
8463 Caller->setName(""); // Void type should not have a name.
8464
Duncan Sandsc849e662008-01-06 18:27:01 +00008465 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008467 Instruction *NC;
8468 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8469 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008470 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008471 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008472 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008473 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008474 NC = new CallInst(Callee, Args.begin(), Args.end(),
8475 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008476 CallInst *CI = cast<CallInst>(Caller);
8477 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008478 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008479 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008480 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008481 }
8482
8483 // Insert a cast of the return type as necessary.
8484 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008485 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008486 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008487 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008488 OldRetTy, false);
8489 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008490
8491 // If this is an invoke instruction, we should insert it after the first
8492 // non-phi, instruction in the normal successor block.
8493 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8494 BasicBlock::iterator I = II->getNormalDest()->begin();
8495 while (isa<PHINode>(I)) ++I;
8496 InsertNewInstBefore(NC, *I);
8497 } else {
8498 // Otherwise, it's a call, just insert cast right after the call instr
8499 InsertNewInstBefore(NC, *Caller);
8500 }
8501 AddUsersToWorkList(*Caller);
8502 } else {
8503 NV = UndefValue::get(Caller->getType());
8504 }
8505 }
8506
8507 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8508 Caller->replaceAllUsesWith(NV);
8509 Caller->eraseFromParent();
8510 RemoveFromWorkList(Caller);
8511 return true;
8512}
8513
Duncan Sands74833f22007-09-17 10:26:40 +00008514// transformCallThroughTrampoline - Turn a call to a function created by the
8515// init_trampoline intrinsic into a direct call to the underlying function.
8516//
8517Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8518 Value *Callee = CS.getCalledValue();
8519 const PointerType *PTy = cast<PointerType>(Callee->getType());
8520 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sands48b81112008-01-14 19:52:09 +00008521 const ParamAttrsList *Attrs = CS.getParamAttrs();
8522
8523 // If the call already has the 'nest' attribute somewhere then give up -
8524 // otherwise 'nest' would occur twice after splicing in the chain.
8525 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8526 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008527
8528 IntrinsicInst *Tramp =
8529 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8530
8531 Function *NestF =
8532 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8533 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8534 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8535
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008536 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008537 unsigned NestIdx = 1;
8538 const Type *NestTy = 0;
8539 uint16_t NestAttr = 0;
8540
8541 // Look for a parameter marked with the 'nest' attribute.
8542 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8543 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8544 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8545 // Record the parameter type and any other attributes.
8546 NestTy = *I;
8547 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8548 break;
8549 }
8550
8551 if (NestTy) {
8552 Instruction *Caller = CS.getInstruction();
8553 std::vector<Value*> NewArgs;
8554 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8555
Duncan Sands48b81112008-01-14 19:52:09 +00008556 ParamAttrsVector NewAttrs;
8557 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8558
Duncan Sands74833f22007-09-17 10:26:40 +00008559 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008560 // mean appending it. Likewise for attributes.
8561
8562 // Add any function result attributes.
8563 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8564 if (Attr)
8565 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8566
Duncan Sands74833f22007-09-17 10:26:40 +00008567 {
8568 unsigned Idx = 1;
8569 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8570 do {
8571 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008572 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008573 Value *NestVal = Tramp->getOperand(3);
8574 if (NestVal->getType() != NestTy)
8575 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8576 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008577 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008578 }
8579
8580 if (I == E)
8581 break;
8582
Duncan Sands48b81112008-01-14 19:52:09 +00008583 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008584 NewArgs.push_back(*I);
Duncan Sands48b81112008-01-14 19:52:09 +00008585 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8586 if (Attr)
8587 NewAttrs.push_back
8588 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008589
8590 ++Idx, ++I;
8591 } while (1);
8592 }
8593
8594 // The trampoline may have been bitcast to a bogus type (FTy).
8595 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008596 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008597
Duncan Sands74833f22007-09-17 10:26:40 +00008598 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008599 NewTypes.reserve(FTy->getNumParams()+1);
8600
Duncan Sands74833f22007-09-17 10:26:40 +00008601 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008602 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008603 {
8604 unsigned Idx = 1;
8605 FunctionType::param_iterator I = FTy->param_begin(),
8606 E = FTy->param_end();
8607
8608 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008609 if (Idx == NestIdx)
8610 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008611 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008612
8613 if (I == E)
8614 break;
8615
Duncan Sands48b81112008-01-14 19:52:09 +00008616 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008617 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008618
8619 ++Idx, ++I;
8620 } while (1);
8621 }
8622
8623 // Replace the trampoline call with a direct call. Let the generic
8624 // code sort out any function type mismatches.
8625 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008626 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008627 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8628 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008629 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sands74833f22007-09-17 10:26:40 +00008630
8631 Instruction *NewCaller;
8632 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8633 NewCaller = new InvokeInst(NewCallee,
8634 II->getNormalDest(), II->getUnwindDest(),
8635 NewArgs.begin(), NewArgs.end(),
8636 Caller->getName(), Caller);
8637 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008638 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008639 } else {
8640 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8641 Caller->getName(), Caller);
8642 if (cast<CallInst>(Caller)->isTailCall())
8643 cast<CallInst>(NewCaller)->setTailCall();
8644 cast<CallInst>(NewCaller)->
8645 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008646 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008647 }
8648 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8649 Caller->replaceAllUsesWith(NewCaller);
8650 Caller->eraseFromParent();
8651 RemoveFromWorkList(Caller);
8652 return 0;
8653 }
8654 }
8655
8656 // Replace the trampoline call with a direct call. Since there is no 'nest'
8657 // parameter, there is no need to adjust the argument list. Let the generic
8658 // code sort out any function type mismatches.
8659 Constant *NewCallee =
8660 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8661 CS.setCalledFunction(NewCallee);
8662 return CS.getInstruction();
8663}
8664
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008665/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8666/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8667/// and a single binop.
8668Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8669 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8670 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8671 isa<CmpInst>(FirstInst));
8672 unsigned Opc = FirstInst->getOpcode();
8673 Value *LHSVal = FirstInst->getOperand(0);
8674 Value *RHSVal = FirstInst->getOperand(1);
8675
8676 const Type *LHSType = LHSVal->getType();
8677 const Type *RHSType = RHSVal->getType();
8678
8679 // Scan to see if all operands are the same opcode, all have one use, and all
8680 // kill their operands (i.e. the operands have one use).
8681 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8682 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8683 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8684 // Verify type of the LHS matches so we don't fold cmp's of different
8685 // types or GEP's with different index types.
8686 I->getOperand(0)->getType() != LHSType ||
8687 I->getOperand(1)->getType() != RHSType)
8688 return 0;
8689
8690 // If they are CmpInst instructions, check their predicates
8691 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8692 if (cast<CmpInst>(I)->getPredicate() !=
8693 cast<CmpInst>(FirstInst)->getPredicate())
8694 return 0;
8695
8696 // Keep track of which operand needs a phi node.
8697 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8698 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8699 }
8700
8701 // Otherwise, this is safe to transform, determine if it is profitable.
8702
8703 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8704 // Indexes are often folded into load/store instructions, so we don't want to
8705 // hide them behind a phi.
8706 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8707 return 0;
8708
8709 Value *InLHS = FirstInst->getOperand(0);
8710 Value *InRHS = FirstInst->getOperand(1);
8711 PHINode *NewLHS = 0, *NewRHS = 0;
8712 if (LHSVal == 0) {
8713 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8714 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8715 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8716 InsertNewInstBefore(NewLHS, PN);
8717 LHSVal = NewLHS;
8718 }
8719
8720 if (RHSVal == 0) {
8721 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8722 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8723 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8724 InsertNewInstBefore(NewRHS, PN);
8725 RHSVal = NewRHS;
8726 }
8727
8728 // Add all operands to the new PHIs.
8729 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8730 if (NewLHS) {
8731 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8732 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8733 }
8734 if (NewRHS) {
8735 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8736 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8737 }
8738 }
8739
8740 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8741 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8742 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8743 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8744 RHSVal);
8745 else {
8746 assert(isa<GetElementPtrInst>(FirstInst));
8747 return new GetElementPtrInst(LHSVal, RHSVal);
8748 }
8749}
8750
8751/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8752/// of the block that defines it. This means that it must be obvious the value
8753/// of the load is not changed from the point of the load to the end of the
8754/// block it is in.
8755///
8756/// Finally, it is safe, but not profitable, to sink a load targetting a
8757/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8758/// to a register.
8759static bool isSafeToSinkLoad(LoadInst *L) {
8760 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8761
8762 for (++BBI; BBI != E; ++BBI)
8763 if (BBI->mayWriteToMemory())
8764 return false;
8765
8766 // Check for non-address taken alloca. If not address-taken already, it isn't
8767 // profitable to do this xform.
8768 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8769 bool isAddressTaken = false;
8770 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8771 UI != E; ++UI) {
8772 if (isa<LoadInst>(UI)) continue;
8773 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8774 // If storing TO the alloca, then the address isn't taken.
8775 if (SI->getOperand(1) == AI) continue;
8776 }
8777 isAddressTaken = true;
8778 break;
8779 }
8780
8781 if (!isAddressTaken)
8782 return false;
8783 }
8784
8785 return true;
8786}
8787
8788
8789// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8790// operator and they all are only used by the PHI, PHI together their
8791// inputs, and do the operation once, to the result of the PHI.
8792Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8793 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8794
8795 // Scan the instruction, looking for input operations that can be folded away.
8796 // If all input operands to the phi are the same instruction (e.g. a cast from
8797 // the same type or "+42") we can pull the operation through the PHI, reducing
8798 // code size and simplifying code.
8799 Constant *ConstantOp = 0;
8800 const Type *CastSrcTy = 0;
8801 bool isVolatile = false;
8802 if (isa<CastInst>(FirstInst)) {
8803 CastSrcTy = FirstInst->getOperand(0)->getType();
8804 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8805 // Can fold binop, compare or shift here if the RHS is a constant,
8806 // otherwise call FoldPHIArgBinOpIntoPHI.
8807 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8808 if (ConstantOp == 0)
8809 return FoldPHIArgBinOpIntoPHI(PN);
8810 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8811 isVolatile = LI->isVolatile();
8812 // We can't sink the load if the loaded value could be modified between the
8813 // load and the PHI.
8814 if (LI->getParent() != PN.getIncomingBlock(0) ||
8815 !isSafeToSinkLoad(LI))
8816 return 0;
8817 } else if (isa<GetElementPtrInst>(FirstInst)) {
8818 if (FirstInst->getNumOperands() == 2)
8819 return FoldPHIArgBinOpIntoPHI(PN);
8820 // Can't handle general GEPs yet.
8821 return 0;
8822 } else {
8823 return 0; // Cannot fold this operation.
8824 }
8825
8826 // Check to see if all arguments are the same operation.
8827 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8828 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8829 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8830 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8831 return 0;
8832 if (CastSrcTy) {
8833 if (I->getOperand(0)->getType() != CastSrcTy)
8834 return 0; // Cast operation must match.
8835 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8836 // We can't sink the load if the loaded value could be modified between
8837 // the load and the PHI.
8838 if (LI->isVolatile() != isVolatile ||
8839 LI->getParent() != PN.getIncomingBlock(i) ||
8840 !isSafeToSinkLoad(LI))
8841 return 0;
8842 } else if (I->getOperand(1) != ConstantOp) {
8843 return 0;
8844 }
8845 }
8846
8847 // Okay, they are all the same operation. Create a new PHI node of the
8848 // correct type, and PHI together all of the LHS's of the instructions.
8849 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8850 PN.getName()+".in");
8851 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8852
8853 Value *InVal = FirstInst->getOperand(0);
8854 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8855
8856 // Add all operands to the new PHI.
8857 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8858 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8859 if (NewInVal != InVal)
8860 InVal = 0;
8861 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8862 }
8863
8864 Value *PhiVal;
8865 if (InVal) {
8866 // The new PHI unions all of the same values together. This is really
8867 // common, so we handle it intelligently here for compile-time speed.
8868 PhiVal = InVal;
8869 delete NewPN;
8870 } else {
8871 InsertNewInstBefore(NewPN, PN);
8872 PhiVal = NewPN;
8873 }
8874
8875 // Insert and return the new operation.
8876 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8877 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8878 else if (isa<LoadInst>(FirstInst))
8879 return new LoadInst(PhiVal, "", isVolatile);
8880 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8881 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8882 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8883 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8884 PhiVal, ConstantOp);
8885 else
8886 assert(0 && "Unknown operation");
8887 return 0;
8888}
8889
8890/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8891/// that is dead.
8892static bool DeadPHICycle(PHINode *PN,
8893 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8894 if (PN->use_empty()) return true;
8895 if (!PN->hasOneUse()) return false;
8896
8897 // Remember this node, and if we find the cycle, return.
8898 if (!PotentiallyDeadPHIs.insert(PN))
8899 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00008900
8901 // Don't scan crazily complex things.
8902 if (PotentiallyDeadPHIs.size() == 16)
8903 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008904
8905 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8906 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8907
8908 return false;
8909}
8910
Chris Lattner27b695d2007-11-06 21:52:06 +00008911/// PHIsEqualValue - Return true if this phi node is always equal to
8912/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8913/// z = some value; x = phi (y, z); y = phi (x, z)
8914static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8915 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8916 // See if we already saw this PHI node.
8917 if (!ValueEqualPHIs.insert(PN))
8918 return true;
8919
8920 // Don't scan crazily complex things.
8921 if (ValueEqualPHIs.size() == 16)
8922 return false;
8923
8924 // Scan the operands to see if they are either phi nodes or are equal to
8925 // the value.
8926 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8927 Value *Op = PN->getIncomingValue(i);
8928 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8929 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8930 return false;
8931 } else if (Op != NonPhiInVal)
8932 return false;
8933 }
8934
8935 return true;
8936}
8937
8938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008939// PHINode simplification
8940//
8941Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8942 // If LCSSA is around, don't mess with Phi nodes
8943 if (MustPreserveLCSSA) return 0;
8944
8945 if (Value *V = PN.hasConstantValue())
8946 return ReplaceInstUsesWith(PN, V);
8947
8948 // If all PHI operands are the same operation, pull them through the PHI,
8949 // reducing code size.
8950 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8951 PN.getIncomingValue(0)->hasOneUse())
8952 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8953 return Result;
8954
8955 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8956 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8957 // PHI)... break the cycle.
8958 if (PN.hasOneUse()) {
8959 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8960 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8961 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8962 PotentiallyDeadPHIs.insert(&PN);
8963 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8964 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8965 }
8966
8967 // If this phi has a single use, and if that use just computes a value for
8968 // the next iteration of a loop, delete the phi. This occurs with unused
8969 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8970 // common case here is good because the only other things that catch this
8971 // are induction variable analysis (sometimes) and ADCE, which is only run
8972 // late.
8973 if (PHIUser->hasOneUse() &&
8974 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8975 PHIUser->use_back() == &PN) {
8976 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8977 }
8978 }
8979
Chris Lattner27b695d2007-11-06 21:52:06 +00008980 // We sometimes end up with phi cycles that non-obviously end up being the
8981 // same value, for example:
8982 // z = some value; x = phi (y, z); y = phi (x, z)
8983 // where the phi nodes don't necessarily need to be in the same block. Do a
8984 // quick check to see if the PHI node only contains a single non-phi value, if
8985 // so, scan to see if the phi cycle is actually equal to that value.
8986 {
8987 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8988 // Scan for the first non-phi operand.
8989 while (InValNo != NumOperandVals &&
8990 isa<PHINode>(PN.getIncomingValue(InValNo)))
8991 ++InValNo;
8992
8993 if (InValNo != NumOperandVals) {
8994 Value *NonPhiInVal = PN.getOperand(InValNo);
8995
8996 // Scan the rest of the operands to see if there are any conflicts, if so
8997 // there is no need to recursively scan other phis.
8998 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8999 Value *OpVal = PN.getIncomingValue(InValNo);
9000 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9001 break;
9002 }
9003
9004 // If we scanned over all operands, then we have one unique value plus
9005 // phi values. Scan PHI nodes to see if they all merge in each other or
9006 // the value.
9007 if (InValNo == NumOperandVals) {
9008 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9009 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9010 return ReplaceInstUsesWith(PN, NonPhiInVal);
9011 }
9012 }
9013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009014 return 0;
9015}
9016
9017static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9018 Instruction *InsertPoint,
9019 InstCombiner *IC) {
9020 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9021 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9022 // We must cast correctly to the pointer type. Ensure that we
9023 // sign extend the integer value if it is smaller as this is
9024 // used for address computation.
9025 Instruction::CastOps opcode =
9026 (VTySize < PtrSize ? Instruction::SExt :
9027 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9028 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9029}
9030
9031
9032Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9033 Value *PtrOp = GEP.getOperand(0);
9034 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9035 // If so, eliminate the noop.
9036 if (GEP.getNumOperands() == 1)
9037 return ReplaceInstUsesWith(GEP, PtrOp);
9038
9039 if (isa<UndefValue>(GEP.getOperand(0)))
9040 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9041
9042 bool HasZeroPointerIndex = false;
9043 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9044 HasZeroPointerIndex = C->isNullValue();
9045
9046 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9047 return ReplaceInstUsesWith(GEP, PtrOp);
9048
9049 // Eliminate unneeded casts for indices.
9050 bool MadeChange = false;
9051
9052 gep_type_iterator GTI = gep_type_begin(GEP);
9053 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9054 if (isa<SequentialType>(*GTI)) {
9055 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9056 if (CI->getOpcode() == Instruction::ZExt ||
9057 CI->getOpcode() == Instruction::SExt) {
9058 const Type *SrcTy = CI->getOperand(0)->getType();
9059 // We can eliminate a cast from i32 to i64 iff the target
9060 // is a 32-bit pointer target.
9061 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9062 MadeChange = true;
9063 GEP.setOperand(i, CI->getOperand(0));
9064 }
9065 }
9066 }
9067 // If we are using a wider index than needed for this platform, shrink it
9068 // to what we need. If the incoming value needs a cast instruction,
9069 // insert it. This explicit cast can make subsequent optimizations more
9070 // obvious.
9071 Value *Op = GEP.getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009072 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009073 if (Constant *C = dyn_cast<Constant>(Op)) {
9074 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9075 MadeChange = true;
9076 } else {
9077 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9078 GEP);
9079 GEP.setOperand(i, Op);
9080 MadeChange = true;
9081 }
9082 }
9083 }
9084 if (MadeChange) return &GEP;
9085
9086 // If this GEP instruction doesn't move the pointer, and if the input operand
9087 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9088 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009089 if (GEP.hasAllZeroIndices()) {
9090 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9091 // If the bitcast is of an allocation, and the allocation will be
9092 // converted to match the type of the cast, don't touch this.
9093 if (isa<AllocationInst>(BCI->getOperand(0))) {
9094 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009095 if (Instruction *I = visitBitCast(*BCI)) {
9096 if (I != BCI) {
9097 I->takeName(BCI);
9098 BCI->getParent()->getInstList().insert(BCI, I);
9099 ReplaceInstUsesWith(*BCI, I);
9100 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009101 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009102 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009103 }
9104 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9105 }
9106 }
9107
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009108 // Combine Indices - If the source pointer to this getelementptr instruction
9109 // is a getelementptr instruction, combine the indices of the two
9110 // getelementptr instructions into a single instruction.
9111 //
9112 SmallVector<Value*, 8> SrcGEPOperands;
9113 if (User *Src = dyn_castGetElementPtr(PtrOp))
9114 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9115
9116 if (!SrcGEPOperands.empty()) {
9117 // Note that if our source is a gep chain itself that we wait for that
9118 // chain to be resolved before we perform this transformation. This
9119 // avoids us creating a TON of code in some cases.
9120 //
9121 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9122 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9123 return 0; // Wait until our source is folded to completion.
9124
9125 SmallVector<Value*, 8> Indices;
9126
9127 // Find out whether the last index in the source GEP is a sequential idx.
9128 bool EndsWithSequential = false;
9129 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9130 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9131 EndsWithSequential = !isa<StructType>(*I);
9132
9133 // Can we combine the two pointer arithmetics offsets?
9134 if (EndsWithSequential) {
9135 // Replace: gep (gep %P, long B), long A, ...
9136 // With: T = long A+B; gep %P, T, ...
9137 //
9138 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9139 if (SO1 == Constant::getNullValue(SO1->getType())) {
9140 Sum = GO1;
9141 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9142 Sum = SO1;
9143 } else {
9144 // If they aren't the same type, convert both to an integer of the
9145 // target's pointer size.
9146 if (SO1->getType() != GO1->getType()) {
9147 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9148 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9149 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9150 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9151 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009152 unsigned PS = TD->getPointerSizeInBits();
9153 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009154 // Convert GO1 to SO1's type.
9155 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9156
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009157 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 // Convert SO1 to GO1's type.
9159 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9160 } else {
9161 const Type *PT = TD->getIntPtrType();
9162 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9163 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9164 }
9165 }
9166 }
9167 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9168 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9169 else {
9170 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9171 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9172 }
9173 }
9174
9175 // Recycle the GEP we already have if possible.
9176 if (SrcGEPOperands.size() == 2) {
9177 GEP.setOperand(0, SrcGEPOperands[0]);
9178 GEP.setOperand(1, Sum);
9179 return &GEP;
9180 } else {
9181 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9182 SrcGEPOperands.end()-1);
9183 Indices.push_back(Sum);
9184 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9185 }
9186 } else if (isa<Constant>(*GEP.idx_begin()) &&
9187 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9188 SrcGEPOperands.size() != 1) {
9189 // Otherwise we can do the fold if the first index of the GEP is a zero
9190 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9191 SrcGEPOperands.end());
9192 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9193 }
9194
9195 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00009196 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9197 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009198
9199 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9200 // GEP of global variable. If all of the indices for this GEP are
9201 // constants, we can promote this to a constexpr instead of an instruction.
9202
9203 // Scan for nonconstants...
9204 SmallVector<Constant*, 8> Indices;
9205 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9206 for (; I != E && isa<Constant>(*I); ++I)
9207 Indices.push_back(cast<Constant>(*I));
9208
9209 if (I == E) { // If they are all constants...
9210 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9211 &Indices[0],Indices.size());
9212
9213 // Replace all uses of the GEP with the new constexpr...
9214 return ReplaceInstUsesWith(GEP, CE);
9215 }
9216 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9217 if (!isa<PointerType>(X->getType())) {
9218 // Not interesting. Source pointer must be a cast from pointer.
9219 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009220 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9221 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009222 //
9223 // This occurs when the program declares an array extern like "int X[];"
9224 //
9225 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9226 const PointerType *XTy = cast<PointerType>(X->getType());
9227 if (const ArrayType *XATy =
9228 dyn_cast<ArrayType>(XTy->getElementType()))
9229 if (const ArrayType *CATy =
9230 dyn_cast<ArrayType>(CPTy->getElementType()))
9231 if (CATy->getElementType() == XATy->getElementType()) {
9232 // At this point, we know that the cast source type is a pointer
9233 // to an array of the same type as the destination pointer
9234 // array. Because the array type is never stepped over (there
9235 // is a leading zero) we can fold the cast into this GEP.
9236 GEP.setOperand(0, X);
9237 return &GEP;
9238 }
9239 } else if (GEP.getNumOperands() == 2) {
9240 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009241 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9242 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009243 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9244 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9245 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009246 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9247 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009248 Value *Idx[2];
9249 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9250 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009251 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00009252 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009253 // V and GEP are both pointer types --> BitCast
9254 return new BitCastInst(V, GEP.getType());
9255 }
9256
9257 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009258 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009259 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009260 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009261
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009262 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009263 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009264 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009265
9266 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9267 // allow either a mul, shift, or constant here.
9268 Value *NewIdx = 0;
9269 ConstantInt *Scale = 0;
9270 if (ArrayEltSize == 1) {
9271 NewIdx = GEP.getOperand(1);
9272 Scale = ConstantInt::get(NewIdx->getType(), 1);
9273 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9274 NewIdx = ConstantInt::get(CI->getType(), 1);
9275 Scale = CI;
9276 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9277 if (Inst->getOpcode() == Instruction::Shl &&
9278 isa<ConstantInt>(Inst->getOperand(1))) {
9279 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9280 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9281 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9282 NewIdx = Inst->getOperand(0);
9283 } else if (Inst->getOpcode() == Instruction::Mul &&
9284 isa<ConstantInt>(Inst->getOperand(1))) {
9285 Scale = cast<ConstantInt>(Inst->getOperand(1));
9286 NewIdx = Inst->getOperand(0);
9287 }
9288 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009289
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009290 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009291 // out, perform the transformation. Note, we don't know whether Scale is
9292 // signed or not. We'll use unsigned version of division/modulo
9293 // operation after making sure Scale doesn't have the sign bit set.
9294 if (Scale && Scale->getSExtValue() >= 0LL &&
9295 Scale->getZExtValue() % ArrayEltSize == 0) {
9296 Scale = ConstantInt::get(Scale->getType(),
9297 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009298 if (Scale->getZExtValue() != 1) {
9299 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009300 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009301 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9302 NewIdx = InsertNewInstBefore(Sc, GEP);
9303 }
9304
9305 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009306 Value *Idx[2];
9307 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9308 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009309 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00009310 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009311 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9312 // The NewGEP must be pointer typed, so must the old one -> BitCast
9313 return new BitCastInst(NewGEP, GEP.getType());
9314 }
9315 }
9316 }
9317 }
9318
9319 return 0;
9320}
9321
9322Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9323 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9324 if (AI.isArrayAllocation()) // Check C != 1
9325 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9326 const Type *NewTy =
9327 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9328 AllocationInst *New = 0;
9329
9330 // Create and insert the replacement instruction...
9331 if (isa<MallocInst>(AI))
9332 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9333 else {
9334 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9335 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9336 }
9337
9338 InsertNewInstBefore(New, AI);
9339
9340 // Scan to the end of the allocation instructions, to skip over a block of
9341 // allocas if possible...
9342 //
9343 BasicBlock::iterator It = New;
9344 while (isa<AllocationInst>(*It)) ++It;
9345
9346 // Now that I is pointing to the first non-allocation-inst in the block,
9347 // insert our getelementptr instruction...
9348 //
9349 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009350 Value *Idx[2];
9351 Idx[0] = NullIdx;
9352 Idx[1] = NullIdx;
9353 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009354 New->getName()+".sub", It);
9355
9356 // Now make everything use the getelementptr instead of the original
9357 // allocation.
9358 return ReplaceInstUsesWith(AI, V);
9359 } else if (isa<UndefValue>(AI.getArraySize())) {
9360 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9361 }
9362
9363 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9364 // Note that we only do this for alloca's, because malloc should allocate and
9365 // return a unique pointer, even for a zero byte allocation.
9366 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009367 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009368 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9369
9370 return 0;
9371}
9372
9373Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9374 Value *Op = FI.getOperand(0);
9375
9376 // free undef -> unreachable.
9377 if (isa<UndefValue>(Op)) {
9378 // Insert a new store to null because we cannot modify the CFG here.
9379 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009380 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009381 return EraseInstFromFunction(FI);
9382 }
9383
9384 // If we have 'free null' delete the instruction. This can happen in stl code
9385 // when lots of inlining happens.
9386 if (isa<ConstantPointerNull>(Op))
9387 return EraseInstFromFunction(FI);
9388
9389 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9390 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9391 FI.setOperand(0, CI->getOperand(0));
9392 return &FI;
9393 }
9394
9395 // Change free (gep X, 0,0,0,0) into free(X)
9396 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9397 if (GEPI->hasAllZeroIndices()) {
9398 AddToWorkList(GEPI);
9399 FI.setOperand(0, GEPI->getOperand(0));
9400 return &FI;
9401 }
9402 }
9403
9404 // Change free(malloc) into nothing, if the malloc has a single use.
9405 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9406 if (MI->hasOneUse()) {
9407 EraseInstFromFunction(FI);
9408 return EraseInstFromFunction(*MI);
9409 }
9410
9411 return 0;
9412}
9413
9414
9415/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009416static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9417 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009418 User *CI = cast<User>(LI.getOperand(0));
9419 Value *CastOp = CI->getOperand(0);
9420
Devang Patela0f8ea82007-10-18 19:52:32 +00009421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9422 // Instead of loading constant c string, use corresponding integer value
9423 // directly if string length is small enough.
9424 const std::string &Str = CE->getOperand(0)->getStringValue();
9425 if (!Str.empty()) {
9426 unsigned len = Str.length();
9427 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9428 unsigned numBits = Ty->getPrimitiveSizeInBits();
9429 // Replace LI with immediate integer store.
9430 if ((numBits >> 3) == len + 1) {
9431 APInt StrVal(numBits, 0);
9432 APInt SingleChar(numBits, 0);
9433 if (TD->isLittleEndian()) {
9434 for (signed i = len-1; i >= 0; i--) {
9435 SingleChar = (uint64_t) Str[i];
9436 StrVal = (StrVal << 8) | SingleChar;
9437 }
9438 } else {
9439 for (unsigned i = 0; i < len; i++) {
9440 SingleChar = (uint64_t) Str[i];
9441 StrVal = (StrVal << 8) | SingleChar;
9442 }
9443 // Append NULL at the end.
9444 SingleChar = 0;
9445 StrVal = (StrVal << 8) | SingleChar;
9446 }
9447 Value *NL = ConstantInt::get(StrVal);
9448 return IC.ReplaceInstUsesWith(LI, NL);
9449 }
9450 }
9451 }
9452
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009453 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9454 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9455 const Type *SrcPTy = SrcTy->getElementType();
9456
9457 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9458 isa<VectorType>(DestPTy)) {
9459 // If the source is an array, the code below will not succeed. Check to
9460 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9461 // constants.
9462 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9463 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9464 if (ASrcTy->getNumElements() != 0) {
9465 Value *Idxs[2];
9466 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9467 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9468 SrcTy = cast<PointerType>(CastOp->getType());
9469 SrcPTy = SrcTy->getElementType();
9470 }
9471
9472 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9473 isa<VectorType>(SrcPTy)) &&
9474 // Do not allow turning this into a load of an integer, which is then
9475 // casted to a pointer, this pessimizes pointer analysis a lot.
9476 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9477 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9478 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9479
9480 // Okay, we are casting from one integer or pointer type to another of
9481 // the same size. Instead of casting the pointer before the load, cast
9482 // the result of the loaded value.
9483 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9484 CI->getName(),
9485 LI.isVolatile()),LI);
9486 // Now cast the result of the load.
9487 return new BitCastInst(NewLoad, LI.getType());
9488 }
9489 }
9490 }
9491 return 0;
9492}
9493
9494/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9495/// from this value cannot trap. If it is not obviously safe to load from the
9496/// specified pointer, we do a quick local scan of the basic block containing
9497/// ScanFrom, to determine if the address is already accessed.
9498static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009499 // If it is an alloca it is always safe to load from.
9500 if (isa<AllocaInst>(V)) return true;
9501
Duncan Sandse40a94a2007-09-19 10:25:38 +00009502 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009503 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009504 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009505 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009506
9507 // Otherwise, be a little bit agressive by scanning the local block where we
9508 // want to check to see if the pointer is already being loaded or stored
9509 // from/to. If so, the previous load or store would have already trapped,
9510 // so there is no harm doing an extra load (also, CSE will later eliminate
9511 // the load entirely).
9512 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9513
9514 while (BBI != E) {
9515 --BBI;
9516
9517 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9518 if (LI->getOperand(0) == V) return true;
9519 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9520 if (SI->getOperand(1) == V) return true;
9521
9522 }
9523 return false;
9524}
9525
Chris Lattner0270a112007-08-11 18:48:48 +00009526/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9527/// until we find the underlying object a pointer is referring to or something
9528/// we don't understand. Note that the returned pointer may be offset from the
9529/// input, because we ignore GEP indices.
9530static Value *GetUnderlyingObject(Value *Ptr) {
9531 while (1) {
9532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9533 if (CE->getOpcode() == Instruction::BitCast ||
9534 CE->getOpcode() == Instruction::GetElementPtr)
9535 Ptr = CE->getOperand(0);
9536 else
9537 return Ptr;
9538 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9539 Ptr = BCI->getOperand(0);
9540 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9541 Ptr = GEP->getOperand(0);
9542 } else {
9543 return Ptr;
9544 }
9545 }
9546}
9547
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9549 Value *Op = LI.getOperand(0);
9550
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009551 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009552 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009553 if (KnownAlign > LI.getAlignment())
9554 LI.setAlignment(KnownAlign);
9555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009556 // load (cast X) --> cast (load X) iff safe
9557 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009558 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009559 return Res;
9560
9561 // None of the following transforms are legal for volatile loads.
9562 if (LI.isVolatile()) return 0;
9563
9564 if (&LI.getParent()->front() != &LI) {
9565 BasicBlock::iterator BBI = &LI; --BBI;
9566 // If the instruction immediately before this is a store to the same
9567 // address, do a simple form of store->load forwarding.
9568 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9569 if (SI->getOperand(1) == LI.getOperand(0))
9570 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9571 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9572 if (LIB->getOperand(0) == LI.getOperand(0))
9573 return ReplaceInstUsesWith(LI, LIB);
9574 }
9575
Christopher Lamb2c175392007-12-29 07:56:53 +00009576 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9577 const Value *GEPI0 = GEPI->getOperand(0);
9578 // TODO: Consider a target hook for valid address spaces for this xform.
9579 if (isa<ConstantPointerNull>(GEPI0) &&
9580 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009581 // Insert a new store to null instruction before the load to indicate
9582 // that this code is not reachable. We do this instead of inserting
9583 // an unreachable instruction directly because we cannot modify the
9584 // CFG.
9585 new StoreInst(UndefValue::get(LI.getType()),
9586 Constant::getNullValue(Op->getType()), &LI);
9587 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9588 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009589 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009590
9591 if (Constant *C = dyn_cast<Constant>(Op)) {
9592 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009593 // TODO: Consider a target hook for valid address spaces for this xform.
9594 if (isa<UndefValue>(C) || (C->isNullValue() &&
9595 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009596 // Insert a new store to null instruction before the load to indicate that
9597 // this code is not reachable. We do this instead of inserting an
9598 // unreachable instruction directly because we cannot modify the CFG.
9599 new StoreInst(UndefValue::get(LI.getType()),
9600 Constant::getNullValue(Op->getType()), &LI);
9601 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9602 }
9603
9604 // Instcombine load (constant global) into the value loaded.
9605 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9606 if (GV->isConstant() && !GV->isDeclaration())
9607 return ReplaceInstUsesWith(LI, GV->getInitializer());
9608
9609 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9611 if (CE->getOpcode() == Instruction::GetElementPtr) {
9612 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9613 if (GV->isConstant() && !GV->isDeclaration())
9614 if (Constant *V =
9615 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9616 return ReplaceInstUsesWith(LI, V);
9617 if (CE->getOperand(0)->isNullValue()) {
9618 // Insert a new store to null instruction before the load to indicate
9619 // that this code is not reachable. We do this instead of inserting
9620 // an unreachable instruction directly because we cannot modify the
9621 // CFG.
9622 new StoreInst(UndefValue::get(LI.getType()),
9623 Constant::getNullValue(Op->getType()), &LI);
9624 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9625 }
9626
9627 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009628 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009629 return Res;
9630 }
9631 }
Chris Lattner0270a112007-08-11 18:48:48 +00009632
9633 // If this load comes from anywhere in a constant global, and if the global
9634 // is all undef or zero, we know what it loads.
9635 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9636 if (GV->isConstant() && GV->hasInitializer()) {
9637 if (GV->getInitializer()->isNullValue())
9638 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9639 else if (isa<UndefValue>(GV->getInitializer()))
9640 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9641 }
9642 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009643
9644 if (Op->hasOneUse()) {
9645 // Change select and PHI nodes to select values instead of addresses: this
9646 // helps alias analysis out a lot, allows many others simplifications, and
9647 // exposes redundancy in the code.
9648 //
9649 // Note that we cannot do the transformation unless we know that the
9650 // introduced loads cannot trap! Something like this is valid as long as
9651 // the condition is always false: load (select bool %C, int* null, int* %G),
9652 // but it would not be valid if we transformed it to load from null
9653 // unconditionally.
9654 //
9655 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9656 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9657 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9658 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9659 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9660 SI->getOperand(1)->getName()+".val"), LI);
9661 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9662 SI->getOperand(2)->getName()+".val"), LI);
9663 return new SelectInst(SI->getCondition(), V1, V2);
9664 }
9665
9666 // load (select (cond, null, P)) -> load P
9667 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9668 if (C->isNullValue()) {
9669 LI.setOperand(0, SI->getOperand(2));
9670 return &LI;
9671 }
9672
9673 // load (select (cond, P, null)) -> load P
9674 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9675 if (C->isNullValue()) {
9676 LI.setOperand(0, SI->getOperand(1));
9677 return &LI;
9678 }
9679 }
9680 }
9681 return 0;
9682}
9683
9684/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9685/// when possible.
9686static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9687 User *CI = cast<User>(SI.getOperand(1));
9688 Value *CastOp = CI->getOperand(0);
9689
9690 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9691 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9692 const Type *SrcPTy = SrcTy->getElementType();
9693
9694 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9695 // If the source is an array, the code below will not succeed. Check to
9696 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9697 // constants.
9698 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9699 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9700 if (ASrcTy->getNumElements() != 0) {
9701 Value* Idxs[2];
9702 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9703 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9704 SrcTy = cast<PointerType>(CastOp->getType());
9705 SrcPTy = SrcTy->getElementType();
9706 }
9707
9708 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9709 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9710 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9711
9712 // Okay, we are casting from one integer or pointer type to another of
9713 // the same size. Instead of casting the pointer before
9714 // the store, cast the value to be stored.
9715 Value *NewCast;
9716 Value *SIOp0 = SI.getOperand(0);
9717 Instruction::CastOps opcode = Instruction::BitCast;
9718 const Type* CastSrcTy = SIOp0->getType();
9719 const Type* CastDstTy = SrcPTy;
9720 if (isa<PointerType>(CastDstTy)) {
9721 if (CastSrcTy->isInteger())
9722 opcode = Instruction::IntToPtr;
9723 } else if (isa<IntegerType>(CastDstTy)) {
9724 if (isa<PointerType>(SIOp0->getType()))
9725 opcode = Instruction::PtrToInt;
9726 }
9727 if (Constant *C = dyn_cast<Constant>(SIOp0))
9728 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9729 else
9730 NewCast = IC.InsertNewInstBefore(
9731 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9732 SI);
9733 return new StoreInst(NewCast, CastOp);
9734 }
9735 }
9736 }
9737 return 0;
9738}
9739
9740Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9741 Value *Val = SI.getOperand(0);
9742 Value *Ptr = SI.getOperand(1);
9743
9744 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9745 EraseInstFromFunction(SI);
9746 ++NumCombined;
9747 return 0;
9748 }
9749
9750 // If the RHS is an alloca with a single use, zapify the store, making the
9751 // alloca dead.
9752 if (Ptr->hasOneUse()) {
9753 if (isa<AllocaInst>(Ptr)) {
9754 EraseInstFromFunction(SI);
9755 ++NumCombined;
9756 return 0;
9757 }
9758
9759 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9760 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9761 GEP->getOperand(0)->hasOneUse()) {
9762 EraseInstFromFunction(SI);
9763 ++NumCombined;
9764 return 0;
9765 }
9766 }
9767
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009768 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009769 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009770 if (KnownAlign > SI.getAlignment())
9771 SI.setAlignment(KnownAlign);
9772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009773 // Do really simple DSE, to catch cases where there are several consequtive
9774 // stores to the same location, separated by a few arithmetic operations. This
9775 // situation often occurs with bitfield accesses.
9776 BasicBlock::iterator BBI = &SI;
9777 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9778 --ScanInsts) {
9779 --BBI;
9780
9781 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9782 // Prev store isn't volatile, and stores to the same location?
9783 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9784 ++NumDeadStore;
9785 ++BBI;
9786 EraseInstFromFunction(*PrevSI);
9787 continue;
9788 }
9789 break;
9790 }
9791
9792 // If this is a load, we have to stop. However, if the loaded value is from
9793 // the pointer we're loading and is producing the pointer we're storing,
9794 // then *this* store is dead (X = load P; store X -> P).
9795 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009796 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009797 EraseInstFromFunction(SI);
9798 ++NumCombined;
9799 return 0;
9800 }
9801 // Otherwise, this is a load from some other location. Stores before it
9802 // may not be dead.
9803 break;
9804 }
9805
9806 // Don't skip over loads or things that can modify memory.
9807 if (BBI->mayWriteToMemory())
9808 break;
9809 }
9810
9811
9812 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9813
9814 // store X, null -> turns into 'unreachable' in SimplifyCFG
9815 if (isa<ConstantPointerNull>(Ptr)) {
9816 if (!isa<UndefValue>(Val)) {
9817 SI.setOperand(0, UndefValue::get(Val->getType()));
9818 if (Instruction *U = dyn_cast<Instruction>(Val))
9819 AddToWorkList(U); // Dropped a use.
9820 ++NumCombined;
9821 }
9822 return 0; // Do not modify these!
9823 }
9824
9825 // store undef, Ptr -> noop
9826 if (isa<UndefValue>(Val)) {
9827 EraseInstFromFunction(SI);
9828 ++NumCombined;
9829 return 0;
9830 }
9831
9832 // If the pointer destination is a cast, see if we can fold the cast into the
9833 // source instead.
9834 if (isa<CastInst>(Ptr))
9835 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9836 return Res;
9837 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9838 if (CE->isCast())
9839 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9840 return Res;
9841
9842
9843 // If this store is the last instruction in the basic block, and if the block
9844 // ends with an unconditional branch, try to move it to the successor block.
9845 BBI = &SI; ++BBI;
9846 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9847 if (BI->isUnconditional())
9848 if (SimplifyStoreAtEndOfBlock(SI))
9849 return 0; // xform done!
9850
9851 return 0;
9852}
9853
9854/// SimplifyStoreAtEndOfBlock - Turn things like:
9855/// if () { *P = v1; } else { *P = v2 }
9856/// into a phi node with a store in the successor.
9857///
9858/// Simplify things like:
9859/// *P = v1; if () { *P = v2; }
9860/// into a phi node with a store in the successor.
9861///
9862bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9863 BasicBlock *StoreBB = SI.getParent();
9864
9865 // Check to see if the successor block has exactly two incoming edges. If
9866 // so, see if the other predecessor contains a store to the same location.
9867 // if so, insert a PHI node (if needed) and move the stores down.
9868 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9869
9870 // Determine whether Dest has exactly two predecessors and, if so, compute
9871 // the other predecessor.
9872 pred_iterator PI = pred_begin(DestBB);
9873 BasicBlock *OtherBB = 0;
9874 if (*PI != StoreBB)
9875 OtherBB = *PI;
9876 ++PI;
9877 if (PI == pred_end(DestBB))
9878 return false;
9879
9880 if (*PI != StoreBB) {
9881 if (OtherBB)
9882 return false;
9883 OtherBB = *PI;
9884 }
9885 if (++PI != pred_end(DestBB))
9886 return false;
9887
9888
9889 // Verify that the other block ends in a branch and is not otherwise empty.
9890 BasicBlock::iterator BBI = OtherBB->getTerminator();
9891 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9892 if (!OtherBr || BBI == OtherBB->begin())
9893 return false;
9894
9895 // If the other block ends in an unconditional branch, check for the 'if then
9896 // else' case. there is an instruction before the branch.
9897 StoreInst *OtherStore = 0;
9898 if (OtherBr->isUnconditional()) {
9899 // If this isn't a store, or isn't a store to the same location, bail out.
9900 --BBI;
9901 OtherStore = dyn_cast<StoreInst>(BBI);
9902 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9903 return false;
9904 } else {
9905 // Otherwise, the other block ended with a conditional branch. If one of the
9906 // destinations is StoreBB, then we have the if/then case.
9907 if (OtherBr->getSuccessor(0) != StoreBB &&
9908 OtherBr->getSuccessor(1) != StoreBB)
9909 return false;
9910
9911 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9912 // if/then triangle. See if there is a store to the same ptr as SI that
9913 // lives in OtherBB.
9914 for (;; --BBI) {
9915 // Check to see if we find the matching store.
9916 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9917 if (OtherStore->getOperand(1) != SI.getOperand(1))
9918 return false;
9919 break;
9920 }
9921 // If we find something that may be using the stored value, or if we run
9922 // out of instructions, we can't do the xform.
9923 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9924 BBI == OtherBB->begin())
9925 return false;
9926 }
9927
9928 // In order to eliminate the store in OtherBr, we have to
9929 // make sure nothing reads the stored value in StoreBB.
9930 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9931 // FIXME: This should really be AA driven.
9932 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9933 return false;
9934 }
9935 }
9936
9937 // Insert a PHI node now if we need it.
9938 Value *MergedVal = OtherStore->getOperand(0);
9939 if (MergedVal != SI.getOperand(0)) {
9940 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9941 PN->reserveOperandSpace(2);
9942 PN->addIncoming(SI.getOperand(0), SI.getParent());
9943 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9944 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9945 }
9946
9947 // Advance to a place where it is safe to insert the new store and
9948 // insert it.
9949 BBI = DestBB->begin();
9950 while (isa<PHINode>(BBI)) ++BBI;
9951 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9952 OtherStore->isVolatile()), *BBI);
9953
9954 // Nuke the old stores.
9955 EraseInstFromFunction(SI);
9956 EraseInstFromFunction(*OtherStore);
9957 ++NumCombined;
9958 return true;
9959}
9960
9961
9962Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9963 // Change br (not X), label True, label False to: br X, label False, True
9964 Value *X = 0;
9965 BasicBlock *TrueDest;
9966 BasicBlock *FalseDest;
9967 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9968 !isa<Constant>(X)) {
9969 // Swap Destinations and condition...
9970 BI.setCondition(X);
9971 BI.setSuccessor(0, FalseDest);
9972 BI.setSuccessor(1, TrueDest);
9973 return &BI;
9974 }
9975
9976 // Cannonicalize fcmp_one -> fcmp_oeq
9977 FCmpInst::Predicate FPred; Value *Y;
9978 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9979 TrueDest, FalseDest)))
9980 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9981 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9982 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9983 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9984 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9985 NewSCC->takeName(I);
9986 // Swap Destinations and condition...
9987 BI.setCondition(NewSCC);
9988 BI.setSuccessor(0, FalseDest);
9989 BI.setSuccessor(1, TrueDest);
9990 RemoveFromWorkList(I);
9991 I->eraseFromParent();
9992 AddToWorkList(NewSCC);
9993 return &BI;
9994 }
9995
9996 // Cannonicalize icmp_ne -> icmp_eq
9997 ICmpInst::Predicate IPred;
9998 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9999 TrueDest, FalseDest)))
10000 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10001 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10002 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10003 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10004 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10005 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10006 NewSCC->takeName(I);
10007 // Swap Destinations and condition...
10008 BI.setCondition(NewSCC);
10009 BI.setSuccessor(0, FalseDest);
10010 BI.setSuccessor(1, TrueDest);
10011 RemoveFromWorkList(I);
10012 I->eraseFromParent();;
10013 AddToWorkList(NewSCC);
10014 return &BI;
10015 }
10016
10017 return 0;
10018}
10019
10020Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10021 Value *Cond = SI.getCondition();
10022 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10023 if (I->getOpcode() == Instruction::Add)
10024 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10025 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10026 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10027 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10028 AddRHS));
10029 SI.setOperand(0, I->getOperand(0));
10030 AddToWorkList(I);
10031 return &SI;
10032 }
10033 }
10034 return 0;
10035}
10036
10037/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10038/// is to leave as a vector operation.
10039static bool CheapToScalarize(Value *V, bool isConstant) {
10040 if (isa<ConstantAggregateZero>(V))
10041 return true;
10042 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10043 if (isConstant) return true;
10044 // If all elts are the same, we can extract.
10045 Constant *Op0 = C->getOperand(0);
10046 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10047 if (C->getOperand(i) != Op0)
10048 return false;
10049 return true;
10050 }
10051 Instruction *I = dyn_cast<Instruction>(V);
10052 if (!I) return false;
10053
10054 // Insert element gets simplified to the inserted element or is deleted if
10055 // this is constant idx extract element and its a constant idx insertelt.
10056 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10057 isa<ConstantInt>(I->getOperand(2)))
10058 return true;
10059 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10060 return true;
10061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10062 if (BO->hasOneUse() &&
10063 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10064 CheapToScalarize(BO->getOperand(1), isConstant)))
10065 return true;
10066 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10067 if (CI->hasOneUse() &&
10068 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10069 CheapToScalarize(CI->getOperand(1), isConstant)))
10070 return true;
10071
10072 return false;
10073}
10074
10075/// Read and decode a shufflevector mask.
10076///
10077/// It turns undef elements into values that are larger than the number of
10078/// elements in the input.
10079static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10080 unsigned NElts = SVI->getType()->getNumElements();
10081 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10082 return std::vector<unsigned>(NElts, 0);
10083 if (isa<UndefValue>(SVI->getOperand(2)))
10084 return std::vector<unsigned>(NElts, 2*NElts);
10085
10086 std::vector<unsigned> Result;
10087 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10088 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10089 if (isa<UndefValue>(CP->getOperand(i)))
10090 Result.push_back(NElts*2); // undef -> 8
10091 else
10092 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10093 return Result;
10094}
10095
10096/// FindScalarElement - Given a vector and an element number, see if the scalar
10097/// value is already around as a register, for example if it were inserted then
10098/// extracted from the vector.
10099static Value *FindScalarElement(Value *V, unsigned EltNo) {
10100 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10101 const VectorType *PTy = cast<VectorType>(V->getType());
10102 unsigned Width = PTy->getNumElements();
10103 if (EltNo >= Width) // Out of range access.
10104 return UndefValue::get(PTy->getElementType());
10105
10106 if (isa<UndefValue>(V))
10107 return UndefValue::get(PTy->getElementType());
10108 else if (isa<ConstantAggregateZero>(V))
10109 return Constant::getNullValue(PTy->getElementType());
10110 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10111 return CP->getOperand(EltNo);
10112 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10113 // If this is an insert to a variable element, we don't know what it is.
10114 if (!isa<ConstantInt>(III->getOperand(2)))
10115 return 0;
10116 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10117
10118 // If this is an insert to the element we are looking for, return the
10119 // inserted value.
10120 if (EltNo == IIElt)
10121 return III->getOperand(1);
10122
10123 // Otherwise, the insertelement doesn't modify the value, recurse on its
10124 // vector input.
10125 return FindScalarElement(III->getOperand(0), EltNo);
10126 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10127 unsigned InEl = getShuffleMask(SVI)[EltNo];
10128 if (InEl < Width)
10129 return FindScalarElement(SVI->getOperand(0), InEl);
10130 else if (InEl < Width*2)
10131 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10132 else
10133 return UndefValue::get(PTy->getElementType());
10134 }
10135
10136 // Otherwise, we don't know.
10137 return 0;
10138}
10139
10140Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10141
10142 // If vector val is undef, replace extract with scalar undef.
10143 if (isa<UndefValue>(EI.getOperand(0)))
10144 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10145
10146 // If vector val is constant 0, replace extract with scalar 0.
10147 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10148 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10149
10150 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10151 // If vector val is constant with uniform operands, replace EI
10152 // with that operand
10153 Constant *op0 = C->getOperand(0);
10154 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10155 if (C->getOperand(i) != op0) {
10156 op0 = 0;
10157 break;
10158 }
10159 if (op0)
10160 return ReplaceInstUsesWith(EI, op0);
10161 }
10162
10163 // If extracting a specified index from the vector, see if we can recursively
10164 // find a previously computed scalar that was inserted into the vector.
10165 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10166 unsigned IndexVal = IdxC->getZExtValue();
10167 unsigned VectorWidth =
10168 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10169
10170 // If this is extracting an invalid index, turn this into undef, to avoid
10171 // crashing the code below.
10172 if (IndexVal >= VectorWidth)
10173 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10174
10175 // This instruction only demands the single element from the input vector.
10176 // If the input vector has a single use, simplify it based on this use
10177 // property.
10178 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10179 uint64_t UndefElts;
10180 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10181 1 << IndexVal,
10182 UndefElts)) {
10183 EI.setOperand(0, V);
10184 return &EI;
10185 }
10186 }
10187
10188 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10189 return ReplaceInstUsesWith(EI, Elt);
10190
10191 // If the this extractelement is directly using a bitcast from a vector of
10192 // the same number of elements, see if we can find the source element from
10193 // it. In this case, we will end up needing to bitcast the scalars.
10194 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10195 if (const VectorType *VT =
10196 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10197 if (VT->getNumElements() == VectorWidth)
10198 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10199 return new BitCastInst(Elt, EI.getType());
10200 }
10201 }
10202
10203 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10204 if (I->hasOneUse()) {
10205 // Push extractelement into predecessor operation if legal and
10206 // profitable to do so
10207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10208 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10209 if (CheapToScalarize(BO, isConstantElt)) {
10210 ExtractElementInst *newEI0 =
10211 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10212 EI.getName()+".lhs");
10213 ExtractElementInst *newEI1 =
10214 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10215 EI.getName()+".rhs");
10216 InsertNewInstBefore(newEI0, EI);
10217 InsertNewInstBefore(newEI1, EI);
10218 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10219 }
10220 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010221 unsigned AS =
10222 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010223 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10224 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010225 GetElementPtrInst *GEP =
10226 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10227 InsertNewInstBefore(GEP, EI);
10228 return new LoadInst(GEP);
10229 }
10230 }
10231 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10232 // Extracting the inserted element?
10233 if (IE->getOperand(2) == EI.getOperand(1))
10234 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10235 // If the inserted and extracted elements are constants, they must not
10236 // be the same value, extract from the pre-inserted value instead.
10237 if (isa<Constant>(IE->getOperand(2)) &&
10238 isa<Constant>(EI.getOperand(1))) {
10239 AddUsesToWorkList(EI);
10240 EI.setOperand(0, IE->getOperand(0));
10241 return &EI;
10242 }
10243 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10244 // If this is extracting an element from a shufflevector, figure out where
10245 // it came from and extract from the appropriate input element instead.
10246 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10247 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10248 Value *Src;
10249 if (SrcIdx < SVI->getType()->getNumElements())
10250 Src = SVI->getOperand(0);
10251 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10252 SrcIdx -= SVI->getType()->getNumElements();
10253 Src = SVI->getOperand(1);
10254 } else {
10255 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10256 }
10257 return new ExtractElementInst(Src, SrcIdx);
10258 }
10259 }
10260 }
10261 return 0;
10262}
10263
10264/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10265/// elements from either LHS or RHS, return the shuffle mask and true.
10266/// Otherwise, return false.
10267static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10268 std::vector<Constant*> &Mask) {
10269 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10270 "Invalid CollectSingleShuffleElements");
10271 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10272
10273 if (isa<UndefValue>(V)) {
10274 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10275 return true;
10276 } else if (V == LHS) {
10277 for (unsigned i = 0; i != NumElts; ++i)
10278 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10279 return true;
10280 } else if (V == RHS) {
10281 for (unsigned i = 0; i != NumElts; ++i)
10282 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10283 return true;
10284 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10285 // If this is an insert of an extract from some other vector, include it.
10286 Value *VecOp = IEI->getOperand(0);
10287 Value *ScalarOp = IEI->getOperand(1);
10288 Value *IdxOp = IEI->getOperand(2);
10289
10290 if (!isa<ConstantInt>(IdxOp))
10291 return false;
10292 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10293
10294 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10295 // Okay, we can handle this if the vector we are insertinting into is
10296 // transitively ok.
10297 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10298 // If so, update the mask to reflect the inserted undef.
10299 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10300 return true;
10301 }
10302 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10303 if (isa<ConstantInt>(EI->getOperand(1)) &&
10304 EI->getOperand(0)->getType() == V->getType()) {
10305 unsigned ExtractedIdx =
10306 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10307
10308 // This must be extracting from either LHS or RHS.
10309 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10310 // Okay, we can handle this if the vector we are insertinting into is
10311 // transitively ok.
10312 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10313 // If so, update the mask to reflect the inserted value.
10314 if (EI->getOperand(0) == LHS) {
10315 Mask[InsertedIdx & (NumElts-1)] =
10316 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10317 } else {
10318 assert(EI->getOperand(0) == RHS);
10319 Mask[InsertedIdx & (NumElts-1)] =
10320 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10321
10322 }
10323 return true;
10324 }
10325 }
10326 }
10327 }
10328 }
10329 // TODO: Handle shufflevector here!
10330
10331 return false;
10332}
10333
10334/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10335/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10336/// that computes V and the LHS value of the shuffle.
10337static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10338 Value *&RHS) {
10339 assert(isa<VectorType>(V->getType()) &&
10340 (RHS == 0 || V->getType() == RHS->getType()) &&
10341 "Invalid shuffle!");
10342 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10343
10344 if (isa<UndefValue>(V)) {
10345 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10346 return V;
10347 } else if (isa<ConstantAggregateZero>(V)) {
10348 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10349 return V;
10350 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10351 // If this is an insert of an extract from some other vector, include it.
10352 Value *VecOp = IEI->getOperand(0);
10353 Value *ScalarOp = IEI->getOperand(1);
10354 Value *IdxOp = IEI->getOperand(2);
10355
10356 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10357 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10358 EI->getOperand(0)->getType() == V->getType()) {
10359 unsigned ExtractedIdx =
10360 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10361 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10362
10363 // Either the extracted from or inserted into vector must be RHSVec,
10364 // otherwise we'd end up with a shuffle of three inputs.
10365 if (EI->getOperand(0) == RHS || RHS == 0) {
10366 RHS = EI->getOperand(0);
10367 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10368 Mask[InsertedIdx & (NumElts-1)] =
10369 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10370 return V;
10371 }
10372
10373 if (VecOp == RHS) {
10374 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10375 // Everything but the extracted element is replaced with the RHS.
10376 for (unsigned i = 0; i != NumElts; ++i) {
10377 if (i != InsertedIdx)
10378 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10379 }
10380 return V;
10381 }
10382
10383 // If this insertelement is a chain that comes from exactly these two
10384 // vectors, return the vector and the effective shuffle.
10385 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10386 return EI->getOperand(0);
10387
10388 }
10389 }
10390 }
10391 // TODO: Handle shufflevector here!
10392
10393 // Otherwise, can't do anything fancy. Return an identity vector.
10394 for (unsigned i = 0; i != NumElts; ++i)
10395 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10396 return V;
10397}
10398
10399Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10400 Value *VecOp = IE.getOperand(0);
10401 Value *ScalarOp = IE.getOperand(1);
10402 Value *IdxOp = IE.getOperand(2);
10403
10404 // Inserting an undef or into an undefined place, remove this.
10405 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10406 ReplaceInstUsesWith(IE, VecOp);
10407
10408 // If the inserted element was extracted from some other vector, and if the
10409 // indexes are constant, try to turn this into a shufflevector operation.
10410 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10411 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10412 EI->getOperand(0)->getType() == IE.getType()) {
10413 unsigned NumVectorElts = IE.getType()->getNumElements();
10414 unsigned ExtractedIdx =
10415 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10416 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10417
10418 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10419 return ReplaceInstUsesWith(IE, VecOp);
10420
10421 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10422 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10423
10424 // If we are extracting a value from a vector, then inserting it right
10425 // back into the same place, just use the input vector.
10426 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10427 return ReplaceInstUsesWith(IE, VecOp);
10428
10429 // We could theoretically do this for ANY input. However, doing so could
10430 // turn chains of insertelement instructions into a chain of shufflevector
10431 // instructions, and right now we do not merge shufflevectors. As such,
10432 // only do this in a situation where it is clear that there is benefit.
10433 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10434 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10435 // the values of VecOp, except then one read from EIOp0.
10436 // Build a new shuffle mask.
10437 std::vector<Constant*> Mask;
10438 if (isa<UndefValue>(VecOp))
10439 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10440 else {
10441 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10442 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10443 NumVectorElts));
10444 }
10445 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10446 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10447 ConstantVector::get(Mask));
10448 }
10449
10450 // If this insertelement isn't used by some other insertelement, turn it
10451 // (and any insertelements it points to), into one big shuffle.
10452 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10453 std::vector<Constant*> Mask;
10454 Value *RHS = 0;
10455 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10456 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10457 // We now have a shuffle of LHS, RHS, Mask.
10458 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10459 }
10460 }
10461 }
10462
10463 return 0;
10464}
10465
10466
10467Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10468 Value *LHS = SVI.getOperand(0);
10469 Value *RHS = SVI.getOperand(1);
10470 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10471
10472 bool MadeChange = false;
10473
10474 // Undefined shuffle mask -> undefined value.
10475 if (isa<UndefValue>(SVI.getOperand(2)))
10476 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10477
10478 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10479 // the undef, change them to undefs.
10480 if (isa<UndefValue>(SVI.getOperand(1))) {
10481 // Scan to see if there are any references to the RHS. If so, replace them
10482 // with undef element refs and set MadeChange to true.
10483 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10484 if (Mask[i] >= e && Mask[i] != 2*e) {
10485 Mask[i] = 2*e;
10486 MadeChange = true;
10487 }
10488 }
10489
10490 if (MadeChange) {
10491 // Remap any references to RHS to use LHS.
10492 std::vector<Constant*> Elts;
10493 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10494 if (Mask[i] == 2*e)
10495 Elts.push_back(UndefValue::get(Type::Int32Ty));
10496 else
10497 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10498 }
10499 SVI.setOperand(2, ConstantVector::get(Elts));
10500 }
10501 }
10502
10503 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10504 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10505 if (LHS == RHS || isa<UndefValue>(LHS)) {
10506 if (isa<UndefValue>(LHS) && LHS == RHS) {
10507 // shuffle(undef,undef,mask) -> undef.
10508 return ReplaceInstUsesWith(SVI, LHS);
10509 }
10510
10511 // Remap any references to RHS to use LHS.
10512 std::vector<Constant*> Elts;
10513 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10514 if (Mask[i] >= 2*e)
10515 Elts.push_back(UndefValue::get(Type::Int32Ty));
10516 else {
10517 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10518 (Mask[i] < e && isa<UndefValue>(LHS)))
10519 Mask[i] = 2*e; // Turn into undef.
10520 else
10521 Mask[i] &= (e-1); // Force to LHS.
10522 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10523 }
10524 }
10525 SVI.setOperand(0, SVI.getOperand(1));
10526 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10527 SVI.setOperand(2, ConstantVector::get(Elts));
10528 LHS = SVI.getOperand(0);
10529 RHS = SVI.getOperand(1);
10530 MadeChange = true;
10531 }
10532
10533 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10534 bool isLHSID = true, isRHSID = true;
10535
10536 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10537 if (Mask[i] >= e*2) continue; // Ignore undef values.
10538 // Is this an identity shuffle of the LHS value?
10539 isLHSID &= (Mask[i] == i);
10540
10541 // Is this an identity shuffle of the RHS value?
10542 isRHSID &= (Mask[i]-e == i);
10543 }
10544
10545 // Eliminate identity shuffles.
10546 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10547 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10548
10549 // If the LHS is a shufflevector itself, see if we can combine it with this
10550 // one without producing an unusual shuffle. Here we are really conservative:
10551 // we are absolutely afraid of producing a shuffle mask not in the input
10552 // program, because the code gen may not be smart enough to turn a merged
10553 // shuffle into two specific shuffles: it may produce worse code. As such,
10554 // we only merge two shuffles if the result is one of the two input shuffle
10555 // masks. In this case, merging the shuffles just removes one instruction,
10556 // which we know is safe. This is good for things like turning:
10557 // (splat(splat)) -> splat.
10558 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10559 if (isa<UndefValue>(RHS)) {
10560 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10561
10562 std::vector<unsigned> NewMask;
10563 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10564 if (Mask[i] >= 2*e)
10565 NewMask.push_back(2*e);
10566 else
10567 NewMask.push_back(LHSMask[Mask[i]]);
10568
10569 // If the result mask is equal to the src shuffle or this shuffle mask, do
10570 // the replacement.
10571 if (NewMask == LHSMask || NewMask == Mask) {
10572 std::vector<Constant*> Elts;
10573 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10574 if (NewMask[i] >= e*2) {
10575 Elts.push_back(UndefValue::get(Type::Int32Ty));
10576 } else {
10577 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10578 }
10579 }
10580 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10581 LHSSVI->getOperand(1),
10582 ConstantVector::get(Elts));
10583 }
10584 }
10585 }
10586
10587 return MadeChange ? &SVI : 0;
10588}
10589
10590
10591
10592
10593/// TryToSinkInstruction - Try to move the specified instruction from its
10594/// current block into the beginning of DestBlock, which can only happen if it's
10595/// safe to move the instruction past all of the instructions between it and the
10596/// end of its block.
10597static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10598 assert(I->hasOneUse() && "Invariants didn't hold!");
10599
10600 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10601 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10602
10603 // Do not sink alloca instructions out of the entry block.
10604 if (isa<AllocaInst>(I) && I->getParent() ==
10605 &DestBlock->getParent()->getEntryBlock())
10606 return false;
10607
10608 // We can only sink load instructions if there is nothing between the load and
10609 // the end of block that could change the value.
10610 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10611 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10612 Scan != E; ++Scan)
10613 if (Scan->mayWriteToMemory())
10614 return false;
10615 }
10616
10617 BasicBlock::iterator InsertPos = DestBlock->begin();
10618 while (isa<PHINode>(InsertPos)) ++InsertPos;
10619
10620 I->moveBefore(InsertPos);
10621 ++NumSunkInst;
10622 return true;
10623}
10624
10625
10626/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10627/// all reachable code to the worklist.
10628///
10629/// This has a couple of tricks to make the code faster and more powerful. In
10630/// particular, we constant fold and DCE instructions as we go, to avoid adding
10631/// them to the worklist (this significantly speeds up instcombine on code where
10632/// many instructions are dead or constant). Additionally, if we find a branch
10633/// whose condition is a known constant, we only visit the reachable successors.
10634///
10635static void AddReachableCodeToWorklist(BasicBlock *BB,
10636 SmallPtrSet<BasicBlock*, 64> &Visited,
10637 InstCombiner &IC,
10638 const TargetData *TD) {
10639 std::vector<BasicBlock*> Worklist;
10640 Worklist.push_back(BB);
10641
10642 while (!Worklist.empty()) {
10643 BB = Worklist.back();
10644 Worklist.pop_back();
10645
10646 // We have now visited this block! If we've already been here, ignore it.
10647 if (!Visited.insert(BB)) continue;
10648
10649 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10650 Instruction *Inst = BBI++;
10651
10652 // DCE instruction if trivially dead.
10653 if (isInstructionTriviallyDead(Inst)) {
10654 ++NumDeadInst;
10655 DOUT << "IC: DCE: " << *Inst;
10656 Inst->eraseFromParent();
10657 continue;
10658 }
10659
10660 // ConstantProp instruction if trivially constant.
10661 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10662 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10663 Inst->replaceAllUsesWith(C);
10664 ++NumConstProp;
10665 Inst->eraseFromParent();
10666 continue;
10667 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010668
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010669 IC.AddToWorkList(Inst);
10670 }
10671
10672 // Recursively visit successors. If this is a branch or switch on a
10673 // constant, only visit the reachable successor.
10674 TerminatorInst *TI = BB->getTerminator();
10675 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10676 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10677 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10678 Worklist.push_back(BI->getSuccessor(!CondVal));
10679 continue;
10680 }
10681 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10682 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10683 // See if this is an explicit destination.
10684 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10685 if (SI->getCaseValue(i) == Cond) {
10686 Worklist.push_back(SI->getSuccessor(i));
10687 continue;
10688 }
10689
10690 // Otherwise it is the default destination.
10691 Worklist.push_back(SI->getSuccessor(0));
10692 continue;
10693 }
10694 }
10695
10696 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10697 Worklist.push_back(TI->getSuccessor(i));
10698 }
10699}
10700
10701bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10702 bool Changed = false;
10703 TD = &getAnalysis<TargetData>();
10704
10705 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10706 << F.getNameStr() << "\n");
10707
10708 {
10709 // Do a depth-first traversal of the function, populate the worklist with
10710 // the reachable instructions. Ignore blocks that are not reachable. Keep
10711 // track of which blocks we visit.
10712 SmallPtrSet<BasicBlock*, 64> Visited;
10713 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10714
10715 // Do a quick scan over the function. If we find any blocks that are
10716 // unreachable, remove any instructions inside of them. This prevents
10717 // the instcombine code from having to deal with some bad special cases.
10718 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10719 if (!Visited.count(BB)) {
10720 Instruction *Term = BB->getTerminator();
10721 while (Term != BB->begin()) { // Remove instrs bottom-up
10722 BasicBlock::iterator I = Term; --I;
10723
10724 DOUT << "IC: DCE: " << *I;
10725 ++NumDeadInst;
10726
10727 if (!I->use_empty())
10728 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10729 I->eraseFromParent();
10730 }
10731 }
10732 }
10733
10734 while (!Worklist.empty()) {
10735 Instruction *I = RemoveOneFromWorkList();
10736 if (I == 0) continue; // skip null values.
10737
10738 // Check to see if we can DCE the instruction.
10739 if (isInstructionTriviallyDead(I)) {
10740 // Add operands to the worklist.
10741 if (I->getNumOperands() < 4)
10742 AddUsesToWorkList(*I);
10743 ++NumDeadInst;
10744
10745 DOUT << "IC: DCE: " << *I;
10746
10747 I->eraseFromParent();
10748 RemoveFromWorkList(I);
10749 continue;
10750 }
10751
10752 // Instruction isn't dead, see if we can constant propagate it.
10753 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10754 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10755
10756 // Add operands to the worklist.
10757 AddUsesToWorkList(*I);
10758 ReplaceInstUsesWith(*I, C);
10759
10760 ++NumConstProp;
10761 I->eraseFromParent();
10762 RemoveFromWorkList(I);
10763 continue;
10764 }
10765
10766 // See if we can trivially sink this instruction to a successor basic block.
10767 if (I->hasOneUse()) {
10768 BasicBlock *BB = I->getParent();
10769 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10770 if (UserParent != BB) {
10771 bool UserIsSuccessor = false;
10772 // See if the user is one of our successors.
10773 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10774 if (*SI == UserParent) {
10775 UserIsSuccessor = true;
10776 break;
10777 }
10778
10779 // If the user is one of our immediate successors, and if that successor
10780 // only has us as a predecessors (we'd have to split the critical edge
10781 // otherwise), we can keep going.
10782 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10783 next(pred_begin(UserParent)) == pred_end(UserParent))
10784 // Okay, the CFG is simple enough, try to sink this instruction.
10785 Changed |= TryToSinkInstruction(I, UserParent);
10786 }
10787 }
10788
10789 // Now that we have an instruction, try combining it to simplify it...
10790#ifndef NDEBUG
10791 std::string OrigI;
10792#endif
10793 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10794 if (Instruction *Result = visit(*I)) {
10795 ++NumCombined;
10796 // Should we replace the old instruction with a new one?
10797 if (Result != I) {
10798 DOUT << "IC: Old = " << *I
10799 << " New = " << *Result;
10800
10801 // Everything uses the new instruction now.
10802 I->replaceAllUsesWith(Result);
10803
10804 // Push the new instruction and any users onto the worklist.
10805 AddToWorkList(Result);
10806 AddUsersToWorkList(*Result);
10807
10808 // Move the name to the new instruction first.
10809 Result->takeName(I);
10810
10811 // Insert the new instruction into the basic block...
10812 BasicBlock *InstParent = I->getParent();
10813 BasicBlock::iterator InsertPos = I;
10814
10815 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10816 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10817 ++InsertPos;
10818
10819 InstParent->getInstList().insert(InsertPos, Result);
10820
10821 // Make sure that we reprocess all operands now that we reduced their
10822 // use counts.
10823 AddUsesToWorkList(*I);
10824
10825 // Instructions can end up on the worklist more than once. Make sure
10826 // we do not process an instruction that has been deleted.
10827 RemoveFromWorkList(I);
10828
10829 // Erase the old instruction.
10830 InstParent->getInstList().erase(I);
10831 } else {
10832#ifndef NDEBUG
10833 DOUT << "IC: Mod = " << OrigI
10834 << " New = " << *I;
10835#endif
10836
10837 // If the instruction was modified, it's possible that it is now dead.
10838 // if so, remove it.
10839 if (isInstructionTriviallyDead(I)) {
10840 // Make sure we process all operands now that we are reducing their
10841 // use counts.
10842 AddUsesToWorkList(*I);
10843
10844 // Instructions may end up in the worklist more than once. Erase all
10845 // occurrences of this instruction.
10846 RemoveFromWorkList(I);
10847 I->eraseFromParent();
10848 } else {
10849 AddToWorkList(I);
10850 AddUsersToWorkList(*I);
10851 }
10852 }
10853 Changed = true;
10854 }
10855 }
10856
10857 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010858
10859 // Do an explicit clear, this shrinks the map if needed.
10860 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010861 return Changed;
10862}
10863
10864
10865bool InstCombiner::runOnFunction(Function &F) {
10866 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10867
10868 bool EverMadeChange = false;
10869
10870 // Iterate while there is work to do.
10871 unsigned Iteration = 0;
10872 while (DoOneIteration(F, Iteration++))
10873 EverMadeChange = true;
10874 return EverMadeChange;
10875}
10876
10877FunctionPass *llvm::createInstructionCombiningPass() {
10878 return new InstCombiner();
10879}
10880