blob: 0c459cf143077bc0dbc1fc1830f4aef12a69a349 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/GetElementPtrTypeIterator.h"
50#include "llvm/Support/InstVisitor.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/PatternMatch.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#include <sstream>
62using namespace llvm;
63using namespace llvm::PatternMatch;
64
65STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71namespace {
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
78 TargetData *TD;
79 bool MustPreserveLCSSA;
80 public:
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
108
109
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116 UI != UE; ++UI)
117 AddToWorkList(cast<Instruction>(*UI));
118 }
119
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126 AddToWorkList(Op);
127 }
128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140 AddToWorkList(Op);
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
147
148 public:
149 virtual bool runOnFunction(Function &F);
150
151 bool DoOneIteration(Function &F, unsigned ItNum);
152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
157 }
158
159 TargetData &getTargetData() const { return *TD; }
160
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
167 //
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
198
199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
202 BinaryOperator &I);
203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
205 Instruction *commonPointerCastTransforms(CastInst &CI);
206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 Instruction *visitBitCast(BitCastInst &CI);
218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
220 Instruction *visitSelectInst(SelectInst &CI);
221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225 Instruction *visitAllocationInst(AllocationInst &AI);
226 Instruction *visitFreeInst(FreeInst &FI);
227 Instruction *visitLoadInst(LoadInst &LI);
228 Instruction *visitStoreInst(StoreInst &SI);
229 Instruction *visitBranchInst(BranchInst &BI);
230 Instruction *visitSwitchInst(SwitchInst &SI);
231 Instruction *visitInsertElementInst(InsertElementInst &IE);
232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
234
235 // visitInstruction - Specify what to return for unhandled instructions...
236 Instruction *visitInstruction(Instruction &I) { return 0; }
237
238 private:
239 Instruction *visitCallSite(CallSite CS);
240 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
245 public:
246 // InsertNewInstBefore - insert an instruction New before instruction Old
247 // in the program. Add the new instruction to the worklist.
248 //
249 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
250 assert(New && New->getParent() == 0 &&
251 "New instruction already inserted into a basic block!");
252 BasicBlock *BB = Old.getParent();
253 BB->getInstList().insert(&Old, New); // Insert inst
254 AddToWorkList(New);
255 return New;
256 }
257
258 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
259 /// This also adds the cast to the worklist. Finally, this returns the
260 /// cast.
261 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
262 Instruction &Pos) {
263 if (V->getType() == Ty) return V;
264
265 if (Constant *CV = dyn_cast<Constant>(V))
266 return ConstantExpr::getCast(opc, CV, Ty);
267
Gabor Greifa645dd32008-05-16 19:29:10 +0000268 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 AddToWorkList(C);
270 return C;
271 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000272
273 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
274 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
275 }
276
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277
278 // ReplaceInstUsesWith - This method is to be used when an instruction is
279 // found to be dead, replacable with another preexisting expression. Here
280 // we add all uses of I to the worklist, replace all uses of I with the new
281 // value, then return I, so that the inst combiner will know that I was
282 // modified.
283 //
284 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
285 AddUsersToWorkList(I); // Add all modified instrs to worklist
286 if (&I != V) {
287 I.replaceAllUsesWith(V);
288 return &I;
289 } else {
290 // If we are replacing the instruction with itself, this must be in a
291 // segment of unreachable code, so just clobber the instruction.
292 I.replaceAllUsesWith(UndefValue::get(I.getType()));
293 return &I;
294 }
295 }
296
297 // UpdateValueUsesWith - This method is to be used when an value is
298 // found to be replacable with another preexisting expression or was
299 // updated. Here we add all uses of I to the worklist, replace all uses of
300 // I with the new value (unless the instruction was just updated), then
301 // return true, so that the inst combiner will know that I was modified.
302 //
303 bool UpdateValueUsesWith(Value *Old, Value *New) {
304 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
305 if (Old != New)
306 Old->replaceAllUsesWith(New);
307 if (Instruction *I = dyn_cast<Instruction>(Old))
308 AddToWorkList(I);
309 if (Instruction *I = dyn_cast<Instruction>(New))
310 AddToWorkList(I);
311 return true;
312 }
313
314 // EraseInstFromFunction - When dealing with an instruction that has side
315 // effects or produces a void value, we can't rely on DCE to delete the
316 // instruction. Instead, visit methods should return the value returned by
317 // this function.
318 Instruction *EraseInstFromFunction(Instruction &I) {
319 assert(I.use_empty() && "Cannot erase instruction that is used!");
320 AddUsesToWorkList(I);
321 RemoveFromWorkList(&I);
322 I.eraseFromParent();
323 return 0; // Don't do anything with FI
324 }
325
326 private:
327 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
328 /// InsertBefore instruction. This is specialized a bit to avoid inserting
329 /// casts that are known to not do anything...
330 ///
331 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
332 Value *V, const Type *DestTy,
333 Instruction *InsertBefore);
334
335 /// SimplifyCommutative - This performs a few simplifications for
336 /// commutative operators.
337 bool SimplifyCommutative(BinaryOperator &I);
338
339 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340 /// most-complex to least-complex order.
341 bool SimplifyCompare(CmpInst &I);
342
343 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
344 /// on the demanded bits.
345 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth = 0);
348
349 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
350 uint64_t &UndefElts, unsigned Depth = 0);
351
352 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
353 // PHI node as operand #0, see if we can fold the instruction into the PHI
354 // (which is only possible if all operands to the PHI are constants).
355 Instruction *FoldOpIntoPhi(Instruction &I);
356
357 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
358 // operator and they all are only used by the PHI, PHI together their
359 // inputs, and do the operation once, to the result of the PHI.
360 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
361 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
362
363
364 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
365 ConstantInt *AndRHS, BinaryOperator &TheAnd);
366
367 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
368 bool isSub, Instruction &I);
369 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
370 bool isSigned, bool Inside, Instruction &IB);
371 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
372 Instruction *MatchBSwap(BinaryOperator &I);
373 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000374 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000375 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000376
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377
378 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
381 APInt& KnownOne, unsigned Depth = 0);
382 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
383 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
384 unsigned CastOpc,
385 int &NumCastsRemoved);
386 unsigned GetOrEnforceKnownAlignment(Value *V,
387 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389}
390
Dan Gohman089efff2008-05-13 00:00:25 +0000391char InstCombiner::ID = 0;
392static RegisterPass<InstCombiner>
393X("instcombine", "Combine redundant instructions");
394
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395// getComplexity: Assign a complexity or rank value to LLVM Values...
396// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
397static unsigned getComplexity(Value *V) {
398 if (isa<Instruction>(V)) {
399 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
400 return 3;
401 return 4;
402 }
403 if (isa<Argument>(V)) return 3;
404 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
405}
406
407// isOnlyUse - Return true if this instruction will be deleted if we stop using
408// it.
409static bool isOnlyUse(Value *V) {
410 return V->hasOneUse() || isa<Constant>(V);
411}
412
413// getPromotedType - Return the specified type promoted as it would be to pass
414// though a va_arg area...
415static const Type *getPromotedType(const Type *Ty) {
416 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
417 if (ITy->getBitWidth() < 32)
418 return Type::Int32Ty;
419 }
420 return Ty;
421}
422
423/// getBitCastOperand - If the specified operand is a CastInst or a constant
424/// expression bitcast, return the operand value, otherwise return null.
425static Value *getBitCastOperand(Value *V) {
426 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
427 return I->getOperand(0);
428 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
429 if (CE->getOpcode() == Instruction::BitCast)
430 return CE->getOperand(0);
431 return 0;
432}
433
434/// This function is a wrapper around CastInst::isEliminableCastPair. It
435/// simply extracts arguments and returns what that function returns.
436static Instruction::CastOps
437isEliminableCastPair(
438 const CastInst *CI, ///< The first cast instruction
439 unsigned opcode, ///< The opcode of the second cast instruction
440 const Type *DstTy, ///< The target type for the second cast instruction
441 TargetData *TD ///< The target data for pointer size
442) {
443
444 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
445 const Type *MidTy = CI->getType(); // B from above
446
447 // Get the opcodes of the two Cast instructions
448 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
449 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
450
451 return Instruction::CastOps(
452 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
453 DstTy, TD->getIntPtrType()));
454}
455
456/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
457/// in any code being generated. It does not require codegen if V is simple
458/// enough or if the cast can be folded into other casts.
459static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
460 const Type *Ty, TargetData *TD) {
461 if (V->getType() == Ty || isa<Constant>(V)) return false;
462
463 // If this is another cast that can be eliminated, it isn't codegen either.
464 if (const CastInst *CI = dyn_cast<CastInst>(V))
465 if (isEliminableCastPair(CI, opcode, Ty, TD))
466 return false;
467 return true;
468}
469
470/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
471/// InsertBefore instruction. This is specialized a bit to avoid inserting
472/// casts that are known to not do anything...
473///
474Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
475 Value *V, const Type *DestTy,
476 Instruction *InsertBefore) {
477 if (V->getType() == DestTy) return V;
478 if (Constant *C = dyn_cast<Constant>(V))
479 return ConstantExpr::getCast(opcode, C, DestTy);
480
481 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
482}
483
484// SimplifyCommutative - This performs a few simplifications for commutative
485// operators:
486//
487// 1. Order operands such that they are listed from right (least complex) to
488// left (most complex). This puts constants before unary operators before
489// binary operators.
490//
491// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
492// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
493//
494bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
495 bool Changed = false;
496 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
497 Changed = !I.swapOperands();
498
499 if (!I.isAssociative()) return Changed;
500 Instruction::BinaryOps Opcode = I.getOpcode();
501 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
502 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
503 if (isa<Constant>(I.getOperand(1))) {
504 Constant *Folded = ConstantExpr::get(I.getOpcode(),
505 cast<Constant>(I.getOperand(1)),
506 cast<Constant>(Op->getOperand(1)));
507 I.setOperand(0, Op->getOperand(0));
508 I.setOperand(1, Folded);
509 return true;
510 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
511 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
512 isOnlyUse(Op) && isOnlyUse(Op1)) {
513 Constant *C1 = cast<Constant>(Op->getOperand(1));
514 Constant *C2 = cast<Constant>(Op1->getOperand(1));
515
516 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000518 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 Op1->getOperand(0),
520 Op1->getName(), &I);
521 AddToWorkList(New);
522 I.setOperand(0, New);
523 I.setOperand(1, Folded);
524 return true;
525 }
526 }
527 return Changed;
528}
529
530/// SimplifyCompare - For a CmpInst this function just orders the operands
531/// so that theyare listed from right (least complex) to left (most complex).
532/// This puts constants before unary operators before binary operators.
533bool InstCombiner::SimplifyCompare(CmpInst &I) {
534 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
535 return false;
536 I.swapOperands();
537 // Compare instructions are not associative so there's nothing else we can do.
538 return true;
539}
540
541// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
542// if the LHS is a constant zero (which is the 'negate' form).
543//
544static inline Value *dyn_castNegVal(Value *V) {
545 if (BinaryOperator::isNeg(V))
546 return BinaryOperator::getNegArgument(V);
547
548 // Constants can be considered to be negated values if they can be folded.
549 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
550 return ConstantExpr::getNeg(C);
551 return 0;
552}
553
554static inline Value *dyn_castNotVal(Value *V) {
555 if (BinaryOperator::isNot(V))
556 return BinaryOperator::getNotArgument(V);
557
558 // Constants can be considered to be not'ed values...
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantInt::get(~C->getValue());
561 return 0;
562}
563
564// dyn_castFoldableMul - If this value is a multiply that can be folded into
565// other computations (because it has a constant operand), return the
566// non-constant operand of the multiply, and set CST to point to the multiplier.
567// Otherwise, return null.
568//
569static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
570 if (V->hasOneUse() && V->getType()->isInteger())
571 if (Instruction *I = dyn_cast<Instruction>(V)) {
572 if (I->getOpcode() == Instruction::Mul)
573 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
574 return I->getOperand(0);
575 if (I->getOpcode() == Instruction::Shl)
576 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
577 // The multiplier is really 1 << CST.
578 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
579 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
580 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
581 return I->getOperand(0);
582 }
583 }
584 return 0;
585}
586
587/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
588/// expression, return it.
589static User *dyn_castGetElementPtr(Value *V) {
590 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
592 if (CE->getOpcode() == Instruction::GetElementPtr)
593 return cast<User>(V);
594 return false;
595}
596
Dan Gohman2d648bb2008-04-10 18:43:06 +0000597/// getOpcode - If this is an Instruction or a ConstantExpr, return the
598/// opcode value. Otherwise return UserOp1.
599static unsigned getOpcode(User *U) {
600 if (Instruction *I = dyn_cast<Instruction>(U))
601 return I->getOpcode();
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
603 return CE->getOpcode();
604 // Use UserOp1 to mean there's no opcode.
605 return Instruction::UserOp1;
606}
607
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608/// AddOne - Add one to a ConstantInt
609static ConstantInt *AddOne(ConstantInt *C) {
610 APInt Val(C->getValue());
611 return ConstantInt::get(++Val);
612}
613/// SubOne - Subtract one from a ConstantInt
614static ConstantInt *SubOne(ConstantInt *C) {
615 APInt Val(C->getValue());
616 return ConstantInt::get(--Val);
617}
618/// Add - Add two ConstantInts together
619static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
620 return ConstantInt::get(C1->getValue() + C2->getValue());
621}
622/// And - Bitwise AND two ConstantInts together
623static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
624 return ConstantInt::get(C1->getValue() & C2->getValue());
625}
626/// Subtract - Subtract one ConstantInt from another
627static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
628 return ConstantInt::get(C1->getValue() - C2->getValue());
629}
630/// Multiply - Multiply two ConstantInts together
631static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
632 return ConstantInt::get(C1->getValue() * C2->getValue());
633}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000634/// MultiplyOverflows - True if the multiply can not be expressed in an int
635/// this size.
636static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
637 uint32_t W = C1->getBitWidth();
638 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
639 if (sign) {
640 LHSExt.sext(W * 2);
641 RHSExt.sext(W * 2);
642 } else {
643 LHSExt.zext(W * 2);
644 RHSExt.zext(W * 2);
645 }
646
647 APInt MulExt = LHSExt * RHSExt;
648
649 if (sign) {
650 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
651 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
652 return MulExt.slt(Min) || MulExt.sgt(Max);
653 } else
654 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
655}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656
657/// ComputeMaskedBits - Determine which of the bits specified in Mask are
658/// known to be either zero or one and return them in the KnownZero/KnownOne
659/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
660/// processing.
661/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
662/// we cannot optimize based on the assumption that it is zero without changing
663/// it to be an explicit zero. If we don't change it to zero, other code could
664/// optimized based on the contradictory assumption that it is non-zero.
665/// Because instcombine aggressively folds operations with undef args anyway,
666/// this won't lose us code quality.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000667void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
668 APInt& KnownZero, APInt& KnownOne,
669 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 assert(V && "No Value?");
671 assert(Depth <= 6 && "Limit Search Depth");
672 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000673 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
674 "Not integer or pointer type!");
675 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
676 (!isa<IntegerType>(V->getType()) ||
677 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 KnownZero.getBitWidth() == BitWidth &&
679 KnownOne.getBitWidth() == BitWidth &&
680 "V, Mask, KnownOne and KnownZero should have same BitWidth");
681 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
682 // We know all of the bits for a constant!
683 KnownOne = CI->getValue() & Mask;
684 KnownZero = ~KnownOne & Mask;
685 return;
686 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000687 // Null is all-zeros.
688 if (isa<ConstantPointerNull>(V)) {
689 KnownOne.clear();
690 KnownZero = Mask;
691 return;
692 }
693 // The address of an aligned GlobalValue has trailing zeros.
694 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
695 unsigned Align = GV->getAlignment();
696 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
697 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
698 if (Align > 0)
699 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
700 CountTrailingZeros_32(Align));
701 else
702 KnownZero.clear();
703 KnownOne.clear();
704 return;
705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706
Dan Gohmanbec16052008-04-28 17:02:21 +0000707 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
708
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 if (Depth == 6 || Mask == 0)
710 return; // Limit search depth.
711
Dan Gohman2d648bb2008-04-10 18:43:06 +0000712 User *I = dyn_cast<User>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 if (!I) return;
714
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000716 switch (getOpcode(I)) {
717 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 case Instruction::And: {
719 // If either the LHS or the RHS are Zero, the result is zero.
720 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
721 APInt Mask2(Mask & ~KnownZero);
722 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
724 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
725
726 // Output known-1 bits are only known if set in both the LHS & RHS.
727 KnownOne &= KnownOne2;
728 // Output known-0 are known to be clear if zero in either the LHS | RHS.
729 KnownZero |= KnownZero2;
730 return;
731 }
732 case Instruction::Or: {
733 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
734 APInt Mask2(Mask & ~KnownOne);
735 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
736 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
737 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
738
739 // Output known-0 bits are only known if clear in both the LHS & RHS.
740 KnownZero &= KnownZero2;
741 // Output known-1 are known to be set if set in either the LHS | RHS.
742 KnownOne |= KnownOne2;
743 return;
744 }
745 case Instruction::Xor: {
746 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
748 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
749 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
750
751 // Output known-0 bits are known if clear or set in both the LHS & RHS.
752 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
753 // Output known-1 are known to be set if set in only one of the LHS, RHS.
754 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
755 KnownZero = KnownZeroOut;
756 return;
757 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000758 case Instruction::Mul: {
759 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
760 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
761 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
762 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
763 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
764
765 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohmanbec16052008-04-28 17:02:21 +0000766 // Also compute a conserative estimate for high known-0 bits.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000767 // More trickiness is possible, but this is sufficient for the
768 // interesting case of alignment computation.
769 KnownOne.clear();
770 unsigned TrailZ = KnownZero.countTrailingOnes() +
771 KnownZero2.countTrailingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +0000772 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman4c451852008-05-07 00:35:55 +0000773 KnownZero2.countLeadingOnes(),
774 BitWidth) - BitWidth;
Dan Gohmanbec16052008-04-28 17:02:21 +0000775
Dan Gohman2d648bb2008-04-10 18:43:06 +0000776 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000777 LeadZ = std::min(LeadZ, BitWidth);
778 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
779 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000780 KnownZero &= Mask;
781 return;
782 }
Dan Gohmanbec16052008-04-28 17:02:21 +0000783 case Instruction::UDiv: {
784 // For the purposes of computing leading zeros we can conservatively
785 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000786 // be less than the denominator.
Dan Gohmanbec16052008-04-28 17:02:21 +0000787 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
788 ComputeMaskedBits(I->getOperand(0),
789 AllOnes, KnownZero2, KnownOne2, Depth+1);
790 unsigned LeadZ = KnownZero2.countLeadingOnes();
791
792 KnownOne2.clear();
793 KnownZero2.clear();
794 ComputeMaskedBits(I->getOperand(1),
795 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000796 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
797 if (RHSUnknownLeadingOnes != BitWidth)
798 LeadZ = std::min(BitWidth,
799 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000800
801 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
802 return;
803 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 case Instruction::Select:
805 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
806 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
807 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
808 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
809
810 // Only known if known in both the LHS and RHS.
811 KnownOne &= KnownOne2;
812 KnownZero &= KnownZero2;
813 return;
814 case Instruction::FPTrunc:
815 case Instruction::FPExt:
816 case Instruction::FPToUI:
817 case Instruction::FPToSI:
818 case Instruction::SIToFP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 case Instruction::UIToFP:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000820 return; // Can't work with floating point.
821 case Instruction::PtrToInt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 case Instruction::IntToPtr:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000823 // We can't handle these if we don't know the pointer size.
824 if (!TD) return;
Chris Lattnere3061db2008-05-19 20:27:56 +0000825 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000826 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 case Instruction::Trunc: {
Chris Lattnere3061db2008-05-19 20:27:56 +0000828 // Note that we handle pointer operands here because of inttoptr/ptrtoint
829 // which fall through here.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000830 const Type *SrcTy = I->getOperand(0)->getType();
831 uint32_t SrcBitWidth = TD ?
832 TD->getTypeSizeInBits(SrcTy) :
833 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000835 MaskIn.zextOrTrunc(SrcBitWidth);
836 KnownZero.zextOrTrunc(SrcBitWidth);
837 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000839 KnownZero.zextOrTrunc(BitWidth);
840 KnownOne.zextOrTrunc(BitWidth);
841 // Any top bits are known to be zero.
842 if (BitWidth > SrcBitWidth)
843 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 return;
845 }
846 case Instruction::BitCast: {
847 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000848 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
850 return;
851 }
852 break;
853 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 case Instruction::SExt: {
855 // Compute the bits in the result that are not present in the input.
856 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
857 uint32_t SrcBitWidth = SrcTy->getBitWidth();
858
859 APInt MaskIn(Mask);
860 MaskIn.trunc(SrcBitWidth);
861 KnownZero.trunc(SrcBitWidth);
862 KnownOne.trunc(SrcBitWidth);
863 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
865 KnownZero.zext(BitWidth);
866 KnownOne.zext(BitWidth);
867
868 // If the sign bit of the input is known set or clear, then we know the
869 // top bits of the result.
870 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
871 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
872 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
873 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
874 return;
875 }
876 case Instruction::Shl:
877 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
878 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
879 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
880 APInt Mask2(Mask.lshr(ShiftAmt));
881 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
882 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
883 KnownZero <<= ShiftAmt;
884 KnownOne <<= ShiftAmt;
885 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
886 return;
887 }
888 break;
889 case Instruction::LShr:
890 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
891 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
892 // Compute the new bits that are at the top now.
893 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
894
895 // Unsigned shift right.
896 APInt Mask2(Mask.shl(ShiftAmt));
897 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
898 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
899 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
900 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
901 // high bits known zero.
902 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
903 return;
904 }
905 break;
906 case Instruction::AShr:
907 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
908 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
909 // Compute the new bits that are at the top now.
910 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
911
912 // Signed shift right.
913 APInt Mask2(Mask.shl(ShiftAmt));
914 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
915 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
916 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
917 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
918
919 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
920 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
921 KnownZero |= HighBits;
922 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
923 KnownOne |= HighBits;
924 return;
925 }
926 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000927 case Instruction::Sub: {
928 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
929 // We know that the top bits of C-X are clear if X contains less bits
930 // than C (i.e. no wrap-around can happen). For example, 20-X is
931 // positive if we can prove that X is >= 0 and < 16.
932 if (!CLHS->getValue().isNegative()) {
933 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
934 // NLZ can't be BitWidth with no sign bit
935 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000936 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
937 Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000938
Dan Gohmanbec16052008-04-28 17:02:21 +0000939 // If all of the MaskV bits are known to be zero, then we know the
940 // output top bits are zero, because we now know that the output is
941 // from [0-C].
942 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman2d648bb2008-04-10 18:43:06 +0000943 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
944 // Top bits known zero.
945 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000946 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000947 }
948 }
949 }
950 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000951 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000952 // Output known-0 bits are known if clear or set in both the low clear bits
953 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
954 // low 3 bits clear.
Dan Gohmanbec16052008-04-28 17:02:21 +0000955 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
956 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
957 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
958 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
959
960 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
961 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
962 KnownZeroOut = std::min(KnownZeroOut,
963 KnownZero2.countTrailingOnes());
964
965 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000966 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000967 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000968 case Instruction::SRem:
969 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
970 APInt RA = Rem->getValue();
971 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +0000972 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000973 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
974 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
975
976 // The sign of a remainder is equal to the sign of the first
977 // operand (zero being positive).
978 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
979 KnownZero2 |= ~LowBits;
980 else if (KnownOne2[BitWidth-1])
981 KnownOne2 |= ~LowBits;
982
983 KnownZero |= KnownZero2 & Mask;
984 KnownOne |= KnownOne2 & Mask;
985
986 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
987 }
988 }
989 break;
Dan Gohmanbec16052008-04-28 17:02:21 +0000990 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000991 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
992 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +0000993 if (RA.isPowerOf2()) {
994 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000995 APInt Mask2 = LowBits & Mask;
996 KnownZero |= ~LowBits & Mask;
997 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
998 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +0000999 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001000 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001001 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001002
1003 // Since the result is less than or equal to either operand, any leading
1004 // zero bits in either operand must also exist in the result.
1005 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1006 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1007 Depth+1);
1008 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1009 Depth+1);
1010
1011 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1012 KnownZero2.countLeadingOnes());
1013 KnownOne.clear();
1014 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001015 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001016 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00001017
1018 case Instruction::Alloca:
1019 case Instruction::Malloc: {
1020 AllocationInst *AI = cast<AllocationInst>(V);
1021 unsigned Align = AI->getAlignment();
1022 if (Align == 0 && TD) {
1023 if (isa<AllocaInst>(AI))
1024 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1025 else if (isa<MallocInst>(AI)) {
1026 // Malloc returns maximally aligned memory.
1027 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1031 Align =
1032 std::max(Align,
1033 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1034 }
1035 }
1036
1037 if (Align > 0)
1038 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1039 CountTrailingZeros_32(Align));
1040 break;
1041 }
1042 case Instruction::GetElementPtr: {
1043 // Analyze all of the subscripts of this getelementptr instruction
1044 // to determine if we can prove known low zero bits.
1045 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1046 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1047 ComputeMaskedBits(I->getOperand(0), LocalMask,
1048 LocalKnownZero, LocalKnownOne, Depth+1);
1049 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1050
1051 gep_type_iterator GTI = gep_type_begin(I);
1052 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1053 Value *Index = I->getOperand(i);
1054 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1055 // Handle struct member offset arithmetic.
1056 if (!TD) return;
1057 const StructLayout *SL = TD->getStructLayout(STy);
1058 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1059 uint64_t Offset = SL->getElementOffset(Idx);
1060 TrailZ = std::min(TrailZ,
1061 CountTrailingZeros_64(Offset));
1062 } else {
1063 // Handle array index arithmetic.
1064 const Type *IndexedTy = GTI.getIndexedType();
1065 if (!IndexedTy->isSized()) return;
1066 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1067 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1068 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1069 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1070 ComputeMaskedBits(Index, LocalMask,
1071 LocalKnownZero, LocalKnownOne, Depth+1);
1072 TrailZ = std::min(TrailZ,
1073 CountTrailingZeros_64(TypeSize) +
1074 LocalKnownZero.countTrailingOnes());
1075 }
1076 }
1077
1078 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1079 break;
1080 }
1081 case Instruction::PHI: {
1082 PHINode *P = cast<PHINode>(I);
1083 // Handle the case of a simple two-predecessor recurrence PHI.
1084 // There's a lot more that could theoretically be done here, but
1085 // this is sufficient to catch some interesting cases.
1086 if (P->getNumIncomingValues() == 2) {
1087 for (unsigned i = 0; i != 2; ++i) {
1088 Value *L = P->getIncomingValue(i);
1089 Value *R = P->getIncomingValue(!i);
1090 User *LU = dyn_cast<User>(L);
1091 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1092 // Check for operations that have the property that if
1093 // both their operands have low zero bits, the result
1094 // will have low zero bits.
1095 if (Opcode == Instruction::Add ||
1096 Opcode == Instruction::Sub ||
1097 Opcode == Instruction::And ||
1098 Opcode == Instruction::Or ||
1099 Opcode == Instruction::Mul) {
1100 Value *LL = LU->getOperand(0);
1101 Value *LR = LU->getOperand(1);
1102 // Find a recurrence.
1103 if (LL == I)
1104 L = LR;
1105 else if (LR == I)
1106 L = LL;
1107 else
1108 break;
1109 // Ok, we have a PHI of the form L op= R. Check for low
1110 // zero bits.
1111 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1112 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1113 Mask2 = APInt::getLowBitsSet(BitWidth,
1114 KnownZero2.countTrailingOnes());
1115 KnownOne2.clear();
1116 KnownZero2.clear();
1117 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1118 KnownZero = Mask &
1119 APInt::getLowBitsSet(BitWidth,
1120 KnownZero2.countTrailingOnes());
1121 break;
1122 }
1123 }
1124 }
1125 break;
1126 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001127 case Instruction::Call:
1128 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1129 switch (II->getIntrinsicID()) {
1130 default: break;
1131 case Intrinsic::ctpop:
1132 case Intrinsic::ctlz:
1133 case Intrinsic::cttz: {
1134 unsigned LowBits = Log2_32(BitWidth)+1;
1135 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1136 break;
1137 }
1138 }
1139 }
1140 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 }
1142}
1143
1144/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1145/// this predicate to simplify operations downstream. Mask is known to be zero
1146/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001147bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1148 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1150 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1151 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1152 return (KnownZero & Mask) == Mask;
1153}
1154
1155/// ShrinkDemandedConstant - Check to see if the specified operand of the
1156/// specified instruction is a constant integer. If so, check to see if there
1157/// are any bits set in the constant that are not demanded. If so, shrink the
1158/// constant and return true.
1159static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1160 APInt Demanded) {
1161 assert(I && "No instruction?");
1162 assert(OpNo < I->getNumOperands() && "Operand index too large");
1163
1164 // If the operand is not a constant integer, nothing to do.
1165 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1166 if (!OpC) return false;
1167
1168 // If there are no bits set that aren't demanded, nothing to do.
1169 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1170 if ((~Demanded & OpC->getValue()) == 0)
1171 return false;
1172
1173 // This instruction is producing bits that are not demanded. Shrink the RHS.
1174 Demanded &= OpC->getValue();
1175 I->setOperand(OpNo, ConstantInt::get(Demanded));
1176 return true;
1177}
1178
1179// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1180// set of known zero and one bits, compute the maximum and minimum values that
1181// could have the specified known zero and known one bits, returning them in
1182// min/max.
1183static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1184 const APInt& KnownZero,
1185 const APInt& KnownOne,
1186 APInt& Min, APInt& Max) {
1187 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1188 assert(KnownZero.getBitWidth() == BitWidth &&
1189 KnownOne.getBitWidth() == BitWidth &&
1190 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1191 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1192 APInt UnknownBits = ~(KnownZero|KnownOne);
1193
1194 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1195 // bit if it is unknown.
1196 Min = KnownOne;
1197 Max = KnownOne|UnknownBits;
1198
1199 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1200 Min.set(BitWidth-1);
1201 Max.clear(BitWidth-1);
1202 }
1203}
1204
1205// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1206// a set of known zero and one bits, compute the maximum and minimum values that
1207// could have the specified known zero and known one bits, returning them in
1208// min/max.
1209static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001210 const APInt &KnownZero,
1211 const APInt &KnownOne,
1212 APInt &Min, APInt &Max) {
1213 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 assert(KnownZero.getBitWidth() == BitWidth &&
1215 KnownOne.getBitWidth() == BitWidth &&
1216 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1217 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1218 APInt UnknownBits = ~(KnownZero|KnownOne);
1219
1220 // The minimum value is when the unknown bits are all zeros.
1221 Min = KnownOne;
1222 // The maximum value is when the unknown bits are all ones.
1223 Max = KnownOne|UnknownBits;
1224}
1225
1226/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1227/// value based on the demanded bits. When this function is called, it is known
1228/// that only the bits set in DemandedMask of the result of V are ever used
1229/// downstream. Consequently, depending on the mask and V, it may be possible
1230/// to replace V with a constant or one of its operands. In such cases, this
1231/// function does the replacement and returns true. In all other cases, it
1232/// returns false after analyzing the expression and setting KnownOne and known
1233/// to be one in the expression. KnownZero contains all the bits that are known
1234/// to be zero in the expression. These are provided to potentially allow the
1235/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1236/// the expression. KnownOne and KnownZero always follow the invariant that
1237/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1238/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1239/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1240/// and KnownOne must all be the same.
1241bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1242 APInt& KnownZero, APInt& KnownOne,
1243 unsigned Depth) {
1244 assert(V != 0 && "Null pointer of Value???");
1245 assert(Depth <= 6 && "Limit Search Depth");
1246 uint32_t BitWidth = DemandedMask.getBitWidth();
1247 const IntegerType *VTy = cast<IntegerType>(V->getType());
1248 assert(VTy->getBitWidth() == BitWidth &&
1249 KnownZero.getBitWidth() == BitWidth &&
1250 KnownOne.getBitWidth() == BitWidth &&
1251 "Value *V, DemandedMask, KnownZero and KnownOne \
1252 must have same BitWidth");
1253 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1254 // We know all of the bits for a constant!
1255 KnownOne = CI->getValue() & DemandedMask;
1256 KnownZero = ~KnownOne & DemandedMask;
1257 return false;
1258 }
1259
1260 KnownZero.clear();
1261 KnownOne.clear();
1262 if (!V->hasOneUse()) { // Other users may use these bits.
1263 if (Depth != 0) { // Not at the root.
1264 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1265 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1266 return false;
1267 }
1268 // If this is the root being simplified, allow it to have multiple uses,
1269 // just set the DemandedMask to all bits.
1270 DemandedMask = APInt::getAllOnesValue(BitWidth);
1271 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1272 if (V != UndefValue::get(VTy))
1273 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1274 return false;
1275 } else if (Depth == 6) { // Limit search depth.
1276 return false;
1277 }
1278
1279 Instruction *I = dyn_cast<Instruction>(V);
1280 if (!I) return false; // Only analyze instructions.
1281
1282 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1283 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1284 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001285 default:
1286 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1287 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 case Instruction::And:
1289 // If either the LHS or the RHS are Zero, the result is zero.
1290 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1291 RHSKnownZero, RHSKnownOne, Depth+1))
1292 return true;
1293 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1294 "Bits known to be one AND zero?");
1295
1296 // If something is known zero on the RHS, the bits aren't demanded on the
1297 // LHS.
1298 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1299 LHSKnownZero, LHSKnownOne, Depth+1))
1300 return true;
1301 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1302 "Bits known to be one AND zero?");
1303
1304 // If all of the demanded bits are known 1 on one side, return the other.
1305 // These bits cannot contribute to the result of the 'and'.
1306 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1307 (DemandedMask & ~LHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(0));
1309 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1310 (DemandedMask & ~RHSKnownZero))
1311 return UpdateValueUsesWith(I, I->getOperand(1));
1312
1313 // If all of the demanded bits in the inputs are known zeros, return zero.
1314 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1315 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1316
1317 // If the RHS is a constant, see if we can simplify it.
1318 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1319 return UpdateValueUsesWith(I, I);
1320
1321 // Output known-1 bits are only known if set in both the LHS & RHS.
1322 RHSKnownOne &= LHSKnownOne;
1323 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1324 RHSKnownZero |= LHSKnownZero;
1325 break;
1326 case Instruction::Or:
1327 // If either the LHS or the RHS are One, the result is One.
1328 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1329 RHSKnownZero, RHSKnownOne, Depth+1))
1330 return true;
1331 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1332 "Bits known to be one AND zero?");
1333 // If something is known one on the RHS, the bits aren't demanded on the
1334 // LHS.
1335 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1336 LHSKnownZero, LHSKnownOne, Depth+1))
1337 return true;
1338 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1339 "Bits known to be one AND zero?");
1340
1341 // If all of the demanded bits are known zero on one side, return the other.
1342 // These bits cannot contribute to the result of the 'or'.
1343 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1344 (DemandedMask & ~LHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(0));
1346 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1347 (DemandedMask & ~RHSKnownOne))
1348 return UpdateValueUsesWith(I, I->getOperand(1));
1349
1350 // If all of the potentially set bits on one side are known to be set on
1351 // the other side, just use the 'other' side.
1352 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1353 (DemandedMask & (~RHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(0));
1355 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1356 (DemandedMask & (~LHSKnownZero)))
1357 return UpdateValueUsesWith(I, I->getOperand(1));
1358
1359 // If the RHS is a constant, see if we can simplify it.
1360 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1361 return UpdateValueUsesWith(I, I);
1362
1363 // Output known-0 bits are only known if clear in both the LHS & RHS.
1364 RHSKnownZero &= LHSKnownZero;
1365 // Output known-1 are known to be set if set in either the LHS | RHS.
1366 RHSKnownOne |= LHSKnownOne;
1367 break;
1368 case Instruction::Xor: {
1369 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1375 LHSKnownZero, LHSKnownOne, Depth+1))
1376 return true;
1377 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1378 "Bits known to be one AND zero?");
1379
1380 // If all of the demanded bits are known zero on one side, return the other.
1381 // These bits cannot contribute to the result of the 'xor'.
1382 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1383 return UpdateValueUsesWith(I, I->getOperand(0));
1384 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1385 return UpdateValueUsesWith(I, I->getOperand(1));
1386
1387 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1388 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1389 (RHSKnownOne & LHSKnownOne);
1390 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1391 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1392 (RHSKnownOne & LHSKnownZero);
1393
1394 // If all of the demanded bits are known to be zero on one side or the
1395 // other, turn this into an *inclusive* or.
1396 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1397 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1398 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001399 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400 I->getName());
1401 InsertNewInstBefore(Or, *I);
1402 return UpdateValueUsesWith(I, Or);
1403 }
1404
1405 // If all of the demanded bits on one side are known, and all of the set
1406 // bits on that side are also known to be set on the other side, turn this
1407 // into an AND, as we know the bits will be cleared.
1408 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1409 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1410 // all known
1411 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1412 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1413 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001414 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 InsertNewInstBefore(And, *I);
1416 return UpdateValueUsesWith(I, And);
1417 }
1418 }
1419
1420 // If the RHS is a constant, see if we can simplify it.
1421 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1422 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1423 return UpdateValueUsesWith(I, I);
1424
1425 RHSKnownZero = KnownZeroOut;
1426 RHSKnownOne = KnownOneOut;
1427 break;
1428 }
1429 case Instruction::Select:
1430 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1431 RHSKnownZero, RHSKnownOne, Depth+1))
1432 return true;
1433 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1434 LHSKnownZero, LHSKnownOne, Depth+1))
1435 return true;
1436 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1437 "Bits known to be one AND zero?");
1438 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440
1441 // If the operands are constants, see if we can simplify them.
1442 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1443 return UpdateValueUsesWith(I, I);
1444 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1445 return UpdateValueUsesWith(I, I);
1446
1447 // Only known if known in both the LHS and RHS.
1448 RHSKnownOne &= LHSKnownOne;
1449 RHSKnownZero &= LHSKnownZero;
1450 break;
1451 case Instruction::Trunc: {
1452 uint32_t truncBf =
1453 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1454 DemandedMask.zext(truncBf);
1455 RHSKnownZero.zext(truncBf);
1456 RHSKnownOne.zext(truncBf);
1457 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1458 RHSKnownZero, RHSKnownOne, Depth+1))
1459 return true;
1460 DemandedMask.trunc(BitWidth);
1461 RHSKnownZero.trunc(BitWidth);
1462 RHSKnownOne.trunc(BitWidth);
1463 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1464 "Bits known to be one AND zero?");
1465 break;
1466 }
1467 case Instruction::BitCast:
1468 if (!I->getOperand(0)->getType()->isInteger())
1469 return false;
1470
1471 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1472 RHSKnownZero, RHSKnownOne, Depth+1))
1473 return true;
1474 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1475 "Bits known to be one AND zero?");
1476 break;
1477 case Instruction::ZExt: {
1478 // Compute the bits in the result that are not present in the input.
1479 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1480 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1481
1482 DemandedMask.trunc(SrcBitWidth);
1483 RHSKnownZero.trunc(SrcBitWidth);
1484 RHSKnownOne.trunc(SrcBitWidth);
1485 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1486 RHSKnownZero, RHSKnownOne, Depth+1))
1487 return true;
1488 DemandedMask.zext(BitWidth);
1489 RHSKnownZero.zext(BitWidth);
1490 RHSKnownOne.zext(BitWidth);
1491 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1492 "Bits known to be one AND zero?");
1493 // The top bits are known to be zero.
1494 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1495 break;
1496 }
1497 case Instruction::SExt: {
1498 // Compute the bits in the result that are not present in the input.
1499 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1500 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1501
1502 APInt InputDemandedBits = DemandedMask &
1503 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1504
1505 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1506 // If any of the sign extended bits are demanded, we know that the sign
1507 // bit is demanded.
1508 if ((NewBits & DemandedMask) != 0)
1509 InputDemandedBits.set(SrcBitWidth-1);
1510
1511 InputDemandedBits.trunc(SrcBitWidth);
1512 RHSKnownZero.trunc(SrcBitWidth);
1513 RHSKnownOne.trunc(SrcBitWidth);
1514 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1515 RHSKnownZero, RHSKnownOne, Depth+1))
1516 return true;
1517 InputDemandedBits.zext(BitWidth);
1518 RHSKnownZero.zext(BitWidth);
1519 RHSKnownOne.zext(BitWidth);
1520 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1521 "Bits known to be one AND zero?");
1522
1523 // If the sign bit of the input is known set or clear, then we know the
1524 // top bits of the result.
1525
1526 // If the input sign bit is known zero, or if the NewBits are not demanded
1527 // convert this into a zero extension.
1528 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1529 {
1530 // Convert to ZExt cast
1531 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1532 return UpdateValueUsesWith(I, NewCast);
1533 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1534 RHSKnownOne |= NewBits;
1535 }
1536 break;
1537 }
1538 case Instruction::Add: {
1539 // Figure out what the input bits are. If the top bits of the and result
1540 // are not demanded, then the add doesn't demand them from its input
1541 // either.
1542 uint32_t NLZ = DemandedMask.countLeadingZeros();
1543
1544 // If there is a constant on the RHS, there are a variety of xformations
1545 // we can do.
1546 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1547 // If null, this should be simplified elsewhere. Some of the xforms here
1548 // won't work if the RHS is zero.
1549 if (RHS->isZero())
1550 break;
1551
1552 // If the top bit of the output is demanded, demand everything from the
1553 // input. Otherwise, we demand all the input bits except NLZ top bits.
1554 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1555
1556 // Find information about known zero/one bits in the input.
1557 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1558 LHSKnownZero, LHSKnownOne, Depth+1))
1559 return true;
1560
1561 // If the RHS of the add has bits set that can't affect the input, reduce
1562 // the constant.
1563 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1564 return UpdateValueUsesWith(I, I);
1565
1566 // Avoid excess work.
1567 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1568 break;
1569
1570 // Turn it into OR if input bits are zero.
1571 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1572 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001573 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001574 I->getName());
1575 InsertNewInstBefore(Or, *I);
1576 return UpdateValueUsesWith(I, Or);
1577 }
1578
1579 // We can say something about the output known-zero and known-one bits,
1580 // depending on potential carries from the input constant and the
1581 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1582 // bits set and the RHS constant is 0x01001, then we know we have a known
1583 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1584
1585 // To compute this, we first compute the potential carry bits. These are
1586 // the bits which may be modified. I'm not aware of a better way to do
1587 // this scan.
1588 const APInt& RHSVal = RHS->getValue();
1589 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1590
1591 // Now that we know which bits have carries, compute the known-1/0 sets.
1592
1593 // Bits are known one if they are known zero in one operand and one in the
1594 // other, and there is no input carry.
1595 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1596 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1597
1598 // Bits are known zero if they are known zero in both operands and there
1599 // is no input carry.
1600 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1601 } else {
1602 // If the high-bits of this ADD are not demanded, then it does not demand
1603 // the high bits of its LHS or RHS.
1604 if (DemandedMask[BitWidth-1] == 0) {
1605 // Right fill the mask of bits for this ADD to demand the most
1606 // significant bit and all those below it.
1607 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1608 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1612 LHSKnownZero, LHSKnownOne, Depth+1))
1613 return true;
1614 }
1615 }
1616 break;
1617 }
1618 case Instruction::Sub:
1619 // If the high-bits of this SUB are not demanded, then it does not demand
1620 // the high bits of its LHS or RHS.
1621 if (DemandedMask[BitWidth-1] == 0) {
1622 // Right fill the mask of bits for this SUB to demand the most
1623 // significant bit and all those below it.
1624 uint32_t NLZ = DemandedMask.countLeadingZeros();
1625 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1626 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1630 LHSKnownZero, LHSKnownOne, Depth+1))
1631 return true;
1632 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001633 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1634 // the known zeros and ones.
1635 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 break;
1637 case Instruction::Shl:
1638 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1639 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1640 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1641 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1642 RHSKnownZero, RHSKnownOne, Depth+1))
1643 return true;
1644 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1645 "Bits known to be one AND zero?");
1646 RHSKnownZero <<= ShiftAmt;
1647 RHSKnownOne <<= ShiftAmt;
1648 // low bits known zero.
1649 if (ShiftAmt)
1650 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1651 }
1652 break;
1653 case Instruction::LShr:
1654 // For a logical shift right
1655 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1656 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1657
1658 // Unsigned shift right.
1659 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1660 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1661 RHSKnownZero, RHSKnownOne, Depth+1))
1662 return true;
1663 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1664 "Bits known to be one AND zero?");
1665 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1666 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1667 if (ShiftAmt) {
1668 // Compute the new bits that are at the top now.
1669 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1670 RHSKnownZero |= HighBits; // high bits known zero.
1671 }
1672 }
1673 break;
1674 case Instruction::AShr:
1675 // If this is an arithmetic shift right and only the low-bit is set, we can
1676 // always convert this into a logical shr, even if the shift amount is
1677 // variable. The low bit of the shift cannot be an input sign bit unless
1678 // the shift amount is >= the size of the datatype, which is undefined.
1679 if (DemandedMask == 1) {
1680 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001681 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 I->getOperand(0), I->getOperand(1), I->getName());
1683 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1684 return UpdateValueUsesWith(I, NewVal);
1685 }
1686
1687 // If the sign bit is the only bit demanded by this ashr, then there is no
1688 // need to do it, the shift doesn't change the high bit.
1689 if (DemandedMask.isSignBit())
1690 return UpdateValueUsesWith(I, I->getOperand(0));
1691
1692 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1693 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1694
1695 // Signed shift right.
1696 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1697 // If any of the "high bits" are demanded, we should set the sign bit as
1698 // demanded.
1699 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1700 DemandedMaskIn.set(BitWidth-1);
1701 if (SimplifyDemandedBits(I->getOperand(0),
1702 DemandedMaskIn,
1703 RHSKnownZero, RHSKnownOne, Depth+1))
1704 return true;
1705 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1706 "Bits known to be one AND zero?");
1707 // Compute the new bits that are at the top now.
1708 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1709 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1710 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1711
1712 // Handle the sign bits.
1713 APInt SignBit(APInt::getSignBit(BitWidth));
1714 // Adjust to where it is now in the mask.
1715 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1716
1717 // If the input sign bit is known to be zero, or if none of the top bits
1718 // are demanded, turn this into an unsigned shift right.
1719 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1720 (HighBits & ~DemandedMask) == HighBits) {
1721 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001722 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 I->getOperand(0), SA, I->getName());
1724 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1725 return UpdateValueUsesWith(I, NewVal);
1726 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1727 RHSKnownOne |= HighBits;
1728 }
1729 }
1730 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001731 case Instruction::SRem:
1732 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1733 APInt RA = Rem->getValue();
1734 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001735 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001736 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1737 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1738 LHSKnownZero, LHSKnownOne, Depth+1))
1739 return true;
1740
1741 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1742 LHSKnownZero |= ~LowBits;
1743 else if (LHSKnownOne[BitWidth-1])
1744 LHSKnownOne |= ~LowBits;
1745
1746 KnownZero |= LHSKnownZero & DemandedMask;
1747 KnownOne |= LHSKnownOne & DemandedMask;
1748
1749 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1750 }
1751 }
1752 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001753 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001754 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1755 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001756 if (RA.isPowerOf2()) {
1757 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001758 APInt Mask2 = LowBits & DemandedMask;
1759 KnownZero |= ~LowBits & DemandedMask;
1760 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1761 KnownZero, KnownOne, Depth+1))
1762 return true;
1763
1764 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001765 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001766 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001767 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001768
1769 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1770 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001771 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1772 KnownZero2, KnownOne2, Depth+1))
1773 return true;
1774
Dan Gohmanbec16052008-04-28 17:02:21 +00001775 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001776 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001777 KnownZero2, KnownOne2, Depth+1))
1778 return true;
1779
1780 Leaders = std::max(Leaders,
1781 KnownZero2.countLeadingOnes());
1782 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001783 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786
1787 // If the client is only demanding bits that we know, return the known
1788 // constant.
1789 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1790 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1791 return false;
1792}
1793
1794
1795/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1796/// 64 or fewer elements. DemandedElts contains the set of elements that are
1797/// actually used by the caller. This method analyzes which elements of the
1798/// operand are undef and returns that information in UndefElts.
1799///
1800/// If the information about demanded elements can be used to simplify the
1801/// operation, the operation is simplified, then the resultant value is
1802/// returned. This returns null if no change was made.
1803Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1804 uint64_t &UndefElts,
1805 unsigned Depth) {
1806 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1807 assert(VWidth <= 64 && "Vector too wide to analyze!");
1808 uint64_t EltMask = ~0ULL >> (64-VWidth);
1809 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1810 "Invalid DemandedElts!");
1811
1812 if (isa<UndefValue>(V)) {
1813 // If the entire vector is undefined, just return this info.
1814 UndefElts = EltMask;
1815 return 0;
1816 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1817 UndefElts = EltMask;
1818 return UndefValue::get(V->getType());
1819 }
1820
1821 UndefElts = 0;
1822 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1823 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1824 Constant *Undef = UndefValue::get(EltTy);
1825
1826 std::vector<Constant*> Elts;
1827 for (unsigned i = 0; i != VWidth; ++i)
1828 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1832 Elts.push_back(Undef);
1833 UndefElts |= (1ULL << i);
1834 } else { // Otherwise, defined.
1835 Elts.push_back(CP->getOperand(i));
1836 }
1837
1838 // If we changed the constant, return it.
1839 Constant *NewCP = ConstantVector::get(Elts);
1840 return NewCP != CP ? NewCP : 0;
1841 } else if (isa<ConstantAggregateZero>(V)) {
1842 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1843 // set to undef.
1844 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1845 Constant *Zero = Constant::getNullValue(EltTy);
1846 Constant *Undef = UndefValue::get(EltTy);
1847 std::vector<Constant*> Elts;
1848 for (unsigned i = 0; i != VWidth; ++i)
1849 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1850 UndefElts = DemandedElts ^ EltMask;
1851 return ConstantVector::get(Elts);
1852 }
1853
1854 if (!V->hasOneUse()) { // Other users may use these bits.
1855 if (Depth != 0) { // Not at the root.
1856 // TODO: Just compute the UndefElts information recursively.
1857 return false;
1858 }
1859 return false;
1860 } else if (Depth == 10) { // Limit search depth.
1861 return false;
1862 }
1863
1864 Instruction *I = dyn_cast<Instruction>(V);
1865 if (!I) return false; // Only analyze instructions.
1866
1867 bool MadeChange = false;
1868 uint64_t UndefElts2;
1869 Value *TmpV;
1870 switch (I->getOpcode()) {
1871 default: break;
1872
1873 case Instruction::InsertElement: {
1874 // If this is a variable index, we don't know which element it overwrites.
1875 // demand exactly the same input as we produce.
1876 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1877 if (Idx == 0) {
1878 // Note that we can't propagate undef elt info, because we don't know
1879 // which elt is getting updated.
1880 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1881 UndefElts2, Depth+1);
1882 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1883 break;
1884 }
1885
1886 // If this is inserting an element that isn't demanded, remove this
1887 // insertelement.
1888 unsigned IdxNo = Idx->getZExtValue();
1889 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1890 return AddSoonDeadInstToWorklist(*I, 0);
1891
1892 // Otherwise, the element inserted overwrites whatever was there, so the
1893 // input demanded set is simpler than the output set.
1894 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1895 DemandedElts & ~(1ULL << IdxNo),
1896 UndefElts, Depth+1);
1897 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1898
1899 // The inserted element is defined.
1900 UndefElts |= 1ULL << IdxNo;
1901 break;
1902 }
1903 case Instruction::BitCast: {
1904 // Vector->vector casts only.
1905 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1906 if (!VTy) break;
1907 unsigned InVWidth = VTy->getNumElements();
1908 uint64_t InputDemandedElts = 0;
1909 unsigned Ratio;
1910
1911 if (VWidth == InVWidth) {
1912 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1913 // elements as are demanded of us.
1914 Ratio = 1;
1915 InputDemandedElts = DemandedElts;
1916 } else if (VWidth > InVWidth) {
1917 // Untested so far.
1918 break;
1919
1920 // If there are more elements in the result than there are in the source,
1921 // then an input element is live if any of the corresponding output
1922 // elements are live.
1923 Ratio = VWidth/InVWidth;
1924 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1925 if (DemandedElts & (1ULL << OutIdx))
1926 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1927 }
1928 } else {
1929 // Untested so far.
1930 break;
1931
1932 // If there are more elements in the source than there are in the result,
1933 // then an input element is live if the corresponding output element is
1934 // live.
1935 Ratio = InVWidth/VWidth;
1936 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1937 if (DemandedElts & (1ULL << InIdx/Ratio))
1938 InputDemandedElts |= 1ULL << InIdx;
1939 }
1940
1941 // div/rem demand all inputs, because they don't want divide by zero.
1942 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1943 UndefElts2, Depth+1);
1944 if (TmpV) {
1945 I->setOperand(0, TmpV);
1946 MadeChange = true;
1947 }
1948
1949 UndefElts = UndefElts2;
1950 if (VWidth > InVWidth) {
1951 assert(0 && "Unimp");
1952 // If there are more elements in the result than there are in the source,
1953 // then an output element is undef if the corresponding input element is
1954 // undef.
1955 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1956 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1957 UndefElts |= 1ULL << OutIdx;
1958 } else if (VWidth < InVWidth) {
1959 assert(0 && "Unimp");
1960 // If there are more elements in the source than there are in the result,
1961 // then a result element is undef if all of the corresponding input
1962 // elements are undef.
1963 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1964 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1965 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1966 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1967 }
1968 break;
1969 }
1970 case Instruction::And:
1971 case Instruction::Or:
1972 case Instruction::Xor:
1973 case Instruction::Add:
1974 case Instruction::Sub:
1975 case Instruction::Mul:
1976 // div/rem demand all inputs, because they don't want divide by zero.
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1978 UndefElts, Depth+1);
1979 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1980 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1981 UndefElts2, Depth+1);
1982 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1983
1984 // Output elements are undefined if both are undefined. Consider things
1985 // like undef&0. The result is known zero, not undef.
1986 UndefElts &= UndefElts2;
1987 break;
1988
1989 case Instruction::Call: {
1990 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1991 if (!II) break;
1992 switch (II->getIntrinsicID()) {
1993 default: break;
1994
1995 // Binary vector operations that work column-wise. A dest element is a
1996 // function of the corresponding input elements from the two inputs.
1997 case Intrinsic::x86_sse_sub_ss:
1998 case Intrinsic::x86_sse_mul_ss:
1999 case Intrinsic::x86_sse_min_ss:
2000 case Intrinsic::x86_sse_max_ss:
2001 case Intrinsic::x86_sse2_sub_sd:
2002 case Intrinsic::x86_sse2_mul_sd:
2003 case Intrinsic::x86_sse2_min_sd:
2004 case Intrinsic::x86_sse2_max_sd:
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2006 UndefElts, Depth+1);
2007 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2008 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2009 UndefElts2, Depth+1);
2010 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2011
2012 // If only the low elt is demanded and this is a scalarizable intrinsic,
2013 // scalarize it now.
2014 if (DemandedElts == 1) {
2015 switch (II->getIntrinsicID()) {
2016 default: break;
2017 case Intrinsic::x86_sse_sub_ss:
2018 case Intrinsic::x86_sse_mul_ss:
2019 case Intrinsic::x86_sse2_sub_sd:
2020 case Intrinsic::x86_sse2_mul_sd:
2021 // TODO: Lower MIN/MAX/ABS/etc
2022 Value *LHS = II->getOperand(1);
2023 Value *RHS = II->getOperand(2);
2024 // Extract the element as scalars.
2025 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2026 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2027
2028 switch (II->getIntrinsicID()) {
2029 default: assert(0 && "Case stmts out of sync!");
2030 case Intrinsic::x86_sse_sub_ss:
2031 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002032 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033 II->getName()), *II);
2034 break;
2035 case Intrinsic::x86_sse_mul_ss:
2036 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002037 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038 II->getName()), *II);
2039 break;
2040 }
2041
2042 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00002043 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2044 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 InsertNewInstBefore(New, *II);
2046 AddSoonDeadInstToWorklist(*II, 0);
2047 return New;
2048 }
2049 }
2050
2051 // Output elements are undefined if both are undefined. Consider things
2052 // like undef&0. The result is known zero, not undef.
2053 UndefElts &= UndefElts2;
2054 break;
2055 }
2056 break;
2057 }
2058 }
2059 return MadeChange ? I : 0;
2060}
2061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062/// AssociativeOpt - Perform an optimization on an associative operator. This
2063/// function is designed to check a chain of associative operators for a
2064/// potential to apply a certain optimization. Since the optimization may be
2065/// applicable if the expression was reassociated, this checks the chain, then
2066/// reassociates the expression as necessary to expose the optimization
2067/// opportunity. This makes use of a special Functor, which must define
2068/// 'shouldApply' and 'apply' methods.
2069///
2070template<typename Functor>
2071Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2072 unsigned Opcode = Root.getOpcode();
2073 Value *LHS = Root.getOperand(0);
2074
2075 // Quick check, see if the immediate LHS matches...
2076 if (F.shouldApply(LHS))
2077 return F.apply(Root);
2078
2079 // Otherwise, if the LHS is not of the same opcode as the root, return.
2080 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2081 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2082 // Should we apply this transform to the RHS?
2083 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2084
2085 // If not to the RHS, check to see if we should apply to the LHS...
2086 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2087 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2088 ShouldApply = true;
2089 }
2090
2091 // If the functor wants to apply the optimization to the RHS of LHSI,
2092 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2093 if (ShouldApply) {
2094 BasicBlock *BB = Root.getParent();
2095
2096 // Now all of the instructions are in the current basic block, go ahead
2097 // and perform the reassociation.
2098 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2099
2100 // First move the selected RHS to the LHS of the root...
2101 Root.setOperand(0, LHSI->getOperand(1));
2102
2103 // Make what used to be the LHS of the root be the user of the root...
2104 Value *ExtraOperand = TmpLHSI->getOperand(1);
2105 if (&Root == TmpLHSI) {
2106 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2107 return 0;
2108 }
2109 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2110 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2111 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2112 BasicBlock::iterator ARI = &Root; ++ARI;
2113 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2114 ARI = Root;
2115
2116 // Now propagate the ExtraOperand down the chain of instructions until we
2117 // get to LHSI.
2118 while (TmpLHSI != LHSI) {
2119 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2120 // Move the instruction to immediately before the chain we are
2121 // constructing to avoid breaking dominance properties.
2122 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2123 BB->getInstList().insert(ARI, NextLHSI);
2124 ARI = NextLHSI;
2125
2126 Value *NextOp = NextLHSI->getOperand(1);
2127 NextLHSI->setOperand(1, ExtraOperand);
2128 TmpLHSI = NextLHSI;
2129 ExtraOperand = NextOp;
2130 }
2131
2132 // Now that the instructions are reassociated, have the functor perform
2133 // the transformation...
2134 return F.apply(Root);
2135 }
2136
2137 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2138 }
2139 return 0;
2140}
2141
Dan Gohman089efff2008-05-13 00:00:25 +00002142namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143
2144// AddRHS - Implements: X + X --> X << 1
2145struct AddRHS {
2146 Value *RHS;
2147 AddRHS(Value *rhs) : RHS(rhs) {}
2148 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2149 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002150 return BinaryOperator::CreateShl(Add.getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002151 ConstantInt::get(Add.getType(), 1));
2152 }
2153};
2154
2155// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2156// iff C1&C2 == 0
2157struct AddMaskingAnd {
2158 Constant *C2;
2159 AddMaskingAnd(Constant *c) : C2(c) {}
2160 bool shouldApply(Value *LHS) const {
2161 ConstantInt *C1;
2162 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2163 ConstantExpr::getAnd(C1, C2)->isNullValue();
2164 }
2165 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002166 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167 }
2168};
2169
Dan Gohman089efff2008-05-13 00:00:25 +00002170}
2171
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2173 InstCombiner *IC) {
2174 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2175 if (Constant *SOC = dyn_cast<Constant>(SO))
2176 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2177
Gabor Greifa645dd32008-05-16 19:29:10 +00002178 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2180 }
2181
2182 // Figure out if the constant is the left or the right argument.
2183 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2184 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2185
2186 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2187 if (ConstIsRHS)
2188 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2189 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2190 }
2191
2192 Value *Op0 = SO, *Op1 = ConstOperand;
2193 if (!ConstIsRHS)
2194 std::swap(Op0, Op1);
2195 Instruction *New;
2196 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002197 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002199 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 SO->getName()+".cmp");
2201 else {
2202 assert(0 && "Unknown binary instruction type!");
2203 abort();
2204 }
2205 return IC->InsertNewInstBefore(New, I);
2206}
2207
2208// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2209// constant as the other operand, try to fold the binary operator into the
2210// select arguments. This also works for Cast instructions, which obviously do
2211// not have a second operand.
2212static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2213 InstCombiner *IC) {
2214 // Don't modify shared select instructions
2215 if (!SI->hasOneUse()) return 0;
2216 Value *TV = SI->getOperand(1);
2217 Value *FV = SI->getOperand(2);
2218
2219 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2220 // Bool selects with constant operands can be folded to logical ops.
2221 if (SI->getType() == Type::Int1Ty) return 0;
2222
2223 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2224 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2225
Gabor Greifd6da1d02008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2227 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228 }
2229 return 0;
2230}
2231
2232
2233/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2234/// node as operand #0, see if we can fold the instruction into the PHI (which
2235/// is only possible if all operands to the PHI are constants).
2236Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2237 PHINode *PN = cast<PHINode>(I.getOperand(0));
2238 unsigned NumPHIValues = PN->getNumIncomingValues();
2239 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2240
2241 // Check to see if all of the operands of the PHI are constants. If there is
2242 // one non-constant value, remember the BB it is. If there is more than one
2243 // or if *it* is a PHI, bail out.
2244 BasicBlock *NonConstBB = 0;
2245 for (unsigned i = 0; i != NumPHIValues; ++i)
2246 if (!isa<Constant>(PN->getIncomingValue(i))) {
2247 if (NonConstBB) return 0; // More than one non-const value.
2248 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2249 NonConstBB = PN->getIncomingBlock(i);
2250
2251 // If the incoming non-constant value is in I's block, we have an infinite
2252 // loop.
2253 if (NonConstBB == I.getParent())
2254 return 0;
2255 }
2256
2257 // If there is exactly one non-constant value, we can insert a copy of the
2258 // operation in that block. However, if this is a critical edge, we would be
2259 // inserting the computation one some other paths (e.g. inside a loop). Only
2260 // do this if the pred block is unconditionally branching into the phi block.
2261 if (NonConstBB) {
2262 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2263 if (!BI || !BI->isUnconditional()) return 0;
2264 }
2265
2266 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002267 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2269 InsertNewInstBefore(NewPN, *PN);
2270 NewPN->takeName(PN);
2271
2272 // Next, add all of the operands to the PHI.
2273 if (I.getNumOperands() == 2) {
2274 Constant *C = cast<Constant>(I.getOperand(1));
2275 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002276 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2278 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2279 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2280 else
2281 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2282 } else {
2283 assert(PN->getIncomingBlock(i) == NonConstBB);
2284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002285 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 PN->getIncomingValue(i), C, "phitmp",
2287 NonConstBB->getTerminator());
2288 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002289 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290 CI->getPredicate(),
2291 PN->getIncomingValue(i), C, "phitmp",
2292 NonConstBB->getTerminator());
2293 else
2294 assert(0 && "Unknown binop!");
2295
2296 AddToWorkList(cast<Instruction>(InV));
2297 }
2298 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2299 }
2300 } else {
2301 CastInst *CI = cast<CastInst>(&I);
2302 const Type *RetTy = CI->getType();
2303 for (unsigned i = 0; i != NumPHIValues; ++i) {
2304 Value *InV;
2305 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2306 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2307 } else {
2308 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002309 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 I.getType(), "phitmp",
2311 NonConstBB->getTerminator());
2312 AddToWorkList(cast<Instruction>(InV));
2313 }
2314 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2315 }
2316 }
2317 return ReplaceInstUsesWith(I, NewPN);
2318}
2319
Chris Lattner55476162008-01-29 06:52:45 +00002320
2321/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2322/// value is never equal to -0.0.
2323///
2324/// Note that this function will need to be revisited when we support nondefault
2325/// rounding modes!
2326///
2327static bool CannotBeNegativeZero(const Value *V) {
2328 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2329 return !CFP->getValueAPF().isNegZero();
2330
Chris Lattner55476162008-01-29 06:52:45 +00002331 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnere3061db2008-05-19 20:27:56 +00002332 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner55476162008-01-29 06:52:45 +00002333 if (I->getOpcode() == Instruction::Add &&
2334 isa<ConstantFP>(I->getOperand(1)) &&
2335 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2336 return true;
2337
Chris Lattnere3061db2008-05-19 20:27:56 +00002338 // sitofp and uitofp turn into +0.0 for zero.
2339 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2340 return true;
2341
Chris Lattner55476162008-01-29 06:52:45 +00002342 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2343 if (II->getIntrinsicID() == Intrinsic::sqrt)
2344 return CannotBeNegativeZero(II->getOperand(1));
2345
2346 if (const CallInst *CI = dyn_cast<CallInst>(I))
2347 if (const Function *F = CI->getCalledFunction()) {
2348 if (F->isDeclaration()) {
2349 switch (F->getNameLen()) {
2350 case 3: // abs(x) != -0.0
2351 if (!strcmp(F->getNameStart(), "abs")) return true;
2352 break;
2353 case 4: // abs[lf](x) != -0.0
2354 if (!strcmp(F->getNameStart(), "absf")) return true;
2355 if (!strcmp(F->getNameStart(), "absl")) return true;
2356 break;
2357 }
2358 }
2359 }
2360 }
2361
2362 return false;
2363}
2364
2365
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2367 bool Changed = SimplifyCommutative(I);
2368 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2369
2370 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2371 // X + undef -> undef
2372 if (isa<UndefValue>(RHS))
2373 return ReplaceInstUsesWith(I, RHS);
2374
2375 // X + 0 --> X
2376 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2377 if (RHSC->isNullValue())
2378 return ReplaceInstUsesWith(I, LHS);
2379 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002380 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2381 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382 return ReplaceInstUsesWith(I, LHS);
2383 }
2384
2385 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2386 // X + (signbit) --> X ^ signbit
2387 const APInt& Val = CI->getValue();
2388 uint32_t BitWidth = Val.getBitWidth();
2389 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391
2392 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2393 // (X & 254)+1 -> (X&254)|1
2394 if (!isa<VectorType>(I.getType())) {
2395 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2396 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2397 KnownZero, KnownOne))
2398 return &I;
2399 }
2400 }
2401
2402 if (isa<PHINode>(LHS))
2403 if (Instruction *NV = FoldOpIntoPhi(I))
2404 return NV;
2405
2406 ConstantInt *XorRHS = 0;
2407 Value *XorLHS = 0;
2408 if (isa<ConstantInt>(RHSC) &&
2409 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2410 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2411 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2412
2413 uint32_t Size = TySizeBits / 2;
2414 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2415 APInt CFF80Val(-C0080Val);
2416 do {
2417 if (TySizeBits > Size) {
2418 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2419 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2420 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2421 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2422 // This is a sign extend if the top bits are known zero.
2423 if (!MaskedValueIsZero(XorLHS,
2424 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2425 Size = 0; // Not a sign ext, but can't be any others either.
2426 break;
2427 }
2428 }
2429 Size >>= 1;
2430 C0080Val = APIntOps::lshr(C0080Val, Size);
2431 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2432 } while (Size >= 1);
2433
2434 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002435 // with funny bit widths then this switch statement should be removed. It
2436 // is just here to get the size of the "middle" type back up to something
2437 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002438 const Type *MiddleType = 0;
2439 switch (Size) {
2440 default: break;
2441 case 32: MiddleType = Type::Int32Ty; break;
2442 case 16: MiddleType = Type::Int16Ty; break;
2443 case 8: MiddleType = Type::Int8Ty; break;
2444 }
2445 if (MiddleType) {
2446 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2447 InsertNewInstBefore(NewTrunc, I);
2448 return new SExtInst(NewTrunc, I.getType(), I.getName());
2449 }
2450 }
2451 }
2452
2453 // X + X --> X << 1
2454 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2455 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2456
2457 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2458 if (RHSI->getOpcode() == Instruction::Sub)
2459 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2460 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2461 }
2462 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2463 if (LHSI->getOpcode() == Instruction::Sub)
2464 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2465 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2466 }
2467 }
2468
2469 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002470 // -A + -B --> -(A + B)
2471 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002472 if (LHS->getType()->isIntOrIntVector()) {
2473 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002474 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002475 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002477 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002478 }
2479
Gabor Greifa645dd32008-05-16 19:29:10 +00002480 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002481 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482
2483 // A + -B --> A - B
2484 if (!isa<Constant>(RHS))
2485 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002486 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002487
2488
2489 ConstantInt *C2;
2490 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2491 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002492 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493
2494 // X*C1 + X*C2 --> X * (C1+C2)
2495 ConstantInt *C1;
2496 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002497 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 }
2499
2500 // X + X*C --> X * (C+1)
2501 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002503
2504 // X + ~X --> -1 since ~X = -X-1
2505 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2506 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2507
2508
2509 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2510 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2511 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2512 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002513
2514 // A+B --> A|B iff A and B have no bits set in common.
2515 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2516 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2517 APInt LHSKnownOne(IT->getBitWidth(), 0);
2518 APInt LHSKnownZero(IT->getBitWidth(), 0);
2519 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2520 if (LHSKnownZero != 0) {
2521 APInt RHSKnownOne(IT->getBitWidth(), 0);
2522 APInt RHSKnownZero(IT->getBitWidth(), 0);
2523 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2524
2525 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002526 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002527 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002528 }
2529 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530
Nick Lewycky83598a72008-02-03 07:42:09 +00002531 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002532 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002533 Value *W, *X, *Y, *Z;
2534 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2535 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2536 if (W != Y) {
2537 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002538 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002539 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002540 std::swap(W, X);
2541 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002542 std::swap(Y, Z);
2543 std::swap(W, X);
2544 }
2545 }
2546
2547 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002548 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002549 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002550 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002551 }
2552 }
2553 }
2554
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002555 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2556 Value *X = 0;
2557 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559
2560 // (X & FF00) + xx00 -> (X+xx00) & FF00
2561 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2562 Constant *Anded = And(CRHS, C2);
2563 if (Anded == CRHS) {
2564 // See if all bits from the first bit set in the Add RHS up are included
2565 // in the mask. First, get the rightmost bit.
2566 const APInt& AddRHSV = CRHS->getValue();
2567
2568 // Form a mask of all bits from the lowest bit added through the top.
2569 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2570
2571 // See if the and mask includes all of these bits.
2572 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2573
2574 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2575 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002576 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579 }
2580 }
2581 }
2582
2583 // Try to fold constant add into select arguments.
2584 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2585 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2586 return R;
2587 }
2588
2589 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002590 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591 {
2592 CastInst *CI = dyn_cast<CastInst>(LHS);
2593 Value *Other = RHS;
2594 if (!CI) {
2595 CI = dyn_cast<CastInst>(RHS);
2596 Other = LHS;
2597 }
2598 if (CI && CI->getType()->isSized() &&
2599 (CI->getType()->getPrimitiveSizeInBits() ==
2600 TD->getIntPtrType()->getPrimitiveSizeInBits())
2601 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002602 unsigned AS =
2603 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002604 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2605 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002606 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 return new PtrToIntInst(I2, CI->getType());
2608 }
2609 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002610
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002611 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002612 {
2613 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2614 Value *Other = RHS;
2615 if (!SI) {
2616 SI = dyn_cast<SelectInst>(RHS);
2617 Other = LHS;
2618 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002619 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002620 Value *TV = SI->getTrueValue();
2621 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002622 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002623
2624 // Can we fold the add into the argument of the select?
2625 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002626 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2627 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002628 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002629 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2630 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002631 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002632 }
2633 }
Chris Lattner55476162008-01-29 06:52:45 +00002634
2635 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2636 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2637 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2638 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639
2640 return Changed ? &I : 0;
2641}
2642
2643// isSignBit - Return true if the value represented by the constant only has the
2644// highest order bit set.
2645static bool isSignBit(ConstantInt *CI) {
2646 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2647 return CI->getValue() == APInt::getSignBit(NumBits);
2648}
2649
2650Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2651 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2652
2653 if (Op0 == Op1) // sub X, X -> 0
2654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2655
2656 // If this is a 'B = x-(-A)', change to B = x+A...
2657 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659
2660 if (isa<UndefValue>(Op0))
2661 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2662 if (isa<UndefValue>(Op1))
2663 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2664
2665 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2666 // Replace (-1 - A) with (~A)...
2667 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 // C - ~X == X + (1+C)
2671 Value *X = 0;
2672 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674
2675 // -(X >>u 31) -> (X >>s 31)
2676 // -(X >>s 31) -> (X >>u 31)
2677 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002678 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002679 if (SI->getOpcode() == Instruction::LShr) {
2680 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2681 // Check to see if we are shifting out everything but the sign bit.
2682 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2683 SI->getType()->getPrimitiveSizeInBits()-1) {
2684 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002685 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 SI->getOperand(0), CU, SI->getName());
2687 }
2688 }
2689 }
2690 else if (SI->getOpcode() == Instruction::AShr) {
2691 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2692 // Check to see if we are shifting out everything but the sign bit.
2693 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2694 SI->getType()->getPrimitiveSizeInBits()-1) {
2695 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002696 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 SI->getOperand(0), CU, SI->getName());
2698 }
2699 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002700 }
2701 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702 }
2703
2704 // Try to fold constant sub into select arguments.
2705 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2707 return R;
2708
2709 if (isa<PHINode>(Op0))
2710 if (Instruction *NV = FoldOpIntoPhi(I))
2711 return NV;
2712 }
2713
2714 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2715 if (Op1I->getOpcode() == Instruction::Add &&
2716 !Op0->getType()->isFPOrFPVector()) {
2717 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002718 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002720 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2722 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2723 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002724 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725 Op1I->getOperand(0));
2726 }
2727 }
2728
2729 if (Op1I->hasOneUse()) {
2730 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2731 // is not used by anyone else...
2732 //
2733 if (Op1I->getOpcode() == Instruction::Sub &&
2734 !Op1I->getType()->isFPOrFPVector()) {
2735 // Swap the two operands of the subexpr...
2736 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2737 Op1I->setOperand(0, IIOp1);
2738 Op1I->setOperand(1, IIOp0);
2739
2740 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002741 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742 }
2743
2744 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2745 //
2746 if (Op1I->getOpcode() == Instruction::And &&
2747 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2748 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2749
2750 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002751 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2752 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 }
2754
2755 // 0 - (X sdiv C) -> (X sdiv -C)
2756 if (Op1I->getOpcode() == Instruction::SDiv)
2757 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2758 if (CSI->isZero())
2759 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 ConstantExpr::getNeg(DivRHS));
2762
2763 // X - X*C --> X * (1-C)
2764 ConstantInt *C2 = 0;
2765 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2766 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 }
Dan Gohmanda338742007-09-17 17:31:57 +00002769
2770 // X - ((X / Y) * Y) --> X % Y
2771 if (Op1I->getOpcode() == Instruction::Mul)
2772 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2773 if (Op0 == I->getOperand(0) &&
2774 Op1I->getOperand(1) == I->getOperand(1)) {
2775 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002776 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002777 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002778 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002779 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 }
2781 }
2782
2783 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002784 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002785 if (Op0I->getOpcode() == Instruction::Add) {
2786 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2787 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2788 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2789 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2790 } else if (Op0I->getOpcode() == Instruction::Sub) {
2791 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002792 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002794 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795
2796 ConstantInt *C1;
2797 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2798 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800
2801 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2802 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002803 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 }
2805 return 0;
2806}
2807
2808/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2809/// comparison only checks the sign bit. If it only checks the sign bit, set
2810/// TrueIfSigned if the result of the comparison is true when the input value is
2811/// signed.
2812static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2813 bool &TrueIfSigned) {
2814 switch (pred) {
2815 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2816 TrueIfSigned = true;
2817 return RHS->isZero();
2818 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2819 TrueIfSigned = true;
2820 return RHS->isAllOnesValue();
2821 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2822 TrueIfSigned = false;
2823 return RHS->isAllOnesValue();
2824 case ICmpInst::ICMP_UGT:
2825 // True if LHS u> RHS and RHS == high-bit-mask - 1
2826 TrueIfSigned = true;
2827 return RHS->getValue() ==
2828 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2829 case ICmpInst::ICMP_UGE:
2830 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2831 TrueIfSigned = true;
2832 return RHS->getValue() ==
2833 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2834 default:
2835 return false;
2836 }
2837}
2838
2839Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2840 bool Changed = SimplifyCommutative(I);
2841 Value *Op0 = I.getOperand(0);
2842
2843 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2844 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2845
2846 // Simplify mul instructions with a constant RHS...
2847 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2849
2850 // ((X << C1)*C2) == (X * (C2 << C1))
2851 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2852 if (SI->getOpcode() == Instruction::Shl)
2853 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002854 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 ConstantExpr::getShl(CI, ShOp));
2856
2857 if (CI->isZero())
2858 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2859 if (CI->equalsInt(1)) // X * 1 == X
2860 return ReplaceInstUsesWith(I, Op0);
2861 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002862 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863
2864 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2865 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002866 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 ConstantInt::get(Op0->getType(), Val.logBase2()));
2868 }
2869 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2870 if (Op1F->isNullValue())
2871 return ReplaceInstUsesWith(I, Op1);
2872
2873 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2874 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002875 // We need a better interface for long double here.
2876 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2877 if (Op1F->isExactlyValue(1.0))
2878 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 }
2880
2881 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2882 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002883 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002884 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002885 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 Op1, "tmp");
2887 InsertNewInstBefore(Add, I);
2888 Value *C1C2 = ConstantExpr::getMul(Op1,
2889 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002890 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891
2892 }
2893
2894 // Try to fold constant mul into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897 return R;
2898
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2901 return NV;
2902 }
2903
2904 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2905 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002906 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907
2908 // If one of the operands of the multiply is a cast from a boolean value, then
2909 // we know the bool is either zero or one, so this is a 'masking' multiply.
2910 // See if we can simplify things based on how the boolean was originally
2911 // formed.
2912 CastInst *BoolCast = 0;
2913 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2914 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2915 BoolCast = CI;
2916 if (!BoolCast)
2917 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2918 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2919 BoolCast = CI;
2920 if (BoolCast) {
2921 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2922 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2923 const Type *SCOpTy = SCIOp0->getType();
2924 bool TIS = false;
2925
2926 // If the icmp is true iff the sign bit of X is set, then convert this
2927 // multiply into a shift/and combination.
2928 if (isa<ConstantInt>(SCIOp1) &&
2929 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2930 TIS) {
2931 // Shift the X value right to turn it into "all signbits".
2932 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2933 SCOpTy->getPrimitiveSizeInBits()-1);
2934 Value *V =
2935 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002936 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937 BoolCast->getOperand(0)->getName()+
2938 ".mask"), I);
2939
2940 // If the multiply type is not the same as the source type, sign extend
2941 // or truncate to the multiply type.
2942 if (I.getType() != V->getType()) {
2943 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2944 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2945 Instruction::CastOps opcode =
2946 (SrcBits == DstBits ? Instruction::BitCast :
2947 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2948 V = InsertCastBefore(opcode, V, I.getType(), I);
2949 }
2950
2951 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002952 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953 }
2954 }
2955 }
2956
2957 return Changed ? &I : 0;
2958}
2959
2960/// This function implements the transforms on div instructions that work
2961/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2962/// used by the visitors to those instructions.
2963/// @brief Transforms common to all three div instructions
2964Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2966
Chris Lattner653ef3c2008-02-19 06:12:18 +00002967 // undef / X -> 0 for integer.
2968 // undef / X -> undef for FP (the undef could be a snan).
2969 if (isa<UndefValue>(Op0)) {
2970 if (Op0->getType()->isFPOrFPVector())
2971 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002973 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974
2975 // X / undef -> undef
2976 if (isa<UndefValue>(Op1))
2977 return ReplaceInstUsesWith(I, Op1);
2978
Chris Lattner5be238b2008-01-28 00:58:18 +00002979 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2980 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002982 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2983 // the same basic block, then we replace the select with Y, and the
2984 // condition of the select with false (if the cond value is in the same BB).
2985 // If the select has uses other than the div, this allows them to be
2986 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2987 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 if (ST->isNullValue()) {
2989 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2990 if (CondI && CondI->getParent() == I.getParent())
2991 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2992 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2993 I.setOperand(1, SI->getOperand(2));
2994 else
2995 UpdateValueUsesWith(SI, SI->getOperand(2));
2996 return &I;
2997 }
2998
Chris Lattner5be238b2008-01-28 00:58:18 +00002999 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3000 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 if (ST->isNullValue()) {
3002 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3003 if (CondI && CondI->getParent() == I.getParent())
3004 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3005 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3006 I.setOperand(1, SI->getOperand(1));
3007 else
3008 UpdateValueUsesWith(SI, SI->getOperand(1));
3009 return &I;
3010 }
3011 }
3012
3013 return 0;
3014}
3015
3016/// This function implements the transforms common to both integer division
3017/// instructions (udiv and sdiv). It is called by the visitors to those integer
3018/// division instructions.
3019/// @brief Common integer divide transforms
3020Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
Chris Lattnercefb36c2008-05-16 02:59:42 +00003023 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3024 if (Op0 == Op1)
3025 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 if (Instruction *Common = commonDivTransforms(I))
3028 return Common;
3029
3030 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3031 // div X, 1 == X
3032 if (RHS->equalsInt(1))
3033 return ReplaceInstUsesWith(I, Op0);
3034
3035 // (X / C1) / C2 -> X / (C1*C2)
3036 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3037 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3038 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00003039 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3041 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003042 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00003043 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003044 }
3045
3046 if (!RHS->isZero()) { // avoid X udiv 0
3047 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3048 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3049 return R;
3050 if (isa<PHINode>(Op0))
3051 if (Instruction *NV = FoldOpIntoPhi(I))
3052 return NV;
3053 }
3054 }
3055
3056 // 0 / X == 0, we don't need to preserve faults!
3057 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3058 if (LHS->equalsInt(0))
3059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3060
3061 return 0;
3062}
3063
3064Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3066
3067 // Handle the integer div common cases
3068 if (Instruction *Common = commonIDivTransforms(I))
3069 return Common;
3070
3071 // X udiv C^2 -> X >> C
3072 // Check to see if this is an unsigned division with an exact power of 2,
3073 // if so, convert to a right shift.
3074 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3075 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003076 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003077 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3078 }
3079
3080 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3081 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3082 if (RHSI->getOpcode() == Instruction::Shl &&
3083 isa<ConstantInt>(RHSI->getOperand(0))) {
3084 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3085 if (C1.isPowerOf2()) {
3086 Value *N = RHSI->getOperand(1);
3087 const Type *NTy = N->getType();
3088 if (uint32_t C2 = C1.logBase2()) {
3089 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003090 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003092 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093 }
3094 }
3095 }
3096
3097 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3098 // where C1&C2 are powers of two.
3099 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3100 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3101 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3102 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3103 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3104 // Compute the shift amounts
3105 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3106 // Construct the "on true" case of the select
3107 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003108 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 Op0, TC, SI->getName()+".t");
3110 TSI = InsertNewInstBefore(TSI, I);
3111
3112 // Construct the "on false" case of the select
3113 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003114 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115 Op0, FC, SI->getName()+".f");
3116 FSI = InsertNewInstBefore(FSI, I);
3117
3118 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003119 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 }
3121 }
3122 return 0;
3123}
3124
3125Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3126 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3127
3128 // Handle the integer div common cases
3129 if (Instruction *Common = commonIDivTransforms(I))
3130 return Common;
3131
3132 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3133 // sdiv X, -1 == -X
3134 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003135 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136
3137 // -X/C -> X/-C
3138 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00003139 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 }
3141
3142 // If the sign bits of both operands are zero (i.e. we can prove they are
3143 // unsigned inputs), turn this into a udiv.
3144 if (I.getType()->isInteger()) {
3145 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3146 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003147 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003148 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149 }
3150 }
3151
3152 return 0;
3153}
3154
3155Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3156 return commonDivTransforms(I);
3157}
3158
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159/// This function implements the transforms on rem instructions that work
3160/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3161/// is used by the visitors to those instructions.
3162/// @brief Transforms common to all three rem instructions
3163Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3165
Chris Lattner653ef3c2008-02-19 06:12:18 +00003166 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 if (Constant *LHS = dyn_cast<Constant>(Op0))
3168 if (LHS->isNullValue())
3169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3170
Chris Lattner653ef3c2008-02-19 06:12:18 +00003171 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3172 if (I.getType()->isFPOrFPVector())
3173 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003175 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 if (isa<UndefValue>(Op1))
3177 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3178
3179 // Handle cases involving: rem X, (select Cond, Y, Z)
3180 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3181 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3182 // the same basic block, then we replace the select with Y, and the
3183 // condition of the select with false (if the cond value is in the same
3184 // BB). If the select has uses other than the div, this allows them to be
3185 // simplified also.
3186 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3187 if (ST->isNullValue()) {
3188 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3189 if (CondI && CondI->getParent() == I.getParent())
3190 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3191 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3192 I.setOperand(1, SI->getOperand(2));
3193 else
3194 UpdateValueUsesWith(SI, SI->getOperand(2));
3195 return &I;
3196 }
3197 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3198 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3199 if (ST->isNullValue()) {
3200 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3201 if (CondI && CondI->getParent() == I.getParent())
3202 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3203 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3204 I.setOperand(1, SI->getOperand(1));
3205 else
3206 UpdateValueUsesWith(SI, SI->getOperand(1));
3207 return &I;
3208 }
3209 }
3210
3211 return 0;
3212}
3213
3214/// This function implements the transforms common to both integer remainder
3215/// instructions (urem and srem). It is called by the visitors to those integer
3216/// remainder instructions.
3217/// @brief Common integer remainder transforms
3218Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3220
3221 if (Instruction *common = commonRemTransforms(I))
3222 return common;
3223
3224 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3225 // X % 0 == undef, we don't need to preserve faults!
3226 if (RHS->equalsInt(0))
3227 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3228
3229 if (RHS->equalsInt(1)) // X % 1 == 0
3230 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3231
3232 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3233 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3234 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3235 return R;
3236 } else if (isa<PHINode>(Op0I)) {
3237 if (Instruction *NV = FoldOpIntoPhi(I))
3238 return NV;
3239 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003240
3241 // See if we can fold away this rem instruction.
3242 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3243 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3244 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3245 KnownZero, KnownOne))
3246 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 }
3248 }
3249
3250 return 0;
3251}
3252
3253Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
3256 if (Instruction *common = commonIRemTransforms(I))
3257 return common;
3258
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3260 // X urem C^2 -> X and C
3261 // Check to see if this is an unsigned remainder with an exact power of 2,
3262 // if so, convert to a bitwise and.
3263 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3264 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003265 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003266 }
3267
3268 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3269 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3270 if (RHSI->getOpcode() == Instruction::Shl &&
3271 isa<ConstantInt>(RHSI->getOperand(0))) {
3272 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3273 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003274 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003276 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277 }
3278 }
3279 }
3280
3281 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3282 // where C1&C2 are powers of two.
3283 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3284 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3285 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3286 // STO == 0 and SFO == 0 handled above.
3287 if ((STO->getValue().isPowerOf2()) &&
3288 (SFO->getValue().isPowerOf2())) {
3289 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003290 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003292 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003293 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294 }
3295 }
3296 }
3297
3298 return 0;
3299}
3300
3301Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3303
Dan Gohmandb3dd962007-11-05 23:16:33 +00003304 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 if (Instruction *common = commonIRemTransforms(I))
3306 return common;
3307
3308 if (Value *RHSNeg = dyn_castNegVal(Op1))
3309 if (!isa<ConstantInt>(RHSNeg) ||
3310 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3311 // X % -Y -> X % Y
3312 AddUsesToWorkList(I);
3313 I.setOperand(1, RHSNeg);
3314 return &I;
3315 }
3316
Dan Gohmandb3dd962007-11-05 23:16:33 +00003317 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003319 if (I.getType()->isInteger()) {
3320 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3321 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3322 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003323 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003324 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003325 }
3326
3327 return 0;
3328}
3329
3330Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3331 return commonRemTransforms(I);
3332}
3333
3334// isMaxValueMinusOne - return true if this is Max-1
3335static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3336 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3337 if (!isSigned)
3338 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3339 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3340}
3341
3342// isMinValuePlusOne - return true if this is Min+1
3343static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3344 if (!isSigned)
3345 return C->getValue() == 1; // unsigned
3346
3347 // Calculate 1111111111000000000000
3348 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3349 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3350}
3351
3352// isOneBitSet - Return true if there is exactly one bit set in the specified
3353// constant.
3354static bool isOneBitSet(const ConstantInt *CI) {
3355 return CI->getValue().isPowerOf2();
3356}
3357
3358// isHighOnes - Return true if the constant is of the form 1+0+.
3359// This is the same as lowones(~X).
3360static bool isHighOnes(const ConstantInt *CI) {
3361 return (~CI->getValue() + 1).isPowerOf2();
3362}
3363
3364/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3365/// are carefully arranged to allow folding of expressions such as:
3366///
3367/// (A < B) | (A > B) --> (A != B)
3368///
3369/// Note that this is only valid if the first and second predicates have the
3370/// same sign. Is illegal to do: (A u< B) | (A s> B)
3371///
3372/// Three bits are used to represent the condition, as follows:
3373/// 0 A > B
3374/// 1 A == B
3375/// 2 A < B
3376///
3377/// <=> Value Definition
3378/// 000 0 Always false
3379/// 001 1 A > B
3380/// 010 2 A == B
3381/// 011 3 A >= B
3382/// 100 4 A < B
3383/// 101 5 A != B
3384/// 110 6 A <= B
3385/// 111 7 Always true
3386///
3387static unsigned getICmpCode(const ICmpInst *ICI) {
3388 switch (ICI->getPredicate()) {
3389 // False -> 0
3390 case ICmpInst::ICMP_UGT: return 1; // 001
3391 case ICmpInst::ICMP_SGT: return 1; // 001
3392 case ICmpInst::ICMP_EQ: return 2; // 010
3393 case ICmpInst::ICMP_UGE: return 3; // 011
3394 case ICmpInst::ICMP_SGE: return 3; // 011
3395 case ICmpInst::ICMP_ULT: return 4; // 100
3396 case ICmpInst::ICMP_SLT: return 4; // 100
3397 case ICmpInst::ICMP_NE: return 5; // 101
3398 case ICmpInst::ICMP_ULE: return 6; // 110
3399 case ICmpInst::ICMP_SLE: return 6; // 110
3400 // True -> 7
3401 default:
3402 assert(0 && "Invalid ICmp predicate!");
3403 return 0;
3404 }
3405}
3406
3407/// getICmpValue - This is the complement of getICmpCode, which turns an
3408/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003409/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410/// of predicate to use in new icmp instructions.
3411static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3412 switch (code) {
3413 default: assert(0 && "Illegal ICmp code!");
3414 case 0: return ConstantInt::getFalse();
3415 case 1:
3416 if (sign)
3417 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3418 else
3419 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3420 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3421 case 3:
3422 if (sign)
3423 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3424 else
3425 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3426 case 4:
3427 if (sign)
3428 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3429 else
3430 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3431 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3432 case 6:
3433 if (sign)
3434 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3435 else
3436 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3437 case 7: return ConstantInt::getTrue();
3438 }
3439}
3440
3441static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3442 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3443 (ICmpInst::isSignedPredicate(p1) &&
3444 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3445 (ICmpInst::isSignedPredicate(p2) &&
3446 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3447}
3448
3449namespace {
3450// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3451struct FoldICmpLogical {
3452 InstCombiner &IC;
3453 Value *LHS, *RHS;
3454 ICmpInst::Predicate pred;
3455 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3456 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3457 pred(ICI->getPredicate()) {}
3458 bool shouldApply(Value *V) const {
3459 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3460 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003461 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3462 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003463 return false;
3464 }
3465 Instruction *apply(Instruction &Log) const {
3466 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3467 if (ICI->getOperand(0) != LHS) {
3468 assert(ICI->getOperand(1) == LHS);
3469 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3470 }
3471
3472 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3473 unsigned LHSCode = getICmpCode(ICI);
3474 unsigned RHSCode = getICmpCode(RHSICI);
3475 unsigned Code;
3476 switch (Log.getOpcode()) {
3477 case Instruction::And: Code = LHSCode & RHSCode; break;
3478 case Instruction::Or: Code = LHSCode | RHSCode; break;
3479 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3480 default: assert(0 && "Illegal logical opcode!"); return 0;
3481 }
3482
3483 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3484 ICmpInst::isSignedPredicate(ICI->getPredicate());
3485
3486 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3487 if (Instruction *I = dyn_cast<Instruction>(RV))
3488 return I;
3489 // Otherwise, it's a constant boolean value...
3490 return IC.ReplaceInstUsesWith(Log, RV);
3491 }
3492};
3493} // end anonymous namespace
3494
3495// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3496// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3497// guaranteed to be a binary operator.
3498Instruction *InstCombiner::OptAndOp(Instruction *Op,
3499 ConstantInt *OpRHS,
3500 ConstantInt *AndRHS,
3501 BinaryOperator &TheAnd) {
3502 Value *X = Op->getOperand(0);
3503 Constant *Together = 0;
3504 if (!Op->isShift())
3505 Together = And(AndRHS, OpRHS);
3506
3507 switch (Op->getOpcode()) {
3508 case Instruction::Xor:
3509 if (Op->hasOneUse()) {
3510 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003511 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 InsertNewInstBefore(And, TheAnd);
3513 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 }
3516 break;
3517 case Instruction::Or:
3518 if (Together == AndRHS) // (X | C) & C --> C
3519 return ReplaceInstUsesWith(TheAnd, AndRHS);
3520
3521 if (Op->hasOneUse() && Together != OpRHS) {
3522 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003523 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 InsertNewInstBefore(Or, TheAnd);
3525 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003526 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527 }
3528 break;
3529 case Instruction::Add:
3530 if (Op->hasOneUse()) {
3531 // Adding a one to a single bit bit-field should be turned into an XOR
3532 // of the bit. First thing to check is to see if this AND is with a
3533 // single bit constant.
3534 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3535
3536 // If there is only one bit set...
3537 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3538 // Ok, at this point, we know that we are masking the result of the
3539 // ADD down to exactly one bit. If the constant we are adding has
3540 // no bits set below this bit, then we can eliminate the ADD.
3541 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3542
3543 // Check to see if any bits below the one bit set in AndRHSV are set.
3544 if ((AddRHS & (AndRHSV-1)) == 0) {
3545 // If not, the only thing that can effect the output of the AND is
3546 // the bit specified by AndRHSV. If that bit is set, the effect of
3547 // the XOR is to toggle the bit. If it is clear, then the ADD has
3548 // no effect.
3549 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3550 TheAnd.setOperand(0, X);
3551 return &TheAnd;
3552 } else {
3553 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003554 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 InsertNewInstBefore(NewAnd, TheAnd);
3556 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003557 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 }
3559 }
3560 }
3561 }
3562 break;
3563
3564 case Instruction::Shl: {
3565 // We know that the AND will not produce any of the bits shifted in, so if
3566 // the anded constant includes them, clear them now!
3567 //
3568 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3569 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3570 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3571 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3572
3573 if (CI->getValue() == ShlMask) {
3574 // Masking out bits that the shift already masks
3575 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3576 } else if (CI != AndRHS) { // Reducing bits set in and.
3577 TheAnd.setOperand(1, CI);
3578 return &TheAnd;
3579 }
3580 break;
3581 }
3582 case Instruction::LShr:
3583 {
3584 // We know that the AND will not produce any of the bits shifted in, so if
3585 // the anded constant includes them, clear them now! This only applies to
3586 // unsigned shifts, because a signed shr may bring in set bits!
3587 //
3588 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3589 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3590 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3591 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3592
3593 if (CI->getValue() == ShrMask) {
3594 // Masking out bits that the shift already masks.
3595 return ReplaceInstUsesWith(TheAnd, Op);
3596 } else if (CI != AndRHS) {
3597 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3598 return &TheAnd;
3599 }
3600 break;
3601 }
3602 case Instruction::AShr:
3603 // Signed shr.
3604 // See if this is shifting in some sign extension, then masking it out
3605 // with an and.
3606 if (Op->hasOneUse()) {
3607 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3608 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3609 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3610 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3611 if (C == AndRHS) { // Masking out bits shifted in.
3612 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3613 // Make the argument unsigned.
3614 Value *ShVal = Op->getOperand(0);
3615 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003616 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003617 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003618 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 }
3620 }
3621 break;
3622 }
3623 return 0;
3624}
3625
3626
3627/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3628/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3629/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3630/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3631/// insert new instructions.
3632Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3633 bool isSigned, bool Inside,
3634 Instruction &IB) {
3635 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3636 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3637 "Lo is not <= Hi in range emission code!");
3638
3639 if (Inside) {
3640 if (Lo == Hi) // Trivially false.
3641 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3642
3643 // V >= Min && V < Hi --> V < Hi
3644 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3645 ICmpInst::Predicate pred = (isSigned ?
3646 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3647 return new ICmpInst(pred, V, Hi);
3648 }
3649
3650 // Emit V-Lo <u Hi-Lo
3651 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003652 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653 InsertNewInstBefore(Add, IB);
3654 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3655 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3656 }
3657
3658 if (Lo == Hi) // Trivially true.
3659 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3660
3661 // V < Min || V >= Hi -> V > Hi-1
3662 Hi = SubOne(cast<ConstantInt>(Hi));
3663 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3664 ICmpInst::Predicate pred = (isSigned ?
3665 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3666 return new ICmpInst(pred, V, Hi);
3667 }
3668
3669 // Emit V-Lo >u Hi-1-Lo
3670 // Note that Hi has already had one subtracted from it, above.
3671 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003672 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003673 InsertNewInstBefore(Add, IB);
3674 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3675 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3676}
3677
3678// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3679// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3680// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3681// not, since all 1s are not contiguous.
3682static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3683 const APInt& V = Val->getValue();
3684 uint32_t BitWidth = Val->getType()->getBitWidth();
3685 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3686
3687 // look for the first zero bit after the run of ones
3688 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3689 // look for the first non-zero bit
3690 ME = V.getActiveBits();
3691 return true;
3692}
3693
3694/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3695/// where isSub determines whether the operator is a sub. If we can fold one of
3696/// the following xforms:
3697///
3698/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3699/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3700/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701///
3702/// return (A +/- B).
3703///
3704Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3705 ConstantInt *Mask, bool isSub,
3706 Instruction &I) {
3707 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3708 if (!LHSI || LHSI->getNumOperands() != 2 ||
3709 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3710
3711 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3712
3713 switch (LHSI->getOpcode()) {
3714 default: return 0;
3715 case Instruction::And:
3716 if (And(N, Mask) == Mask) {
3717 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3718 if ((Mask->getValue().countLeadingZeros() +
3719 Mask->getValue().countPopulation()) ==
3720 Mask->getValue().getBitWidth())
3721 break;
3722
3723 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3724 // part, we don't need any explicit masks to take them out of A. If that
3725 // is all N is, ignore it.
3726 uint32_t MB = 0, ME = 0;
3727 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3728 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3729 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3730 if (MaskedValueIsZero(RHS, Mask))
3731 break;
3732 }
3733 }
3734 return 0;
3735 case Instruction::Or:
3736 case Instruction::Xor:
3737 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3738 if ((Mask->getValue().countLeadingZeros() +
3739 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3740 && And(N, Mask)->isZero())
3741 break;
3742 return 0;
3743 }
3744
3745 Instruction *New;
3746 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003747 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003749 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003750 return InsertNewInstBefore(New, I);
3751}
3752
3753Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3754 bool Changed = SimplifyCommutative(I);
3755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3756
3757 if (isa<UndefValue>(Op1)) // X & undef -> 0
3758 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3759
3760 // and X, X = X
3761 if (Op0 == Op1)
3762 return ReplaceInstUsesWith(I, Op1);
3763
3764 // See if we can simplify any instructions used by the instruction whose sole
3765 // purpose is to compute bits we don't care about.
3766 if (!isa<VectorType>(I.getType())) {
3767 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3768 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3769 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3770 KnownZero, KnownOne))
3771 return &I;
3772 } else {
3773 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3774 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3775 return ReplaceInstUsesWith(I, I.getOperand(0));
3776 } else if (isa<ConstantAggregateZero>(Op1)) {
3777 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3778 }
3779 }
3780
3781 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3782 const APInt& AndRHSMask = AndRHS->getValue();
3783 APInt NotAndRHS(~AndRHSMask);
3784
3785 // Optimize a variety of ((val OP C1) & C2) combinations...
3786 if (isa<BinaryOperator>(Op0)) {
3787 Instruction *Op0I = cast<Instruction>(Op0);
3788 Value *Op0LHS = Op0I->getOperand(0);
3789 Value *Op0RHS = Op0I->getOperand(1);
3790 switch (Op0I->getOpcode()) {
3791 case Instruction::Xor:
3792 case Instruction::Or:
3793 // If the mask is only needed on one incoming arm, push it up.
3794 if (Op0I->hasOneUse()) {
3795 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3796 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003797 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 Op0RHS->getName()+".masked");
3799 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003800 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003801 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3802 }
3803 if (!isa<Constant>(Op0RHS) &&
3804 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3805 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003806 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 Op0LHS->getName()+".masked");
3808 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003809 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3811 }
3812 }
3813
3814 break;
3815 case Instruction::Add:
3816 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3817 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3818 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3819 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003820 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003821 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003822 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003823 break;
3824
3825 case Instruction::Sub:
3826 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3827 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3828 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3829 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003830 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831 break;
3832 }
3833
3834 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3835 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3836 return Res;
3837 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3838 // If this is an integer truncation or change from signed-to-unsigned, and
3839 // if the source is an and/or with immediate, transform it. This
3840 // frequently occurs for bitfield accesses.
3841 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3842 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3843 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003844 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 if (CastOp->getOpcode() == Instruction::And) {
3846 // Change: and (cast (and X, C1) to T), C2
3847 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3848 // This will fold the two constants together, which may allow
3849 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003850 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003851 CastOp->getOperand(0), I.getType(),
3852 CastOp->getName()+".shrunk");
3853 NewCast = InsertNewInstBefore(NewCast, I);
3854 // trunc_or_bitcast(C1)&C2
3855 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3856 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003857 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 } else if (CastOp->getOpcode() == Instruction::Or) {
3859 // Change: and (cast (or X, C1) to T), C2
3860 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3861 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3862 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3863 return ReplaceInstUsesWith(I, AndRHS);
3864 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 }
3867 }
3868
3869 // Try to fold constant and into select arguments.
3870 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3871 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3872 return R;
3873 if (isa<PHINode>(Op0))
3874 if (Instruction *NV = FoldOpIntoPhi(I))
3875 return NV;
3876 }
3877
3878 Value *Op0NotVal = dyn_castNotVal(Op0);
3879 Value *Op1NotVal = dyn_castNotVal(Op1);
3880
3881 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3883
3884 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3885 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003886 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003887 I.getName()+".demorgan");
3888 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003889 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003890 }
3891
3892 {
3893 Value *A = 0, *B = 0, *C = 0, *D = 0;
3894 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3895 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3896 return ReplaceInstUsesWith(I, Op1);
3897
3898 // (A|B) & ~(A&B) -> A^B
3899 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3900 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 }
3903 }
3904
3905 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3906 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3907 return ReplaceInstUsesWith(I, Op0);
3908
3909 // ~(A&B) & (A|B) -> A^B
3910 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3911 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003912 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003913 }
3914 }
3915
3916 if (Op0->hasOneUse() &&
3917 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3918 if (A == Op1) { // (A^B)&A -> A&(A^B)
3919 I.swapOperands(); // Simplify below
3920 std::swap(Op0, Op1);
3921 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3922 cast<BinaryOperator>(Op0)->swapOperands();
3923 I.swapOperands(); // Simplify below
3924 std::swap(Op0, Op1);
3925 }
3926 }
3927 if (Op1->hasOneUse() &&
3928 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3929 if (B == Op0) { // B&(A^B) -> B&(B^A)
3930 cast<BinaryOperator>(Op1)->swapOperands();
3931 std::swap(A, B);
3932 }
3933 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003934 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003935 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003936 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 }
3938 }
3939 }
3940
3941 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3942 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3943 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3944 return R;
3945
3946 Value *LHSVal, *RHSVal;
3947 ConstantInt *LHSCst, *RHSCst;
3948 ICmpInst::Predicate LHSCC, RHSCC;
3949 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3950 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3951 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3952 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3953 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3954 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3955 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003956 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3957
3958 // Don't try to fold ICMP_SLT + ICMP_ULT.
3959 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3960 ICmpInst::isSignedPredicate(LHSCC) ==
3961 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003963 ICmpInst::Predicate GT;
3964 if (ICmpInst::isSignedPredicate(LHSCC) ||
3965 (ICmpInst::isEquality(LHSCC) &&
3966 ICmpInst::isSignedPredicate(RHSCC)))
3967 GT = ICmpInst::ICMP_SGT;
3968 else
3969 GT = ICmpInst::ICMP_UGT;
3970
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003971 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3972 ICmpInst *LHS = cast<ICmpInst>(Op0);
3973 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3974 std::swap(LHS, RHS);
3975 std::swap(LHSCst, RHSCst);
3976 std::swap(LHSCC, RHSCC);
3977 }
3978
3979 // At this point, we know we have have two icmp instructions
3980 // comparing a value against two constants and and'ing the result
3981 // together. Because of the above check, we know that we only have
3982 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3983 // (from the FoldICmpLogical check above), that the two constants
3984 // are not equal and that the larger constant is on the RHS
3985 assert(LHSCst != RHSCst && "Compares not folded above?");
3986
3987 switch (LHSCC) {
3988 default: assert(0 && "Unknown integer condition code!");
3989 case ICmpInst::ICMP_EQ:
3990 switch (RHSCC) {
3991 default: assert(0 && "Unknown integer condition code!");
3992 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3993 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3994 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3995 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3996 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3997 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3998 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3999 return ReplaceInstUsesWith(I, LHS);
4000 }
4001 case ICmpInst::ICMP_NE:
4002 switch (RHSCC) {
4003 default: assert(0 && "Unknown integer condition code!");
4004 case ICmpInst::ICMP_ULT:
4005 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4006 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4007 break; // (X != 13 & X u< 15) -> no change
4008 case ICmpInst::ICMP_SLT:
4009 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4010 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4011 break; // (X != 13 & X s< 15) -> no change
4012 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4013 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4014 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4015 return ReplaceInstUsesWith(I, RHS);
4016 case ICmpInst::ICMP_NE:
4017 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4018 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004019 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004020 LHSVal->getName()+".off");
4021 InsertNewInstBefore(Add, I);
4022 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4023 ConstantInt::get(Add->getType(), 1));
4024 }
4025 break; // (X != 13 & X != 15) -> no change
4026 }
4027 break;
4028 case ICmpInst::ICMP_ULT:
4029 switch (RHSCC) {
4030 default: assert(0 && "Unknown integer condition code!");
4031 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4032 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4033 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4034 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4035 break;
4036 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4037 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4038 return ReplaceInstUsesWith(I, LHS);
4039 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4040 break;
4041 }
4042 break;
4043 case ICmpInst::ICMP_SLT:
4044 switch (RHSCC) {
4045 default: assert(0 && "Unknown integer condition code!");
4046 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4047 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4048 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4049 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4050 break;
4051 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4052 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4053 return ReplaceInstUsesWith(I, LHS);
4054 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4055 break;
4056 }
4057 break;
4058 case ICmpInst::ICMP_UGT:
4059 switch (RHSCC) {
4060 default: assert(0 && "Unknown integer condition code!");
4061 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4062 return ReplaceInstUsesWith(I, LHS);
4063 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4064 return ReplaceInstUsesWith(I, RHS);
4065 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4066 break;
4067 case ICmpInst::ICMP_NE:
4068 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4069 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4070 break; // (X u> 13 & X != 15) -> no change
4071 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4072 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4073 true, I);
4074 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4075 break;
4076 }
4077 break;
4078 case ICmpInst::ICMP_SGT:
4079 switch (RHSCC) {
4080 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004081 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004082 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4083 return ReplaceInstUsesWith(I, RHS);
4084 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4085 break;
4086 case ICmpInst::ICMP_NE:
4087 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4088 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4089 break; // (X s> 13 & X != 15) -> no change
4090 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4091 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4092 true, I);
4093 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4094 break;
4095 }
4096 break;
4097 }
4098 }
4099 }
4100
4101 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4102 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4103 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4104 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4105 const Type *SrcTy = Op0C->getOperand(0)->getType();
4106 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4107 // Only do this if the casts both really cause code to be generated.
4108 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4109 I.getType(), TD) &&
4110 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4111 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004112 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004113 Op1C->getOperand(0),
4114 I.getName());
4115 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004116 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004117 }
4118 }
4119
4120 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4121 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4122 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4123 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4124 SI0->getOperand(1) == SI1->getOperand(1) &&
4125 (SI0->hasOneUse() || SI1->hasOneUse())) {
4126 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004127 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 SI1->getOperand(0),
4129 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004130 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004131 SI1->getOperand(1));
4132 }
4133 }
4134
Chris Lattner91882432007-10-24 05:38:08 +00004135 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4136 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4137 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4138 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4139 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4140 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4141 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4142 // If either of the constants are nans, then the whole thing returns
4143 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004144 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004145 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4146 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4147 RHS->getOperand(0));
4148 }
4149 }
4150 }
4151
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 return Changed ? &I : 0;
4153}
4154
4155/// CollectBSwapParts - Look to see if the specified value defines a single byte
4156/// in the result. If it does, and if the specified byte hasn't been filled in
4157/// yet, fill it in and return false.
4158static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4159 Instruction *I = dyn_cast<Instruction>(V);
4160 if (I == 0) return true;
4161
4162 // If this is an or instruction, it is an inner node of the bswap.
4163 if (I->getOpcode() == Instruction::Or)
4164 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4165 CollectBSwapParts(I->getOperand(1), ByteValues);
4166
4167 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4168 // If this is a shift by a constant int, and it is "24", then its operand
4169 // defines a byte. We only handle unsigned types here.
4170 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4171 // Not shifting the entire input by N-1 bytes?
4172 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4173 8*(ByteValues.size()-1))
4174 return true;
4175
4176 unsigned DestNo;
4177 if (I->getOpcode() == Instruction::Shl) {
4178 // X << 24 defines the top byte with the lowest of the input bytes.
4179 DestNo = ByteValues.size()-1;
4180 } else {
4181 // X >>u 24 defines the low byte with the highest of the input bytes.
4182 DestNo = 0;
4183 }
4184
4185 // If the destination byte value is already defined, the values are or'd
4186 // together, which isn't a bswap (unless it's an or of the same bits).
4187 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4188 return true;
4189 ByteValues[DestNo] = I->getOperand(0);
4190 return false;
4191 }
4192
4193 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4194 // don't have this.
4195 Value *Shift = 0, *ShiftLHS = 0;
4196 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4197 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4198 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4199 return true;
4200 Instruction *SI = cast<Instruction>(Shift);
4201
4202 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4203 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4204 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4205 return true;
4206
4207 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4208 unsigned DestByte;
4209 if (AndAmt->getValue().getActiveBits() > 64)
4210 return true;
4211 uint64_t AndAmtVal = AndAmt->getZExtValue();
4212 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4213 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4214 break;
4215 // Unknown mask for bswap.
4216 if (DestByte == ByteValues.size()) return true;
4217
4218 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4219 unsigned SrcByte;
4220 if (SI->getOpcode() == Instruction::Shl)
4221 SrcByte = DestByte - ShiftBytes;
4222 else
4223 SrcByte = DestByte + ShiftBytes;
4224
4225 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4226 if (SrcByte != ByteValues.size()-DestByte-1)
4227 return true;
4228
4229 // If the destination byte value is already defined, the values are or'd
4230 // together, which isn't a bswap (unless it's an or of the same bits).
4231 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4232 return true;
4233 ByteValues[DestByte] = SI->getOperand(0);
4234 return false;
4235}
4236
4237/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4238/// If so, insert the new bswap intrinsic and return it.
4239Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4240 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4241 if (!ITy || ITy->getBitWidth() % 16)
4242 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4243
4244 /// ByteValues - For each byte of the result, we keep track of which value
4245 /// defines each byte.
4246 SmallVector<Value*, 8> ByteValues;
4247 ByteValues.resize(ITy->getBitWidth()/8);
4248
4249 // Try to find all the pieces corresponding to the bswap.
4250 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4251 CollectBSwapParts(I.getOperand(1), ByteValues))
4252 return 0;
4253
4254 // Check to see if all of the bytes come from the same value.
4255 Value *V = ByteValues[0];
4256 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4257
4258 // Check to make sure that all of the bytes come from the same value.
4259 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4260 if (ByteValues[i] != V)
4261 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004262 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004263 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004264 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004265 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004266}
4267
4268
4269Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4270 bool Changed = SimplifyCommutative(I);
4271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4272
4273 if (isa<UndefValue>(Op1)) // X | undef -> -1
4274 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4275
4276 // or X, X = X
4277 if (Op0 == Op1)
4278 return ReplaceInstUsesWith(I, Op0);
4279
4280 // See if we can simplify any instructions used by the instruction whose sole
4281 // purpose is to compute bits we don't care about.
4282 if (!isa<VectorType>(I.getType())) {
4283 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4284 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4285 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4286 KnownZero, KnownOne))
4287 return &I;
4288 } else if (isa<ConstantAggregateZero>(Op1)) {
4289 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4290 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4291 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4292 return ReplaceInstUsesWith(I, I.getOperand(1));
4293 }
4294
4295
4296
4297 // or X, -1 == -1
4298 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4299 ConstantInt *C1 = 0; Value *X = 0;
4300 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4301 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004302 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004303 InsertNewInstBefore(Or, I);
4304 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004305 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004306 ConstantInt::get(RHS->getValue() | C1->getValue()));
4307 }
4308
4309 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4310 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004311 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312 InsertNewInstBefore(Or, I);
4313 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004314 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4316 }
4317
4318 // Try to fold constant and into select arguments.
4319 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4320 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4321 return R;
4322 if (isa<PHINode>(Op0))
4323 if (Instruction *NV = FoldOpIntoPhi(I))
4324 return NV;
4325 }
4326
4327 Value *A = 0, *B = 0;
4328 ConstantInt *C1 = 0, *C2 = 0;
4329
4330 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4331 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4332 return ReplaceInstUsesWith(I, Op1);
4333 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4334 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4335 return ReplaceInstUsesWith(I, Op0);
4336
4337 // (A | B) | C and A | (B | C) -> bswap if possible.
4338 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4339 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4340 match(Op1, m_Or(m_Value(), m_Value())) ||
4341 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4342 match(Op1, m_Shift(m_Value(), m_Value())))) {
4343 if (Instruction *BSwap = MatchBSwap(I))
4344 return BSwap;
4345 }
4346
4347 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4348 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4349 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004350 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004351 InsertNewInstBefore(NOr, I);
4352 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004353 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004354 }
4355
4356 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4357 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4358 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004359 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004360 InsertNewInstBefore(NOr, I);
4361 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004362 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363 }
4364
4365 // (A & C)|(B & D)
4366 Value *C = 0, *D = 0;
4367 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4368 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4369 Value *V1 = 0, *V2 = 0, *V3 = 0;
4370 C1 = dyn_cast<ConstantInt>(C);
4371 C2 = dyn_cast<ConstantInt>(D);
4372 if (C1 && C2) { // (A & C1)|(B & C2)
4373 // If we have: ((V + N) & C1) | (V & C2)
4374 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4375 // replace with V+N.
4376 if (C1->getValue() == ~C2->getValue()) {
4377 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4378 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4379 // Add commutes, try both ways.
4380 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4381 return ReplaceInstUsesWith(I, A);
4382 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4383 return ReplaceInstUsesWith(I, A);
4384 }
4385 // Or commutes, try both ways.
4386 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4387 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4388 // Add commutes, try both ways.
4389 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4390 return ReplaceInstUsesWith(I, B);
4391 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4392 return ReplaceInstUsesWith(I, B);
4393 }
4394 }
4395 V1 = 0; V2 = 0; V3 = 0;
4396 }
4397
4398 // Check to see if we have any common things being and'ed. If so, find the
4399 // terms for V1 & (V2|V3).
4400 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4401 if (A == B) // (A & C)|(A & D) == A & (C|D)
4402 V1 = A, V2 = C, V3 = D;
4403 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4404 V1 = A, V2 = B, V3 = C;
4405 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4406 V1 = C, V2 = A, V3 = D;
4407 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4408 V1 = C, V2 = A, V3 = B;
4409
4410 if (V1) {
4411 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004412 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4413 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004415 }
4416 }
4417
4418 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4419 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4420 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4421 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4422 SI0->getOperand(1) == SI1->getOperand(1) &&
4423 (SI0->hasOneUse() || SI1->hasOneUse())) {
4424 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004425 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 SI1->getOperand(0),
4427 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004428 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004429 SI1->getOperand(1));
4430 }
4431 }
4432
4433 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4434 if (A == Op1) // ~A | A == -1
4435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4436 } else {
4437 A = 0;
4438 }
4439 // Note, A is still live here!
4440 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4441 if (Op0 == B)
4442 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4443
4444 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4445 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004446 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004448 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004449 }
4450 }
4451
4452 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4453 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4454 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4455 return R;
4456
4457 Value *LHSVal, *RHSVal;
4458 ConstantInt *LHSCst, *RHSCst;
4459 ICmpInst::Predicate LHSCC, RHSCC;
4460 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4461 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4462 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4463 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4464 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4465 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4466 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4467 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4468 // We can't fold (ugt x, C) | (sgt x, C2).
4469 PredicatesFoldable(LHSCC, RHSCC)) {
4470 // Ensure that the larger constant is on the RHS.
4471 ICmpInst *LHS = cast<ICmpInst>(Op0);
4472 bool NeedsSwap;
4473 if (ICmpInst::isSignedPredicate(LHSCC))
4474 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4475 else
4476 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4477
4478 if (NeedsSwap) {
4479 std::swap(LHS, RHS);
4480 std::swap(LHSCst, RHSCst);
4481 std::swap(LHSCC, RHSCC);
4482 }
4483
4484 // At this point, we know we have have two icmp instructions
4485 // comparing a value against two constants and or'ing the result
4486 // together. Because of the above check, we know that we only have
4487 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4488 // FoldICmpLogical check above), that the two constants are not
4489 // equal.
4490 assert(LHSCst != RHSCst && "Compares not folded above?");
4491
4492 switch (LHSCC) {
4493 default: assert(0 && "Unknown integer condition code!");
4494 case ICmpInst::ICMP_EQ:
4495 switch (RHSCC) {
4496 default: assert(0 && "Unknown integer condition code!");
4497 case ICmpInst::ICMP_EQ:
4498 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4499 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004500 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004501 LHSVal->getName()+".off");
4502 InsertNewInstBefore(Add, I);
4503 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4504 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4505 }
4506 break; // (X == 13 | X == 15) -> no change
4507 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4508 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4509 break;
4510 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4511 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4512 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4513 return ReplaceInstUsesWith(I, RHS);
4514 }
4515 break;
4516 case ICmpInst::ICMP_NE:
4517 switch (RHSCC) {
4518 default: assert(0 && "Unknown integer condition code!");
4519 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4520 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4521 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4522 return ReplaceInstUsesWith(I, LHS);
4523 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4524 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4525 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4526 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4527 }
4528 break;
4529 case ICmpInst::ICMP_ULT:
4530 switch (RHSCC) {
4531 default: assert(0 && "Unknown integer condition code!");
4532 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4533 break;
4534 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004535 // If RHSCst is [us]MAXINT, it is always false. Not handling
4536 // this can cause overflow.
4537 if (RHSCst->isMaxValue(false))
4538 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004539 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4540 false, I);
4541 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4542 break;
4543 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4544 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4545 return ReplaceInstUsesWith(I, RHS);
4546 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4547 break;
4548 }
4549 break;
4550 case ICmpInst::ICMP_SLT:
4551 switch (RHSCC) {
4552 default: assert(0 && "Unknown integer condition code!");
4553 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4554 break;
4555 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004556 // If RHSCst is [us]MAXINT, it is always false. Not handling
4557 // this can cause overflow.
4558 if (RHSCst->isMaxValue(true))
4559 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004560 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4561 false, I);
4562 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4563 break;
4564 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4565 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4566 return ReplaceInstUsesWith(I, RHS);
4567 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4568 break;
4569 }
4570 break;
4571 case ICmpInst::ICMP_UGT:
4572 switch (RHSCC) {
4573 default: assert(0 && "Unknown integer condition code!");
4574 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4575 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4576 return ReplaceInstUsesWith(I, LHS);
4577 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4578 break;
4579 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4580 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4581 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4582 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4583 break;
4584 }
4585 break;
4586 case ICmpInst::ICMP_SGT:
4587 switch (RHSCC) {
4588 default: assert(0 && "Unknown integer condition code!");
4589 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4590 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4591 return ReplaceInstUsesWith(I, LHS);
4592 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4595 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4597 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4598 break;
4599 }
4600 break;
4601 }
4602 }
4603 }
4604
4605 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004606 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004607 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4608 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004609 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4610 !isa<ICmpInst>(Op1C->getOperand(0))) {
4611 const Type *SrcTy = Op0C->getOperand(0)->getType();
4612 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4613 // Only do this if the casts both really cause code to be
4614 // generated.
4615 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4616 I.getType(), TD) &&
4617 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4618 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004619 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004620 Op1C->getOperand(0),
4621 I.getName());
4622 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004623 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004624 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004625 }
4626 }
Chris Lattner91882432007-10-24 05:38:08 +00004627 }
4628
4629
4630 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4631 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4632 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4633 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004634 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4635 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004636 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4637 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4638 // If either of the constants are nans, then the whole thing returns
4639 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004640 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004641 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4642
4643 // Otherwise, no need to compare the two constants, compare the
4644 // rest.
4645 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4646 RHS->getOperand(0));
4647 }
4648 }
4649 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004650
4651 return Changed ? &I : 0;
4652}
4653
Dan Gohman089efff2008-05-13 00:00:25 +00004654namespace {
4655
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004656// XorSelf - Implements: X ^ X --> 0
4657struct XorSelf {
4658 Value *RHS;
4659 XorSelf(Value *rhs) : RHS(rhs) {}
4660 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4661 Instruction *apply(BinaryOperator &Xor) const {
4662 return &Xor;
4663 }
4664};
4665
Dan Gohman089efff2008-05-13 00:00:25 +00004666}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004667
4668Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4669 bool Changed = SimplifyCommutative(I);
4670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4671
Evan Chenge5cd8032008-03-25 20:07:13 +00004672 if (isa<UndefValue>(Op1)) {
4673 if (isa<UndefValue>(Op0))
4674 // Handle undef ^ undef -> 0 special case. This is a common
4675 // idiom (misuse).
4676 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004677 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004678 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004679
4680 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4681 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004682 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4684 }
4685
4686 // See if we can simplify any instructions used by the instruction whose sole
4687 // purpose is to compute bits we don't care about.
4688 if (!isa<VectorType>(I.getType())) {
4689 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4690 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4691 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4692 KnownZero, KnownOne))
4693 return &I;
4694 } else if (isa<ConstantAggregateZero>(Op1)) {
4695 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4696 }
4697
4698 // Is this a ~ operation?
4699 if (Value *NotOp = dyn_castNotVal(&I)) {
4700 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4701 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4703 if (Op0I->getOpcode() == Instruction::And ||
4704 Op0I->getOpcode() == Instruction::Or) {
4705 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4706 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4707 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004708 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 Op0I->getOperand(1)->getName()+".not");
4710 InsertNewInstBefore(NotY, I);
4711 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004712 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004714 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004715 }
4716 }
4717 }
4718 }
4719
4720
4721 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004722 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4723 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4724 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004725 return new ICmpInst(ICI->getInversePredicate(),
4726 ICI->getOperand(0), ICI->getOperand(1));
4727
Nick Lewycky1405e922007-08-06 20:04:16 +00004728 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4729 return new FCmpInst(FCI->getInversePredicate(),
4730 FCI->getOperand(0), FCI->getOperand(1));
4731 }
4732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004733 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4734 // ~(c-X) == X-c-1 == X+(-c-1)
4735 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4736 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4737 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4738 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4739 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004740 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741 }
4742
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004743 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744 if (Op0I->getOpcode() == Instruction::Add) {
4745 // ~(X-c) --> (-c-1)-X
4746 if (RHS->isAllOnesValue()) {
4747 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004748 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004749 ConstantExpr::getSub(NegOp0CI,
4750 ConstantInt::get(I.getType(), 1)),
4751 Op0I->getOperand(0));
4752 } else if (RHS->getValue().isSignBit()) {
4753 // (X + C) ^ signbit -> (X + C + signbit)
4754 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004756
4757 }
4758 } else if (Op0I->getOpcode() == Instruction::Or) {
4759 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4760 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4761 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4762 // Anything in both C1 and C2 is known to be zero, remove it from
4763 // NewRHS.
4764 Constant *CommonBits = And(Op0CI, RHS);
4765 NewRHS = ConstantExpr::getAnd(NewRHS,
4766 ConstantExpr::getNot(CommonBits));
4767 AddToWorkList(Op0I);
4768 I.setOperand(0, Op0I->getOperand(0));
4769 I.setOperand(1, NewRHS);
4770 return &I;
4771 }
4772 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004774 }
4775
4776 // Try to fold constant and into select arguments.
4777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4778 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4779 return R;
4780 if (isa<PHINode>(Op0))
4781 if (Instruction *NV = FoldOpIntoPhi(I))
4782 return NV;
4783 }
4784
4785 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4786 if (X == Op1)
4787 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4788
4789 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4790 if (X == Op0)
4791 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4792
4793
4794 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4795 if (Op1I) {
4796 Value *A, *B;
4797 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4798 if (A == Op0) { // B^(B|A) == (A|B)^B
4799 Op1I->swapOperands();
4800 I.swapOperands();
4801 std::swap(Op0, Op1);
4802 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4803 I.swapOperands(); // Simplified below.
4804 std::swap(Op0, Op1);
4805 }
4806 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4807 if (Op0 == A) // A^(A^B) == B
4808 return ReplaceInstUsesWith(I, B);
4809 else if (Op0 == B) // A^(B^A) == B
4810 return ReplaceInstUsesWith(I, A);
4811 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4812 if (A == Op0) { // A^(A&B) -> A^(B&A)
4813 Op1I->swapOperands();
4814 std::swap(A, B);
4815 }
4816 if (B == Op0) { // A^(B&A) -> (B&A)^A
4817 I.swapOperands(); // Simplified below.
4818 std::swap(Op0, Op1);
4819 }
4820 }
4821 }
4822
4823 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4824 if (Op0I) {
4825 Value *A, *B;
4826 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4827 if (A == Op1) // (B|A)^B == (A|B)^B
4828 std::swap(A, B);
4829 if (B == Op1) { // (A|B)^B == A & ~B
4830 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004831 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4832 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004833 }
4834 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4835 if (Op1 == A) // (A^B)^A == B
4836 return ReplaceInstUsesWith(I, B);
4837 else if (Op1 == B) // (B^A)^A == B
4838 return ReplaceInstUsesWith(I, A);
4839 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4840 if (A == Op1) // (A&B)^A -> (B&A)^A
4841 std::swap(A, B);
4842 if (B == Op1 && // (B&A)^A == ~B & A
4843 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4844 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004845 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4846 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004847 }
4848 }
4849 }
4850
4851 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4852 if (Op0I && Op1I && Op0I->isShift() &&
4853 Op0I->getOpcode() == Op1I->getOpcode() &&
4854 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4855 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4856 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004857 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004858 Op1I->getOperand(0),
4859 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004860 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004861 Op1I->getOperand(1));
4862 }
4863
4864 if (Op0I && Op1I) {
4865 Value *A, *B, *C, *D;
4866 // (A & B)^(A | B) -> A ^ B
4867 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4868 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4869 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004870 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004871 }
4872 // (A | B)^(A & B) -> A ^ B
4873 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4874 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4875 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004876 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 }
4878
4879 // (A & B)^(C & D)
4880 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4881 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4882 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4883 // (X & Y)^(X & Y) -> (Y^Z) & X
4884 Value *X = 0, *Y = 0, *Z = 0;
4885 if (A == C)
4886 X = A, Y = B, Z = D;
4887 else if (A == D)
4888 X = A, Y = B, Z = C;
4889 else if (B == C)
4890 X = B, Y = A, Z = D;
4891 else if (B == D)
4892 X = B, Y = A, Z = C;
4893
4894 if (X) {
4895 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004896 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4897 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004898 }
4899 }
4900 }
4901
4902 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4903 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4904 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4905 return R;
4906
4907 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004908 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004909 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4910 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4911 const Type *SrcTy = Op0C->getOperand(0)->getType();
4912 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4913 // Only do this if the casts both really cause code to be generated.
4914 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4915 I.getType(), TD) &&
4916 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4917 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004918 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004919 Op1C->getOperand(0),
4920 I.getName());
4921 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004922 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004923 }
4924 }
Chris Lattner91882432007-10-24 05:38:08 +00004925 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926 return Changed ? &I : 0;
4927}
4928
4929/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4930/// overflowed for this type.
4931static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4932 ConstantInt *In2, bool IsSigned = false) {
4933 Result = cast<ConstantInt>(Add(In1, In2));
4934
4935 if (IsSigned)
4936 if (In2->getValue().isNegative())
4937 return Result->getValue().sgt(In1->getValue());
4938 else
4939 return Result->getValue().slt(In1->getValue());
4940 else
4941 return Result->getValue().ult(In1->getValue());
4942}
4943
4944/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4945/// code necessary to compute the offset from the base pointer (without adding
4946/// in the base pointer). Return the result as a signed integer of intptr size.
4947static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4948 TargetData &TD = IC.getTargetData();
4949 gep_type_iterator GTI = gep_type_begin(GEP);
4950 const Type *IntPtrTy = TD.getIntPtrType();
4951 Value *Result = Constant::getNullValue(IntPtrTy);
4952
4953 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004954 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004955 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4956
4957 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4958 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004959 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004960 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4961 if (OpC->isZero()) continue;
4962
4963 // Handle a struct index, which adds its field offset to the pointer.
4964 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4965 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4966
4967 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4968 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4969 else
4970 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004971 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004972 ConstantInt::get(IntPtrTy, Size),
4973 GEP->getName()+".offs"), I);
4974 continue;
4975 }
4976
4977 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4978 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4979 Scale = ConstantExpr::getMul(OC, Scale);
4980 if (Constant *RC = dyn_cast<Constant>(Result))
4981 Result = ConstantExpr::getAdd(RC, Scale);
4982 else {
4983 // Emit an add instruction.
4984 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004985 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004986 GEP->getName()+".offs"), I);
4987 }
4988 continue;
4989 }
4990 // Convert to correct type.
4991 if (Op->getType() != IntPtrTy) {
4992 if (Constant *OpC = dyn_cast<Constant>(Op))
4993 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4994 else
4995 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4996 Op->getName()+".c"), I);
4997 }
4998 if (Size != 1) {
4999 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5000 if (Constant *OpC = dyn_cast<Constant>(Op))
5001 Op = ConstantExpr::getMul(OpC, Scale);
5002 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005003 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005004 GEP->getName()+".idx"), I);
5005 }
5006
5007 // Emit an add instruction.
5008 if (isa<Constant>(Op) && isa<Constant>(Result))
5009 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5010 cast<Constant>(Result));
5011 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005012 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005013 GEP->getName()+".offs"), I);
5014 }
5015 return Result;
5016}
5017
Chris Lattnereba75862008-04-22 02:53:33 +00005018
5019/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5020/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5021/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5022/// complex, and scales are involved. The above expression would also be legal
5023/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5024/// later form is less amenable to optimization though, and we are allowed to
5025/// generate the first by knowing that pointer arithmetic doesn't overflow.
5026///
5027/// If we can't emit an optimized form for this expression, this returns null.
5028///
5029static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5030 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005031 TargetData &TD = IC.getTargetData();
5032 gep_type_iterator GTI = gep_type_begin(GEP);
5033
5034 // Check to see if this gep only has a single variable index. If so, and if
5035 // any constant indices are a multiple of its scale, then we can compute this
5036 // in terms of the scale of the variable index. For example, if the GEP
5037 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5038 // because the expression will cross zero at the same point.
5039 unsigned i, e = GEP->getNumOperands();
5040 int64_t Offset = 0;
5041 for (i = 1; i != e; ++i, ++GTI) {
5042 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5043 // Compute the aggregate offset of constant indices.
5044 if (CI->isZero()) continue;
5045
5046 // Handle a struct index, which adds its field offset to the pointer.
5047 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5048 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5049 } else {
5050 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5051 Offset += Size*CI->getSExtValue();
5052 }
5053 } else {
5054 // Found our variable index.
5055 break;
5056 }
5057 }
5058
5059 // If there are no variable indices, we must have a constant offset, just
5060 // evaluate it the general way.
5061 if (i == e) return 0;
5062
5063 Value *VariableIdx = GEP->getOperand(i);
5064 // Determine the scale factor of the variable element. For example, this is
5065 // 4 if the variable index is into an array of i32.
5066 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5067
5068 // Verify that there are no other variable indices. If so, emit the hard way.
5069 for (++i, ++GTI; i != e; ++i, ++GTI) {
5070 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5071 if (!CI) return 0;
5072
5073 // Compute the aggregate offset of constant indices.
5074 if (CI->isZero()) continue;
5075
5076 // Handle a struct index, which adds its field offset to the pointer.
5077 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5078 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5079 } else {
5080 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5081 Offset += Size*CI->getSExtValue();
5082 }
5083 }
5084
5085 // Okay, we know we have a single variable index, which must be a
5086 // pointer/array/vector index. If there is no offset, life is simple, return
5087 // the index.
5088 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5089 if (Offset == 0) {
5090 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5091 // we don't need to bother extending: the extension won't affect where the
5092 // computation crosses zero.
5093 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5094 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5095 VariableIdx->getNameStart(), &I);
5096 return VariableIdx;
5097 }
5098
5099 // Otherwise, there is an index. The computation we will do will be modulo
5100 // the pointer size, so get it.
5101 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5102
5103 Offset &= PtrSizeMask;
5104 VariableScale &= PtrSizeMask;
5105
5106 // To do this transformation, any constant index must be a multiple of the
5107 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5108 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5109 // multiple of the variable scale.
5110 int64_t NewOffs = Offset / (int64_t)VariableScale;
5111 if (Offset != NewOffs*(int64_t)VariableScale)
5112 return 0;
5113
5114 // Okay, we can do this evaluation. Start by converting the index to intptr.
5115 const Type *IntPtrTy = TD.getIntPtrType();
5116 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005117 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005118 true /*SExt*/,
5119 VariableIdx->getNameStart(), &I);
5120 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005122}
5123
5124
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5126/// else. At this point we know that the GEP is on the LHS of the comparison.
5127Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5128 ICmpInst::Predicate Cond,
5129 Instruction &I) {
5130 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5131
Chris Lattnereba75862008-04-22 02:53:33 +00005132 // Look through bitcasts.
5133 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5134 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005135
5136 Value *PtrBase = GEPLHS->getOperand(0);
5137 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005138 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005139 // This transformation (ignoring the base and scales) is valid because we
5140 // know pointers can't overflow. See if we can output an optimized form.
5141 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5142
5143 // If not, synthesize the offset the hard way.
5144 if (Offset == 0)
5145 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005146 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5147 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005148 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5149 // If the base pointers are different, but the indices are the same, just
5150 // compare the base pointer.
5151 if (PtrBase != GEPRHS->getOperand(0)) {
5152 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5153 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5154 GEPRHS->getOperand(0)->getType();
5155 if (IndicesTheSame)
5156 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5157 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5158 IndicesTheSame = false;
5159 break;
5160 }
5161
5162 // If all indices are the same, just compare the base pointers.
5163 if (IndicesTheSame)
5164 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5165 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5166
5167 // Otherwise, the base pointers are different and the indices are
5168 // different, bail out.
5169 return 0;
5170 }
5171
5172 // If one of the GEPs has all zero indices, recurse.
5173 bool AllZeros = true;
5174 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5175 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5176 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5177 AllZeros = false;
5178 break;
5179 }
5180 if (AllZeros)
5181 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5182 ICmpInst::getSwappedPredicate(Cond), I);
5183
5184 // If the other GEP has all zero indices, recurse.
5185 AllZeros = true;
5186 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5187 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5188 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5189 AllZeros = false;
5190 break;
5191 }
5192 if (AllZeros)
5193 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5194
5195 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5196 // If the GEPs only differ by one index, compare it.
5197 unsigned NumDifferences = 0; // Keep track of # differences.
5198 unsigned DiffOperand = 0; // The operand that differs.
5199 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5200 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5201 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5202 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5203 // Irreconcilable differences.
5204 NumDifferences = 2;
5205 break;
5206 } else {
5207 if (NumDifferences++) break;
5208 DiffOperand = i;
5209 }
5210 }
5211
5212 if (NumDifferences == 0) // SAME GEP?
5213 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005214 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005215 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005216
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217 else if (NumDifferences == 1) {
5218 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5219 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5220 // Make sure we do a signed comparison here.
5221 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5222 }
5223 }
5224
5225 // Only lower this if the icmp is the only user of the GEP or if we expect
5226 // the result to fold to a constant!
5227 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5228 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5229 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5230 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5231 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5232 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5233 }
5234 }
5235 return 0;
5236}
5237
Chris Lattnere6b62d92008-05-19 20:18:56 +00005238/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5239///
5240Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5241 Instruction *LHSI,
5242 Constant *RHSC) {
5243 if (!isa<ConstantFP>(RHSC)) return 0;
5244 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5245
5246 // Get the width of the mantissa. We don't want to hack on conversions that
5247 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005248 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005249 if (MantissaWidth == -1) return 0; // Unknown.
5250
5251 // Check to see that the input is converted from an integer type that is small
5252 // enough that preserves all bits. TODO: check here for "known" sign bits.
5253 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5254 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5255
5256 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5257 if (isa<UIToFPInst>(LHSI))
5258 ++InputSize;
5259
5260 // If the conversion would lose info, don't hack on this.
5261 if ((int)InputSize > MantissaWidth)
5262 return 0;
5263
5264 // Otherwise, we can potentially simplify the comparison. We know that it
5265 // will always come through as an integer value and we know the constant is
5266 // not a NAN (it would have been previously simplified).
5267 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5268
5269 ICmpInst::Predicate Pred;
5270 switch (I.getPredicate()) {
5271 default: assert(0 && "Unexpected predicate!");
5272 case FCmpInst::FCMP_UEQ:
5273 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5274 case FCmpInst::FCMP_UGT:
5275 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5276 case FCmpInst::FCMP_UGE:
5277 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5278 case FCmpInst::FCMP_ULT:
5279 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5280 case FCmpInst::FCMP_ULE:
5281 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5282 case FCmpInst::FCMP_UNE:
5283 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5284 case FCmpInst::FCMP_ORD:
5285 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5286 case FCmpInst::FCMP_UNO:
5287 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5288 }
5289
5290 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5291
5292 // Now we know that the APFloat is a normal number, zero or inf.
5293
5294 // See if the FP constant is top large for the integer. For example,
5295 // comparing an i8 to 300.0.
5296 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5297
5298 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5299 // and large values.
5300 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5301 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5302 APFloat::rmNearestTiesToEven);
5303 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5304 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5305 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5306 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5307 }
5308
5309 // See if the RHS value is < SignedMin.
5310 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5311 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5312 APFloat::rmNearestTiesToEven);
5313 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5314 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5315 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5316 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5317 }
5318
5319 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5320 // it may still be fractional. See if it is fractional by casting the FP
5321 // value to the integer value and back, checking for equality. Don't do this
5322 // for zero, because -0.0 is not fractional.
5323 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5324 if (!RHS.isZero() &&
5325 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5326 // If we had a comparison against a fractional value, we have to adjust
5327 // the compare predicate and sometimes the value. RHSC is rounded towards
5328 // zero at this point.
5329 switch (Pred) {
5330 default: assert(0 && "Unexpected integer comparison!");
5331 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5332 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5333 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5334 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5335 case ICmpInst::ICMP_SLE:
5336 // (float)int <= 4.4 --> int <= 4
5337 // (float)int <= -4.4 --> int < -4
5338 if (RHS.isNegative())
5339 Pred = ICmpInst::ICMP_SLT;
5340 break;
5341 case ICmpInst::ICMP_SLT:
5342 // (float)int < -4.4 --> int < -4
5343 // (float)int < 4.4 --> int <= 4
5344 if (!RHS.isNegative())
5345 Pred = ICmpInst::ICMP_SLE;
5346 break;
5347 case ICmpInst::ICMP_SGT:
5348 // (float)int > 4.4 --> int > 4
5349 // (float)int > -4.4 --> int >= -4
5350 if (RHS.isNegative())
5351 Pred = ICmpInst::ICMP_SGE;
5352 break;
5353 case ICmpInst::ICMP_SGE:
5354 // (float)int >= -4.4 --> int >= -4
5355 // (float)int >= 4.4 --> int > 4
5356 if (!RHS.isNegative())
5357 Pred = ICmpInst::ICMP_SGT;
5358 break;
5359 }
5360 }
5361
5362 // Lower this FP comparison into an appropriate integer version of the
5363 // comparison.
5364 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5365}
5366
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005367Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5368 bool Changed = SimplifyCompare(I);
5369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5370
5371 // Fold trivial predicates.
5372 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5373 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5374 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5375 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5376
5377 // Simplify 'fcmp pred X, X'
5378 if (Op0 == Op1) {
5379 switch (I.getPredicate()) {
5380 default: assert(0 && "Unknown predicate!");
5381 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5382 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5383 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5384 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5385 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5386 case FCmpInst::FCMP_OLT: // True if ordered and less than
5387 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5388 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5389
5390 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5391 case FCmpInst::FCMP_ULT: // True if unordered or less than
5392 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5393 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5394 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5395 I.setPredicate(FCmpInst::FCMP_UNO);
5396 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5397 return &I;
5398
5399 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5400 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5401 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5402 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5403 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5404 I.setPredicate(FCmpInst::FCMP_ORD);
5405 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5406 return &I;
5407 }
5408 }
5409
5410 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5411 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5412
5413 // Handle fcmp with constant RHS
5414 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005415 // If the constant is a nan, see if we can fold the comparison based on it.
5416 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5417 if (CFP->getValueAPF().isNaN()) {
5418 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5419 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5420 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5421 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5422 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5423 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5424 }
5425 }
5426
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005427 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5428 switch (LHSI->getOpcode()) {
5429 case Instruction::PHI:
5430 if (Instruction *NV = FoldOpIntoPhi(I))
5431 return NV;
5432 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005433 case Instruction::SIToFP:
5434 case Instruction::UIToFP:
5435 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5436 return NV;
5437 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005438 case Instruction::Select:
5439 // If either operand of the select is a constant, we can fold the
5440 // comparison into the select arms, which will cause one to be
5441 // constant folded and the select turned into a bitwise or.
5442 Value *Op1 = 0, *Op2 = 0;
5443 if (LHSI->hasOneUse()) {
5444 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5445 // Fold the known value into the constant operand.
5446 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5447 // Insert a new FCmp of the other select operand.
5448 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5449 LHSI->getOperand(2), RHSC,
5450 I.getName()), I);
5451 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5452 // Fold the known value into the constant operand.
5453 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5454 // Insert a new FCmp of the other select operand.
5455 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5456 LHSI->getOperand(1), RHSC,
5457 I.getName()), I);
5458 }
5459 }
5460
5461 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005462 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005463 break;
5464 }
5465 }
5466
5467 return Changed ? &I : 0;
5468}
5469
5470Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5471 bool Changed = SimplifyCompare(I);
5472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5473 const Type *Ty = Op0->getType();
5474
5475 // icmp X, X
5476 if (Op0 == Op1)
5477 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005478 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005479
5480 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5481 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005482
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005483 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5484 // addresses never equal each other! We already know that Op0 != Op1.
5485 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5486 isa<ConstantPointerNull>(Op0)) &&
5487 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5488 isa<ConstantPointerNull>(Op1)))
5489 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005490 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005491
5492 // icmp's with boolean values can always be turned into bitwise operations
5493 if (Ty == Type::Int1Ty) {
5494 switch (I.getPredicate()) {
5495 default: assert(0 && "Invalid icmp instruction!");
5496 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005497 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005498 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005499 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005500 }
5501 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005502 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005503
5504 case ICmpInst::ICMP_UGT:
5505 case ICmpInst::ICMP_SGT:
5506 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5507 // FALL THROUGH
5508 case ICmpInst::ICMP_ULT:
5509 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005510 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005512 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005513 }
5514 case ICmpInst::ICMP_UGE:
5515 case ICmpInst::ICMP_SGE:
5516 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5517 // FALL THROUGH
5518 case ICmpInst::ICMP_ULE:
5519 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005520 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005521 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005522 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005523 }
5524 }
5525 }
5526
5527 // See if we are doing a comparison between a constant and an instruction that
5528 // can be folded into the comparison.
5529 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005530 Value *A, *B;
5531
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005532 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5533 if (I.isEquality() && CI->isNullValue() &&
5534 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5535 // (icmp cond A B) if cond is equality
5536 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005537 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005538
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005539 switch (I.getPredicate()) {
5540 default: break;
5541 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5542 if (CI->isMinValue(false))
5543 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5544 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5545 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5546 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5547 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5548 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5549 if (CI->isMinValue(true))
5550 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5551 ConstantInt::getAllOnesValue(Op0->getType()));
5552
5553 break;
5554
5555 case ICmpInst::ICMP_SLT:
5556 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5557 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5558 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5559 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5560 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5561 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5562 break;
5563
5564 case ICmpInst::ICMP_UGT:
5565 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5566 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5567 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5568 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5569 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5570 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5571
5572 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5573 if (CI->isMaxValue(true))
5574 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5575 ConstantInt::getNullValue(Op0->getType()));
5576 break;
5577
5578 case ICmpInst::ICMP_SGT:
5579 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5580 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5581 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5582 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5583 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5584 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5585 break;
5586
5587 case ICmpInst::ICMP_ULE:
5588 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5589 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5590 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5591 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5592 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5593 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5594 break;
5595
5596 case ICmpInst::ICMP_SLE:
5597 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5598 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5599 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5600 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5601 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5602 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5603 break;
5604
5605 case ICmpInst::ICMP_UGE:
5606 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5607 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5608 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5609 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5610 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5611 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5612 break;
5613
5614 case ICmpInst::ICMP_SGE:
5615 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5616 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5617 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5618 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5619 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5620 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5621 break;
5622 }
5623
5624 // If we still have a icmp le or icmp ge instruction, turn it into the
5625 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5626 // already been handled above, this requires little checking.
5627 //
5628 switch (I.getPredicate()) {
5629 default: break;
5630 case ICmpInst::ICMP_ULE:
5631 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5632 case ICmpInst::ICMP_SLE:
5633 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5634 case ICmpInst::ICMP_UGE:
5635 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5636 case ICmpInst::ICMP_SGE:
5637 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5638 }
5639
5640 // See if we can fold the comparison based on bits known to be zero or one
5641 // in the input. If this comparison is a normal comparison, it demands all
5642 // bits, if it is a sign bit comparison, it only demands the sign bit.
5643
5644 bool UnusedBit;
5645 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5646
5647 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5648 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5649 if (SimplifyDemandedBits(Op0,
5650 isSignBit ? APInt::getSignBit(BitWidth)
5651 : APInt::getAllOnesValue(BitWidth),
5652 KnownZero, KnownOne, 0))
5653 return &I;
5654
5655 // Given the known and unknown bits, compute a range that the LHS could be
5656 // in.
5657 if ((KnownOne | KnownZero) != 0) {
5658 // Compute the Min, Max and RHS values based on the known bits. For the
5659 // EQ and NE we use unsigned values.
5660 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5661 const APInt& RHSVal = CI->getValue();
5662 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5663 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5664 Max);
5665 } else {
5666 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5667 Max);
5668 }
5669 switch (I.getPredicate()) { // LE/GE have been folded already.
5670 default: assert(0 && "Unknown icmp opcode!");
5671 case ICmpInst::ICMP_EQ:
5672 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5673 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5674 break;
5675 case ICmpInst::ICMP_NE:
5676 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5677 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5678 break;
5679 case ICmpInst::ICMP_ULT:
5680 if (Max.ult(RHSVal))
5681 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5682 if (Min.uge(RHSVal))
5683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5684 break;
5685 case ICmpInst::ICMP_UGT:
5686 if (Min.ugt(RHSVal))
5687 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5688 if (Max.ule(RHSVal))
5689 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5690 break;
5691 case ICmpInst::ICMP_SLT:
5692 if (Max.slt(RHSVal))
5693 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5694 if (Min.sgt(RHSVal))
5695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5696 break;
5697 case ICmpInst::ICMP_SGT:
5698 if (Min.sgt(RHSVal))
5699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5700 if (Max.sle(RHSVal))
5701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5702 break;
5703 }
5704 }
5705
5706 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5707 // instruction, see if that instruction also has constants so that the
5708 // instruction can be folded into the icmp
5709 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5710 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5711 return Res;
5712 }
5713
5714 // Handle icmp with constant (but not simple integer constant) RHS
5715 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5717 switch (LHSI->getOpcode()) {
5718 case Instruction::GetElementPtr:
5719 if (RHSC->isNullValue()) {
5720 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5721 bool isAllZeros = true;
5722 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5723 if (!isa<Constant>(LHSI->getOperand(i)) ||
5724 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5725 isAllZeros = false;
5726 break;
5727 }
5728 if (isAllZeros)
5729 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5730 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5731 }
5732 break;
5733
5734 case Instruction::PHI:
5735 if (Instruction *NV = FoldOpIntoPhi(I))
5736 return NV;
5737 break;
5738 case Instruction::Select: {
5739 // If either operand of the select is a constant, we can fold the
5740 // comparison into the select arms, which will cause one to be
5741 // constant folded and the select turned into a bitwise or.
5742 Value *Op1 = 0, *Op2 = 0;
5743 if (LHSI->hasOneUse()) {
5744 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5745 // Fold the known value into the constant operand.
5746 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5747 // Insert a new ICmp of the other select operand.
5748 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5749 LHSI->getOperand(2), RHSC,
5750 I.getName()), I);
5751 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5752 // Fold the known value into the constant operand.
5753 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5754 // Insert a new ICmp of the other select operand.
5755 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5756 LHSI->getOperand(1), RHSC,
5757 I.getName()), I);
5758 }
5759 }
5760
5761 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005762 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005763 break;
5764 }
5765 case Instruction::Malloc:
5766 // If we have (malloc != null), and if the malloc has a single use, we
5767 // can assume it is successful and remove the malloc.
5768 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5769 AddToWorkList(LHSI);
5770 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005771 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005772 }
5773 break;
5774 }
5775 }
5776
5777 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5778 if (User *GEP = dyn_castGetElementPtr(Op0))
5779 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5780 return NI;
5781 if (User *GEP = dyn_castGetElementPtr(Op1))
5782 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5783 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5784 return NI;
5785
5786 // Test to see if the operands of the icmp are casted versions of other
5787 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5788 // now.
5789 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5790 if (isa<PointerType>(Op0->getType()) &&
5791 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5792 // We keep moving the cast from the left operand over to the right
5793 // operand, where it can often be eliminated completely.
5794 Op0 = CI->getOperand(0);
5795
5796 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5797 // so eliminate it as well.
5798 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5799 Op1 = CI2->getOperand(0);
5800
5801 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005802 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005803 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5804 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5805 } else {
5806 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005807 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005808 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005809 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005810 return new ICmpInst(I.getPredicate(), Op0, Op1);
5811 }
5812 }
5813
5814 if (isa<CastInst>(Op0)) {
5815 // Handle the special case of: icmp (cast bool to X), <cst>
5816 // This comes up when you have code like
5817 // int X = A < B;
5818 // if (X) ...
5819 // For generality, we handle any zero-extension of any operand comparison
5820 // with a constant or another cast from the same type.
5821 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5822 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5823 return R;
5824 }
5825
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005826 // ~x < ~y --> y < x
5827 { Value *A, *B;
5828 if (match(Op0, m_Not(m_Value(A))) &&
5829 match(Op1, m_Not(m_Value(B))))
5830 return new ICmpInst(I.getPredicate(), B, A);
5831 }
5832
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005833 if (I.isEquality()) {
5834 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005835
5836 // -x == -y --> x == y
5837 if (match(Op0, m_Neg(m_Value(A))) &&
5838 match(Op1, m_Neg(m_Value(B))))
5839 return new ICmpInst(I.getPredicate(), A, B);
5840
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005841 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5842 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5843 Value *OtherVal = A == Op1 ? B : A;
5844 return new ICmpInst(I.getPredicate(), OtherVal,
5845 Constant::getNullValue(A->getType()));
5846 }
5847
5848 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5849 // A^c1 == C^c2 --> A == C^(c1^c2)
5850 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5851 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5852 if (Op1->hasOneUse()) {
5853 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005854 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005855 return new ICmpInst(I.getPredicate(), A,
5856 InsertNewInstBefore(Xor, I));
5857 }
5858
5859 // A^B == A^D -> B == D
5860 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5861 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5862 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5863 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5864 }
5865 }
5866
5867 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5868 (A == Op0 || B == Op0)) {
5869 // A == (A^B) -> B == 0
5870 Value *OtherVal = A == Op0 ? B : A;
5871 return new ICmpInst(I.getPredicate(), OtherVal,
5872 Constant::getNullValue(A->getType()));
5873 }
5874 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5875 // (A-B) == A -> B == 0
5876 return new ICmpInst(I.getPredicate(), B,
5877 Constant::getNullValue(B->getType()));
5878 }
5879 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5880 // A == (A-B) -> B == 0
5881 return new ICmpInst(I.getPredicate(), B,
5882 Constant::getNullValue(B->getType()));
5883 }
5884
5885 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5886 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5887 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5888 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5889 Value *X = 0, *Y = 0, *Z = 0;
5890
5891 if (A == C) {
5892 X = B; Y = D; Z = A;
5893 } else if (A == D) {
5894 X = B; Y = C; Z = A;
5895 } else if (B == C) {
5896 X = A; Y = D; Z = B;
5897 } else if (B == D) {
5898 X = A; Y = C; Z = B;
5899 }
5900
5901 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005902 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5903 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005904 I.setOperand(0, Op1);
5905 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5906 return &I;
5907 }
5908 }
5909 }
5910 return Changed ? &I : 0;
5911}
5912
5913
5914/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5915/// and CmpRHS are both known to be integer constants.
5916Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5917 ConstantInt *DivRHS) {
5918 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5919 const APInt &CmpRHSV = CmpRHS->getValue();
5920
5921 // FIXME: If the operand types don't match the type of the divide
5922 // then don't attempt this transform. The code below doesn't have the
5923 // logic to deal with a signed divide and an unsigned compare (and
5924 // vice versa). This is because (x /s C1) <s C2 produces different
5925 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5926 // (x /u C1) <u C2. Simply casting the operands and result won't
5927 // work. :( The if statement below tests that condition and bails
5928 // if it finds it.
5929 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5930 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5931 return 0;
5932 if (DivRHS->isZero())
5933 return 0; // The ProdOV computation fails on divide by zero.
5934
5935 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5936 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5937 // C2 (CI). By solving for X we can turn this into a range check
5938 // instead of computing a divide.
5939 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5940
5941 // Determine if the product overflows by seeing if the product is
5942 // not equal to the divide. Make sure we do the same kind of divide
5943 // as in the LHS instruction that we're folding.
5944 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5945 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5946
5947 // Get the ICmp opcode
5948 ICmpInst::Predicate Pred = ICI.getPredicate();
5949
5950 // Figure out the interval that is being checked. For example, a comparison
5951 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5952 // Compute this interval based on the constants involved and the signedness of
5953 // the compare/divide. This computes a half-open interval, keeping track of
5954 // whether either value in the interval overflows. After analysis each
5955 // overflow variable is set to 0 if it's corresponding bound variable is valid
5956 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5957 int LoOverflow = 0, HiOverflow = 0;
5958 ConstantInt *LoBound = 0, *HiBound = 0;
5959
5960
5961 if (!DivIsSigned) { // udiv
5962 // e.g. X/5 op 3 --> [15, 20)
5963 LoBound = Prod;
5964 HiOverflow = LoOverflow = ProdOV;
5965 if (!HiOverflow)
5966 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005967 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005968 if (CmpRHSV == 0) { // (X / pos) op 0
5969 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5970 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5971 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005972 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005973 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5974 HiOverflow = LoOverflow = ProdOV;
5975 if (!HiOverflow)
5976 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5977 } else { // (X / pos) op neg
5978 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5979 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5980 LoOverflow = AddWithOverflow(LoBound, Prod,
5981 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5982 HiBound = AddOne(Prod);
5983 HiOverflow = ProdOV ? -1 : 0;
5984 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005985 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005986 if (CmpRHSV == 0) { // (X / neg) op 0
5987 // e.g. X/-5 op 0 --> [-4, 5)
5988 LoBound = AddOne(DivRHS);
5989 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5990 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5991 HiOverflow = 1; // [INTMIN+1, overflow)
5992 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5993 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005994 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005995 // e.g. X/-5 op 3 --> [-19, -14)
5996 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5997 if (!LoOverflow)
5998 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5999 HiBound = AddOne(Prod);
6000 } else { // (X / neg) op neg
6001 // e.g. X/-5 op -3 --> [15, 20)
6002 LoBound = Prod;
6003 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6004 HiBound = Subtract(Prod, DivRHS);
6005 }
6006
6007 // Dividing by a negative swaps the condition. LT <-> GT
6008 Pred = ICmpInst::getSwappedPredicate(Pred);
6009 }
6010
6011 Value *X = DivI->getOperand(0);
6012 switch (Pred) {
6013 default: assert(0 && "Unhandled icmp opcode!");
6014 case ICmpInst::ICMP_EQ:
6015 if (LoOverflow && HiOverflow)
6016 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6017 else if (HiOverflow)
6018 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6019 ICmpInst::ICMP_UGE, X, LoBound);
6020 else if (LoOverflow)
6021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6022 ICmpInst::ICMP_ULT, X, HiBound);
6023 else
6024 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6025 case ICmpInst::ICMP_NE:
6026 if (LoOverflow && HiOverflow)
6027 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6028 else if (HiOverflow)
6029 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6030 ICmpInst::ICMP_ULT, X, LoBound);
6031 else if (LoOverflow)
6032 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6033 ICmpInst::ICMP_UGE, X, HiBound);
6034 else
6035 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6036 case ICmpInst::ICMP_ULT:
6037 case ICmpInst::ICMP_SLT:
6038 if (LoOverflow == +1) // Low bound is greater than input range.
6039 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6040 if (LoOverflow == -1) // Low bound is less than input range.
6041 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6042 return new ICmpInst(Pred, X, LoBound);
6043 case ICmpInst::ICMP_UGT:
6044 case ICmpInst::ICMP_SGT:
6045 if (HiOverflow == +1) // High bound greater than input range.
6046 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6047 else if (HiOverflow == -1) // High bound less than input range.
6048 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6049 if (Pred == ICmpInst::ICMP_UGT)
6050 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6051 else
6052 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6053 }
6054}
6055
6056
6057/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6058///
6059Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6060 Instruction *LHSI,
6061 ConstantInt *RHS) {
6062 const APInt &RHSV = RHS->getValue();
6063
6064 switch (LHSI->getOpcode()) {
6065 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6066 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6067 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6068 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006069 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6070 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006071 Value *CompareVal = LHSI->getOperand(0);
6072
6073 // If the sign bit of the XorCST is not set, there is no change to
6074 // the operation, just stop using the Xor.
6075 if (!XorCST->getValue().isNegative()) {
6076 ICI.setOperand(0, CompareVal);
6077 AddToWorkList(LHSI);
6078 return &ICI;
6079 }
6080
6081 // Was the old condition true if the operand is positive?
6082 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6083
6084 // If so, the new one isn't.
6085 isTrueIfPositive ^= true;
6086
6087 if (isTrueIfPositive)
6088 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6089 else
6090 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6091 }
6092 }
6093 break;
6094 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6095 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6096 LHSI->getOperand(0)->hasOneUse()) {
6097 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6098
6099 // If the LHS is an AND of a truncating cast, we can widen the
6100 // and/compare to be the input width without changing the value
6101 // produced, eliminating a cast.
6102 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6103 // We can do this transformation if either the AND constant does not
6104 // have its sign bit set or if it is an equality comparison.
6105 // Extending a relational comparison when we're checking the sign
6106 // bit would not work.
6107 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006108 (ICI.isEquality() ||
6109 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110 uint32_t BitWidth =
6111 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6112 APInt NewCST = AndCST->getValue();
6113 NewCST.zext(BitWidth);
6114 APInt NewCI = RHSV;
6115 NewCI.zext(BitWidth);
6116 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006117 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006118 ConstantInt::get(NewCST),LHSI->getName());
6119 InsertNewInstBefore(NewAnd, ICI);
6120 return new ICmpInst(ICI.getPredicate(), NewAnd,
6121 ConstantInt::get(NewCI));
6122 }
6123 }
6124
6125 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6126 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6127 // happens a LOT in code produced by the C front-end, for bitfield
6128 // access.
6129 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6130 if (Shift && !Shift->isShift())
6131 Shift = 0;
6132
6133 ConstantInt *ShAmt;
6134 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6135 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6136 const Type *AndTy = AndCST->getType(); // Type of the and.
6137
6138 // We can fold this as long as we can't shift unknown bits
6139 // into the mask. This can only happen with signed shift
6140 // rights, as they sign-extend.
6141 if (ShAmt) {
6142 bool CanFold = Shift->isLogicalShift();
6143 if (!CanFold) {
6144 // To test for the bad case of the signed shr, see if any
6145 // of the bits shifted in could be tested after the mask.
6146 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6147 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6148
6149 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6150 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6151 AndCST->getValue()) == 0)
6152 CanFold = true;
6153 }
6154
6155 if (CanFold) {
6156 Constant *NewCst;
6157 if (Shift->getOpcode() == Instruction::Shl)
6158 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6159 else
6160 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6161
6162 // Check to see if we are shifting out any of the bits being
6163 // compared.
6164 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6165 // If we shifted bits out, the fold is not going to work out.
6166 // As a special case, check to see if this means that the
6167 // result is always true or false now.
6168 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6169 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6170 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6171 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6172 } else {
6173 ICI.setOperand(1, NewCst);
6174 Constant *NewAndCST;
6175 if (Shift->getOpcode() == Instruction::Shl)
6176 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6177 else
6178 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6179 LHSI->setOperand(1, NewAndCST);
6180 LHSI->setOperand(0, Shift->getOperand(0));
6181 AddToWorkList(Shift); // Shift is dead.
6182 AddUsesToWorkList(ICI);
6183 return &ICI;
6184 }
6185 }
6186 }
6187
6188 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6189 // preferable because it allows the C<<Y expression to be hoisted out
6190 // of a loop if Y is invariant and X is not.
6191 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6192 ICI.isEquality() && !Shift->isArithmeticShift() &&
6193 isa<Instruction>(Shift->getOperand(0))) {
6194 // Compute C << Y.
6195 Value *NS;
6196 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006197 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006198 Shift->getOperand(1), "tmp");
6199 } else {
6200 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006201 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006202 Shift->getOperand(1), "tmp");
6203 }
6204 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6205
6206 // Compute X & (C << Y).
6207 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006208 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006209 InsertNewInstBefore(NewAnd, ICI);
6210
6211 ICI.setOperand(0, NewAnd);
6212 return &ICI;
6213 }
6214 }
6215 break;
6216
6217 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6218 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6219 if (!ShAmt) break;
6220
6221 uint32_t TypeBits = RHSV.getBitWidth();
6222
6223 // Check that the shift amount is in range. If not, don't perform
6224 // undefined shifts. When the shift is visited it will be
6225 // simplified.
6226 if (ShAmt->uge(TypeBits))
6227 break;
6228
6229 if (ICI.isEquality()) {
6230 // If we are comparing against bits always shifted out, the
6231 // comparison cannot succeed.
6232 Constant *Comp =
6233 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6234 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6235 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6236 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6237 return ReplaceInstUsesWith(ICI, Cst);
6238 }
6239
6240 if (LHSI->hasOneUse()) {
6241 // Otherwise strength reduce the shift into an and.
6242 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6243 Constant *Mask =
6244 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6245
6246 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006247 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006248 Mask, LHSI->getName()+".mask");
6249 Value *And = InsertNewInstBefore(AndI, ICI);
6250 return new ICmpInst(ICI.getPredicate(), And,
6251 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6252 }
6253 }
6254
6255 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6256 bool TrueIfSigned = false;
6257 if (LHSI->hasOneUse() &&
6258 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6259 // (X << 31) <s 0 --> (X&1) != 0
6260 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6261 (TypeBits-ShAmt->getZExtValue()-1));
6262 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006263 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006264 Mask, LHSI->getName()+".mask");
6265 Value *And = InsertNewInstBefore(AndI, ICI);
6266
6267 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6268 And, Constant::getNullValue(And->getType()));
6269 }
6270 break;
6271 }
6272
6273 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6274 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006275 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006276 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006277 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006278
Chris Lattner5ee84f82008-03-21 05:19:58 +00006279 // Check that the shift amount is in range. If not, don't perform
6280 // undefined shifts. When the shift is visited it will be
6281 // simplified.
6282 uint32_t TypeBits = RHSV.getBitWidth();
6283 if (ShAmt->uge(TypeBits))
6284 break;
6285
6286 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006287
Chris Lattner5ee84f82008-03-21 05:19:58 +00006288 // If we are comparing against bits always shifted out, the
6289 // comparison cannot succeed.
6290 APInt Comp = RHSV << ShAmtVal;
6291 if (LHSI->getOpcode() == Instruction::LShr)
6292 Comp = Comp.lshr(ShAmtVal);
6293 else
6294 Comp = Comp.ashr(ShAmtVal);
6295
6296 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6297 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6298 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6299 return ReplaceInstUsesWith(ICI, Cst);
6300 }
6301
6302 // Otherwise, check to see if the bits shifted out are known to be zero.
6303 // If so, we can compare against the unshifted value:
6304 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006305 if (LHSI->hasOneUse() &&
6306 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006307 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6308 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6309 ConstantExpr::getShl(RHS, ShAmt));
6310 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006311
Evan Chengfb9292a2008-04-23 00:38:06 +00006312 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006313 // Otherwise strength reduce the shift into an and.
6314 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6315 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006316
Chris Lattner5ee84f82008-03-21 05:19:58 +00006317 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006318 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006319 Mask, LHSI->getName()+".mask");
6320 Value *And = InsertNewInstBefore(AndI, ICI);
6321 return new ICmpInst(ICI.getPredicate(), And,
6322 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323 }
6324 break;
6325 }
6326
6327 case Instruction::SDiv:
6328 case Instruction::UDiv:
6329 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6330 // Fold this div into the comparison, producing a range check.
6331 // Determine, based on the divide type, what the range is being
6332 // checked. If there is an overflow on the low or high side, remember
6333 // it, otherwise compute the range [low, hi) bounding the new value.
6334 // See: InsertRangeTest above for the kinds of replacements possible.
6335 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6336 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6337 DivRHS))
6338 return R;
6339 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006340
6341 case Instruction::Add:
6342 // Fold: icmp pred (add, X, C1), C2
6343
6344 if (!ICI.isEquality()) {
6345 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6346 if (!LHSC) break;
6347 const APInt &LHSV = LHSC->getValue();
6348
6349 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6350 .subtract(LHSV);
6351
6352 if (ICI.isSignedPredicate()) {
6353 if (CR.getLower().isSignBit()) {
6354 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6355 ConstantInt::get(CR.getUpper()));
6356 } else if (CR.getUpper().isSignBit()) {
6357 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6358 ConstantInt::get(CR.getLower()));
6359 }
6360 } else {
6361 if (CR.getLower().isMinValue()) {
6362 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6363 ConstantInt::get(CR.getUpper()));
6364 } else if (CR.getUpper().isMinValue()) {
6365 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6366 ConstantInt::get(CR.getLower()));
6367 }
6368 }
6369 }
6370 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006371 }
6372
6373 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6374 if (ICI.isEquality()) {
6375 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6376
6377 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6378 // the second operand is a constant, simplify a bit.
6379 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6380 switch (BO->getOpcode()) {
6381 case Instruction::SRem:
6382 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6383 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6384 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6385 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6386 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006387 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006388 BO->getName());
6389 InsertNewInstBefore(NewRem, ICI);
6390 return new ICmpInst(ICI.getPredicate(), NewRem,
6391 Constant::getNullValue(BO->getType()));
6392 }
6393 }
6394 break;
6395 case Instruction::Add:
6396 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6397 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6398 if (BO->hasOneUse())
6399 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6400 Subtract(RHS, BOp1C));
6401 } else if (RHSV == 0) {
6402 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6403 // efficiently invertible, or if the add has just this one use.
6404 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6405
6406 if (Value *NegVal = dyn_castNegVal(BOp1))
6407 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6408 else if (Value *NegVal = dyn_castNegVal(BOp0))
6409 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6410 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006411 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006412 InsertNewInstBefore(Neg, ICI);
6413 Neg->takeName(BO);
6414 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6415 }
6416 }
6417 break;
6418 case Instruction::Xor:
6419 // For the xor case, we can xor two constants together, eliminating
6420 // the explicit xor.
6421 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6422 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6423 ConstantExpr::getXor(RHS, BOC));
6424
6425 // FALLTHROUGH
6426 case Instruction::Sub:
6427 // Replace (([sub|xor] A, B) != 0) with (A != B)
6428 if (RHSV == 0)
6429 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6430 BO->getOperand(1));
6431 break;
6432
6433 case Instruction::Or:
6434 // If bits are being or'd in that are not present in the constant we
6435 // are comparing against, then the comparison could never succeed!
6436 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6437 Constant *NotCI = ConstantExpr::getNot(RHS);
6438 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6439 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6440 isICMP_NE));
6441 }
6442 break;
6443
6444 case Instruction::And:
6445 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6446 // If bits are being compared against that are and'd out, then the
6447 // comparison can never succeed!
6448 if ((RHSV & ~BOC->getValue()) != 0)
6449 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6450 isICMP_NE));
6451
6452 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6453 if (RHS == BOC && RHSV.isPowerOf2())
6454 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6455 ICmpInst::ICMP_NE, LHSI,
6456 Constant::getNullValue(RHS->getType()));
6457
6458 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6459 if (isSignBit(BOC)) {
6460 Value *X = BO->getOperand(0);
6461 Constant *Zero = Constant::getNullValue(X->getType());
6462 ICmpInst::Predicate pred = isICMP_NE ?
6463 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6464 return new ICmpInst(pred, X, Zero);
6465 }
6466
6467 // ((X & ~7) == 0) --> X < 8
6468 if (RHSV == 0 && isHighOnes(BOC)) {
6469 Value *X = BO->getOperand(0);
6470 Constant *NegX = ConstantExpr::getNeg(BOC);
6471 ICmpInst::Predicate pred = isICMP_NE ?
6472 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6473 return new ICmpInst(pred, X, NegX);
6474 }
6475 }
6476 default: break;
6477 }
6478 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6479 // Handle icmp {eq|ne} <intrinsic>, intcst.
6480 if (II->getIntrinsicID() == Intrinsic::bswap) {
6481 AddToWorkList(II);
6482 ICI.setOperand(0, II->getOperand(1));
6483 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6484 return &ICI;
6485 }
6486 }
6487 } else { // Not a ICMP_EQ/ICMP_NE
6488 // If the LHS is a cast from an integral value of the same size,
6489 // then since we know the RHS is a constant, try to simlify.
6490 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6491 Value *CastOp = Cast->getOperand(0);
6492 const Type *SrcTy = CastOp->getType();
6493 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6494 if (SrcTy->isInteger() &&
6495 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6496 // If this is an unsigned comparison, try to make the comparison use
6497 // smaller constant values.
6498 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6499 // X u< 128 => X s> -1
6500 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6501 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6502 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6503 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6504 // X u> 127 => X s< 0
6505 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6506 Constant::getNullValue(SrcTy));
6507 }
6508 }
6509 }
6510 }
6511 return 0;
6512}
6513
6514/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6515/// We only handle extending casts so far.
6516///
6517Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6518 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6519 Value *LHSCIOp = LHSCI->getOperand(0);
6520 const Type *SrcTy = LHSCIOp->getType();
6521 const Type *DestTy = LHSCI->getType();
6522 Value *RHSCIOp;
6523
6524 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6525 // integer type is the same size as the pointer type.
6526 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6527 getTargetData().getPointerSizeInBits() ==
6528 cast<IntegerType>(DestTy)->getBitWidth()) {
6529 Value *RHSOp = 0;
6530 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6531 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6532 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6533 RHSOp = RHSC->getOperand(0);
6534 // If the pointer types don't match, insert a bitcast.
6535 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006536 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006537 }
6538
6539 if (RHSOp)
6540 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6541 }
6542
6543 // The code below only handles extension cast instructions, so far.
6544 // Enforce this.
6545 if (LHSCI->getOpcode() != Instruction::ZExt &&
6546 LHSCI->getOpcode() != Instruction::SExt)
6547 return 0;
6548
6549 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6550 bool isSignedCmp = ICI.isSignedPredicate();
6551
6552 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6553 // Not an extension from the same type?
6554 RHSCIOp = CI->getOperand(0);
6555 if (RHSCIOp->getType() != LHSCIOp->getType())
6556 return 0;
6557
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006558 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559 // and the other is a zext), then we can't handle this.
6560 if (CI->getOpcode() != LHSCI->getOpcode())
6561 return 0;
6562
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006563 // Deal with equality cases early.
6564 if (ICI.isEquality())
6565 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6566
6567 // A signed comparison of sign extended values simplifies into a
6568 // signed comparison.
6569 if (isSignedCmp && isSignedExt)
6570 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6571
6572 // The other three cases all fold into an unsigned comparison.
6573 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006574 }
6575
6576 // If we aren't dealing with a constant on the RHS, exit early
6577 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6578 if (!CI)
6579 return 0;
6580
6581 // Compute the constant that would happen if we truncated to SrcTy then
6582 // reextended to DestTy.
6583 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6584 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6585
6586 // If the re-extended constant didn't change...
6587 if (Res2 == CI) {
6588 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6589 // For example, we might have:
6590 // %A = sext short %X to uint
6591 // %B = icmp ugt uint %A, 1330
6592 // It is incorrect to transform this into
6593 // %B = icmp ugt short %X, 1330
6594 // because %A may have negative value.
6595 //
6596 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6597 // OR operation is EQ/NE.
6598 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6599 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6600 else
6601 return 0;
6602 }
6603
6604 // The re-extended constant changed so the constant cannot be represented
6605 // in the shorter type. Consequently, we cannot emit a simple comparison.
6606
6607 // First, handle some easy cases. We know the result cannot be equal at this
6608 // point so handle the ICI.isEquality() cases
6609 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6610 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6611 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6612 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6613
6614 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6615 // should have been folded away previously and not enter in here.
6616 Value *Result;
6617 if (isSignedCmp) {
6618 // We're performing a signed comparison.
6619 if (cast<ConstantInt>(CI)->getValue().isNegative())
6620 Result = ConstantInt::getFalse(); // X < (small) --> false
6621 else
6622 Result = ConstantInt::getTrue(); // X < (large) --> true
6623 } else {
6624 // We're performing an unsigned comparison.
6625 if (isSignedExt) {
6626 // We're performing an unsigned comp with a sign extended value.
6627 // This is true if the input is >= 0. [aka >s -1]
6628 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6629 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6630 NegOne, ICI.getName()), ICI);
6631 } else {
6632 // Unsigned extend & unsigned compare -> always true.
6633 Result = ConstantInt::getTrue();
6634 }
6635 }
6636
6637 // Finally, return the value computed.
6638 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6639 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6640 return ReplaceInstUsesWith(ICI, Result);
6641 } else {
6642 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6643 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6644 "ICmp should be folded!");
6645 if (Constant *CI = dyn_cast<Constant>(Result))
6646 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6647 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006648 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006649 }
6650}
6651
6652Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6653 return commonShiftTransforms(I);
6654}
6655
6656Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6657 return commonShiftTransforms(I);
6658}
6659
6660Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006661 if (Instruction *R = commonShiftTransforms(I))
6662 return R;
6663
6664 Value *Op0 = I.getOperand(0);
6665
6666 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6667 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6668 if (CSI->isAllOnesValue())
6669 return ReplaceInstUsesWith(I, CSI);
6670
6671 // See if we can turn a signed shr into an unsigned shr.
6672 if (MaskedValueIsZero(Op0,
6673 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006674 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006675
6676 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006677}
6678
6679Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6680 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6682
6683 // shl X, 0 == X and shr X, 0 == X
6684 // shl 0, X == 0 and shr 0, X == 0
6685 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6686 Op0 == Constant::getNullValue(Op0->getType()))
6687 return ReplaceInstUsesWith(I, Op0);
6688
6689 if (isa<UndefValue>(Op0)) {
6690 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6691 return ReplaceInstUsesWith(I, Op0);
6692 else // undef << X -> 0, undef >>u X -> 0
6693 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6694 }
6695 if (isa<UndefValue>(Op1)) {
6696 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6697 return ReplaceInstUsesWith(I, Op0);
6698 else // X << undef, X >>u undef -> 0
6699 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6700 }
6701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 // Try to fold constant and into select arguments.
6703 if (isa<Constant>(Op0))
6704 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6705 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6706 return R;
6707
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006708 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6709 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6710 return Res;
6711 return 0;
6712}
6713
6714Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6715 BinaryOperator &I) {
6716 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6717
6718 // See if we can simplify any instructions used by the instruction whose sole
6719 // purpose is to compute bits we don't care about.
6720 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6721 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6722 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6723 KnownZero, KnownOne))
6724 return &I;
6725
6726 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6727 // of a signed value.
6728 //
6729 if (Op1->uge(TypeBits)) {
6730 if (I.getOpcode() != Instruction::AShr)
6731 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6732 else {
6733 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6734 return &I;
6735 }
6736 }
6737
6738 // ((X*C1) << C2) == (X * (C1 << C2))
6739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6740 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6741 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006742 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006743 ConstantExpr::getShl(BOOp, Op1));
6744
6745 // Try to fold constant and into select arguments.
6746 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6747 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6748 return R;
6749 if (isa<PHINode>(Op0))
6750 if (Instruction *NV = FoldOpIntoPhi(I))
6751 return NV;
6752
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006753 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6754 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6755 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6756 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6757 // place. Don't try to do this transformation in this case. Also, we
6758 // require that the input operand is a shift-by-constant so that we have
6759 // confidence that the shifts will get folded together. We could do this
6760 // xform in more cases, but it is unlikely to be profitable.
6761 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6762 isa<ConstantInt>(TrOp->getOperand(1))) {
6763 // Okay, we'll do this xform. Make the shift of shift.
6764 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006765 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006766 I.getName());
6767 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6768
6769 // For logical shifts, the truncation has the effect of making the high
6770 // part of the register be zeros. Emulate this by inserting an AND to
6771 // clear the top bits as needed. This 'and' will usually be zapped by
6772 // other xforms later if dead.
6773 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6774 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6775 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6776
6777 // The mask we constructed says what the trunc would do if occurring
6778 // between the shifts. We want to know the effect *after* the second
6779 // shift. We know that it is a logical shift by a constant, so adjust the
6780 // mask as appropriate.
6781 if (I.getOpcode() == Instruction::Shl)
6782 MaskV <<= Op1->getZExtValue();
6783 else {
6784 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6785 MaskV = MaskV.lshr(Op1->getZExtValue());
6786 }
6787
Gabor Greifa645dd32008-05-16 19:29:10 +00006788 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006789 TI->getName());
6790 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6791
6792 // Return the value truncated to the interesting size.
6793 return new TruncInst(And, I.getType());
6794 }
6795 }
6796
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006797 if (Op0->hasOneUse()) {
6798 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6799 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6800 Value *V1, *V2;
6801 ConstantInt *CC;
6802 switch (Op0BO->getOpcode()) {
6803 default: break;
6804 case Instruction::Add:
6805 case Instruction::And:
6806 case Instruction::Or:
6807 case Instruction::Xor: {
6808 // These operators commute.
6809 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6810 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6811 match(Op0BO->getOperand(1),
6812 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006813 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006814 Op0BO->getOperand(0), Op1,
6815 Op0BO->getName());
6816 InsertNewInstBefore(YS, I); // (Y << C)
6817 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006818 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006819 Op0BO->getOperand(1)->getName());
6820 InsertNewInstBefore(X, I); // (X + (Y << C))
6821 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006822 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6824 }
6825
6826 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6827 Value *Op0BOOp1 = Op0BO->getOperand(1);
6828 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6829 match(Op0BOOp1,
6830 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6831 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6832 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006833 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834 Op0BO->getOperand(0), Op1,
6835 Op0BO->getName());
6836 InsertNewInstBefore(YS, I); // (Y << C)
6837 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006838 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006839 V1->getName()+".mask");
6840 InsertNewInstBefore(XM, I); // X & (CC << C)
6841
Gabor Greifa645dd32008-05-16 19:29:10 +00006842 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006843 }
6844 }
6845
6846 // FALL THROUGH.
6847 case Instruction::Sub: {
6848 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6849 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6850 match(Op0BO->getOperand(0),
6851 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006852 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006853 Op0BO->getOperand(1), Op1,
6854 Op0BO->getName());
6855 InsertNewInstBefore(YS, I); // (Y << C)
6856 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006857 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006858 Op0BO->getOperand(0)->getName());
6859 InsertNewInstBefore(X, I); // (X + (Y << C))
6860 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006861 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006862 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6863 }
6864
6865 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6866 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6867 match(Op0BO->getOperand(0),
6868 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6869 m_ConstantInt(CC))) && V2 == Op1 &&
6870 cast<BinaryOperator>(Op0BO->getOperand(0))
6871 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006872 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006873 Op0BO->getOperand(1), Op1,
6874 Op0BO->getName());
6875 InsertNewInstBefore(YS, I); // (Y << C)
6876 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006877 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006878 V1->getName()+".mask");
6879 InsertNewInstBefore(XM, I); // X & (CC << C)
6880
Gabor Greifa645dd32008-05-16 19:29:10 +00006881 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006882 }
6883
6884 break;
6885 }
6886 }
6887
6888
6889 // If the operand is an bitwise operator with a constant RHS, and the
6890 // shift is the only use, we can pull it out of the shift.
6891 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6892 bool isValid = true; // Valid only for And, Or, Xor
6893 bool highBitSet = false; // Transform if high bit of constant set?
6894
6895 switch (Op0BO->getOpcode()) {
6896 default: isValid = false; break; // Do not perform transform!
6897 case Instruction::Add:
6898 isValid = isLeftShift;
6899 break;
6900 case Instruction::Or:
6901 case Instruction::Xor:
6902 highBitSet = false;
6903 break;
6904 case Instruction::And:
6905 highBitSet = true;
6906 break;
6907 }
6908
6909 // If this is a signed shift right, and the high bit is modified
6910 // by the logical operation, do not perform the transformation.
6911 // The highBitSet boolean indicates the value of the high bit of
6912 // the constant which would cause it to be modified for this
6913 // operation.
6914 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006915 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006916 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006917
6918 if (isValid) {
6919 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6920
6921 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006922 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006923 InsertNewInstBefore(NewShift, I);
6924 NewShift->takeName(Op0BO);
6925
Gabor Greifa645dd32008-05-16 19:29:10 +00006926 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006927 NewRHS);
6928 }
6929 }
6930 }
6931 }
6932
6933 // Find out if this is a shift of a shift by a constant.
6934 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6935 if (ShiftOp && !ShiftOp->isShift())
6936 ShiftOp = 0;
6937
6938 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6939 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6940 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6941 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6942 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6943 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6944 Value *X = ShiftOp->getOperand(0);
6945
6946 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6947 if (AmtSum > TypeBits)
6948 AmtSum = TypeBits;
6949
6950 const IntegerType *Ty = cast<IntegerType>(I.getType());
6951
6952 // Check for (X << c1) << c2 and (X >> c1) >> c2
6953 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006954 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006955 ConstantInt::get(Ty, AmtSum));
6956 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6957 I.getOpcode() == Instruction::AShr) {
6958 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006959 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006960 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6961 I.getOpcode() == Instruction::LShr) {
6962 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6963 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006964 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965 InsertNewInstBefore(Shift, I);
6966
6967 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006968 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006969 }
6970
6971 // Okay, if we get here, one shift must be left, and the other shift must be
6972 // right. See if the amounts are equal.
6973 if (ShiftAmt1 == ShiftAmt2) {
6974 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6975 if (I.getOpcode() == Instruction::Shl) {
6976 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006977 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978 }
6979 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6980 if (I.getOpcode() == Instruction::LShr) {
6981 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006982 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006983 }
6984 // We can simplify ((X << C) >>s C) into a trunc + sext.
6985 // NOTE: we could do this for any C, but that would make 'unusual' integer
6986 // types. For now, just stick to ones well-supported by the code
6987 // generators.
6988 const Type *SExtType = 0;
6989 switch (Ty->getBitWidth() - ShiftAmt1) {
6990 case 1 :
6991 case 8 :
6992 case 16 :
6993 case 32 :
6994 case 64 :
6995 case 128:
6996 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6997 break;
6998 default: break;
6999 }
7000 if (SExtType) {
7001 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7002 InsertNewInstBefore(NewTrunc, I);
7003 return new SExtInst(NewTrunc, Ty);
7004 }
7005 // Otherwise, we can't handle it yet.
7006 } else if (ShiftAmt1 < ShiftAmt2) {
7007 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7008
7009 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7010 if (I.getOpcode() == Instruction::Shl) {
7011 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7012 ShiftOp->getOpcode() == Instruction::AShr);
7013 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007014 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007015 InsertNewInstBefore(Shift, I);
7016
7017 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007018 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007019 }
7020
7021 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7022 if (I.getOpcode() == Instruction::LShr) {
7023 assert(ShiftOp->getOpcode() == Instruction::Shl);
7024 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007025 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007026 InsertNewInstBefore(Shift, I);
7027
7028 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007029 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007030 }
7031
7032 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7033 } else {
7034 assert(ShiftAmt2 < ShiftAmt1);
7035 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7036
7037 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7038 if (I.getOpcode() == Instruction::Shl) {
7039 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7040 ShiftOp->getOpcode() == Instruction::AShr);
7041 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007042 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007043 ConstantInt::get(Ty, ShiftDiff));
7044 InsertNewInstBefore(Shift, I);
7045
7046 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007047 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007048 }
7049
7050 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7051 if (I.getOpcode() == Instruction::LShr) {
7052 assert(ShiftOp->getOpcode() == Instruction::Shl);
7053 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007054 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007055 InsertNewInstBefore(Shift, I);
7056
7057 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007058 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007059 }
7060
7061 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7062 }
7063 }
7064 return 0;
7065}
7066
7067
7068/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7069/// expression. If so, decompose it, returning some value X, such that Val is
7070/// X*Scale+Offset.
7071///
7072static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7073 int &Offset) {
7074 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7075 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7076 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007077 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007078 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007079 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7080 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7081 if (I->getOpcode() == Instruction::Shl) {
7082 // This is a value scaled by '1 << the shift amt'.
7083 Scale = 1U << RHS->getZExtValue();
7084 Offset = 0;
7085 return I->getOperand(0);
7086 } else if (I->getOpcode() == Instruction::Mul) {
7087 // This value is scaled by 'RHS'.
7088 Scale = RHS->getZExtValue();
7089 Offset = 0;
7090 return I->getOperand(0);
7091 } else if (I->getOpcode() == Instruction::Add) {
7092 // We have X+C. Check to see if we really have (X*C2)+C1,
7093 // where C1 is divisible by C2.
7094 unsigned SubScale;
7095 Value *SubVal =
7096 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7097 Offset += RHS->getZExtValue();
7098 Scale = SubScale;
7099 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007100 }
7101 }
7102 }
7103
7104 // Otherwise, we can't look past this.
7105 Scale = 1;
7106 Offset = 0;
7107 return Val;
7108}
7109
7110
7111/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7112/// try to eliminate the cast by moving the type information into the alloc.
7113Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7114 AllocationInst &AI) {
7115 const PointerType *PTy = cast<PointerType>(CI.getType());
7116
7117 // Remove any uses of AI that are dead.
7118 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7119
7120 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7121 Instruction *User = cast<Instruction>(*UI++);
7122 if (isInstructionTriviallyDead(User)) {
7123 while (UI != E && *UI == User)
7124 ++UI; // If this instruction uses AI more than once, don't break UI.
7125
7126 ++NumDeadInst;
7127 DOUT << "IC: DCE: " << *User;
7128 EraseInstFromFunction(*User);
7129 }
7130 }
7131
7132 // Get the type really allocated and the type casted to.
7133 const Type *AllocElTy = AI.getAllocatedType();
7134 const Type *CastElTy = PTy->getElementType();
7135 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7136
7137 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7138 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7139 if (CastElTyAlign < AllocElTyAlign) return 0;
7140
7141 // If the allocation has multiple uses, only promote it if we are strictly
7142 // increasing the alignment of the resultant allocation. If we keep it the
7143 // same, we open the door to infinite loops of various kinds.
7144 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7145
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007146 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7147 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007148 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7149
7150 // See if we can satisfy the modulus by pulling a scale out of the array
7151 // size argument.
7152 unsigned ArraySizeScale;
7153 int ArrayOffset;
7154 Value *NumElements = // See if the array size is a decomposable linear expr.
7155 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7156
7157 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7158 // do the xform.
7159 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7160 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7161
7162 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7163 Value *Amt = 0;
7164 if (Scale == 1) {
7165 Amt = NumElements;
7166 } else {
7167 // If the allocation size is constant, form a constant mul expression
7168 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7169 if (isa<ConstantInt>(NumElements))
7170 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7171 // otherwise multiply the amount and the number of elements
7172 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007173 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 Amt = InsertNewInstBefore(Tmp, AI);
7175 }
7176 }
7177
7178 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7179 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007180 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007181 Amt = InsertNewInstBefore(Tmp, AI);
7182 }
7183
7184 AllocationInst *New;
7185 if (isa<MallocInst>(AI))
7186 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7187 else
7188 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7189 InsertNewInstBefore(New, AI);
7190 New->takeName(&AI);
7191
7192 // If the allocation has multiple uses, insert a cast and change all things
7193 // that used it to use the new cast. This will also hack on CI, but it will
7194 // die soon.
7195 if (!AI.hasOneUse()) {
7196 AddUsesToWorkList(AI);
7197 // New is the allocation instruction, pointer typed. AI is the original
7198 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7199 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7200 InsertNewInstBefore(NewCast, AI);
7201 AI.replaceAllUsesWith(NewCast);
7202 }
7203 return ReplaceInstUsesWith(CI, New);
7204}
7205
7206/// CanEvaluateInDifferentType - Return true if we can take the specified value
7207/// and return it as type Ty without inserting any new casts and without
7208/// changing the computed value. This is used by code that tries to decide
7209/// whether promoting or shrinking integer operations to wider or smaller types
7210/// will allow us to eliminate a truncate or extend.
7211///
7212/// This is a truncation operation if Ty is smaller than V->getType(), or an
7213/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007214bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7215 unsigned CastOpc,
7216 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007217 // We can always evaluate constants in another type.
7218 if (isa<ConstantInt>(V))
7219 return true;
7220
7221 Instruction *I = dyn_cast<Instruction>(V);
7222 if (!I) return false;
7223
7224 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7225
Chris Lattneref70bb82007-08-02 06:11:14 +00007226 // If this is an extension or truncate, we can often eliminate it.
7227 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7228 // If this is a cast from the destination type, we can trivially eliminate
7229 // it, and this will remove a cast overall.
7230 if (I->getOperand(0)->getType() == Ty) {
7231 // If the first operand is itself a cast, and is eliminable, do not count
7232 // this as an eliminable cast. We would prefer to eliminate those two
7233 // casts first.
7234 if (!isa<CastInst>(I->getOperand(0)))
7235 ++NumCastsRemoved;
7236 return true;
7237 }
7238 }
7239
7240 // We can't extend or shrink something that has multiple uses: doing so would
7241 // require duplicating the instruction in general, which isn't profitable.
7242 if (!I->hasOneUse()) return false;
7243
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007244 switch (I->getOpcode()) {
7245 case Instruction::Add:
7246 case Instruction::Sub:
7247 case Instruction::And:
7248 case Instruction::Or:
7249 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007250 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007251 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7252 NumCastsRemoved) &&
7253 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7254 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007255
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007256 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007257 // A multiply can be truncated by truncating its operands.
7258 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7259 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7260 NumCastsRemoved) &&
7261 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7262 NumCastsRemoved);
7263
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007264 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007265 // If we are truncating the result of this SHL, and if it's a shift of a
7266 // constant amount, we can always perform a SHL in a smaller type.
7267 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7268 uint32_t BitWidth = Ty->getBitWidth();
7269 if (BitWidth < OrigTy->getBitWidth() &&
7270 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007271 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7272 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 }
7274 break;
7275 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276 // If this is a truncate of a logical shr, we can truncate it to a smaller
7277 // lshr iff we know that the bits we would otherwise be shifting in are
7278 // already zeros.
7279 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7280 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7281 uint32_t BitWidth = Ty->getBitWidth();
7282 if (BitWidth < OrigBitWidth &&
7283 MaskedValueIsZero(I->getOperand(0),
7284 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7285 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007286 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7287 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288 }
7289 }
7290 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007291 case Instruction::ZExt:
7292 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007293 case Instruction::Trunc:
7294 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007295 // can safely replace it. Note that replacing it does not reduce the number
7296 // of casts in the input.
7297 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00007299
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 break;
7301 default:
7302 // TODO: Can handle more cases here.
7303 break;
7304 }
7305
7306 return false;
7307}
7308
7309/// EvaluateInDifferentType - Given an expression that
7310/// CanEvaluateInDifferentType returns true for, actually insert the code to
7311/// evaluate the expression.
7312Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7313 bool isSigned) {
7314 if (Constant *C = dyn_cast<Constant>(V))
7315 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7316
7317 // Otherwise, it must be an instruction.
7318 Instruction *I = cast<Instruction>(V);
7319 Instruction *Res = 0;
7320 switch (I->getOpcode()) {
7321 case Instruction::Add:
7322 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007323 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007324 case Instruction::And:
7325 case Instruction::Or:
7326 case Instruction::Xor:
7327 case Instruction::AShr:
7328 case Instruction::LShr:
7329 case Instruction::Shl: {
7330 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7331 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007332 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 LHS, RHS, I->getName());
7334 break;
7335 }
7336 case Instruction::Trunc:
7337 case Instruction::ZExt:
7338 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007339 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007340 // just return the source. There's no need to insert it because it is not
7341 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007342 if (I->getOperand(0)->getType() == Ty)
7343 return I->getOperand(0);
7344
Chris Lattneref70bb82007-08-02 06:11:14 +00007345 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007346 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007347 Ty, I->getName());
7348 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007349 default:
7350 // TODO: Can handle more cases here.
7351 assert(0 && "Unreachable!");
7352 break;
7353 }
7354
7355 return InsertNewInstBefore(Res, *I);
7356}
7357
7358/// @brief Implement the transforms common to all CastInst visitors.
7359Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7360 Value *Src = CI.getOperand(0);
7361
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007362 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7363 // eliminate it now.
7364 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7365 if (Instruction::CastOps opc =
7366 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7367 // The first cast (CSrc) is eliminable so we need to fix up or replace
7368 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007369 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007370 }
7371 }
7372
7373 // If we are casting a select then fold the cast into the select
7374 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7375 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7376 return NV;
7377
7378 // If we are casting a PHI then fold the cast into the PHI
7379 if (isa<PHINode>(Src))
7380 if (Instruction *NV = FoldOpIntoPhi(CI))
7381 return NV;
7382
7383 return 0;
7384}
7385
7386/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7387Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7388 Value *Src = CI.getOperand(0);
7389
7390 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7391 // If casting the result of a getelementptr instruction with no offset, turn
7392 // this into a cast of the original pointer!
7393 if (GEP->hasAllZeroIndices()) {
7394 // Changing the cast operand is usually not a good idea but it is safe
7395 // here because the pointer operand is being replaced with another
7396 // pointer operand so the opcode doesn't need to change.
7397 AddToWorkList(GEP);
7398 CI.setOperand(0, GEP->getOperand(0));
7399 return &CI;
7400 }
7401
7402 // If the GEP has a single use, and the base pointer is a bitcast, and the
7403 // GEP computes a constant offset, see if we can convert these three
7404 // instructions into fewer. This typically happens with unions and other
7405 // non-type-safe code.
7406 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7407 if (GEP->hasAllConstantIndices()) {
7408 // We are guaranteed to get a constant from EmitGEPOffset.
7409 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7410 int64_t Offset = OffsetV->getSExtValue();
7411
7412 // Get the base pointer input of the bitcast, and the type it points to.
7413 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7414 const Type *GEPIdxTy =
7415 cast<PointerType>(OrigBase->getType())->getElementType();
7416 if (GEPIdxTy->isSized()) {
7417 SmallVector<Value*, 8> NewIndices;
7418
7419 // Start with the index over the outer type. Note that the type size
7420 // might be zero (even if the offset isn't zero) if the indexed type
7421 // is something like [0 x {int, int}]
7422 const Type *IntPtrTy = TD->getIntPtrType();
7423 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007424 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007425 FirstIdx = Offset/TySize;
7426 Offset %= TySize;
7427
7428 // Handle silly modulus not returning values values [0..TySize).
7429 if (Offset < 0) {
7430 --FirstIdx;
7431 Offset += TySize;
7432 assert(Offset >= 0);
7433 }
7434 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7435 }
7436
7437 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7438
7439 // Index into the types. If we fail, set OrigBase to null.
7440 while (Offset) {
7441 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7442 const StructLayout *SL = TD->getStructLayout(STy);
7443 if (Offset < (int64_t)SL->getSizeInBytes()) {
7444 unsigned Elt = SL->getElementContainingOffset(Offset);
7445 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7446
7447 Offset -= SL->getElementOffset(Elt);
7448 GEPIdxTy = STy->getElementType(Elt);
7449 } else {
7450 // Otherwise, we can't index into this, bail out.
7451 Offset = 0;
7452 OrigBase = 0;
7453 }
7454 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7455 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007456 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007457 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7458 Offset %= EltSize;
7459 } else {
7460 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7461 }
7462 GEPIdxTy = STy->getElementType();
7463 } else {
7464 // Otherwise, we can't index into this, bail out.
7465 Offset = 0;
7466 OrigBase = 0;
7467 }
7468 }
7469 if (OrigBase) {
7470 // If we were able to index down into an element, create the GEP
7471 // and bitcast the result. This eliminates one bitcast, potentially
7472 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007473 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7474 NewIndices.begin(),
7475 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007476 InsertNewInstBefore(NGEP, CI);
7477 NGEP->takeName(GEP);
7478
7479 if (isa<BitCastInst>(CI))
7480 return new BitCastInst(NGEP, CI.getType());
7481 assert(isa<PtrToIntInst>(CI));
7482 return new PtrToIntInst(NGEP, CI.getType());
7483 }
7484 }
7485 }
7486 }
7487 }
7488
7489 return commonCastTransforms(CI);
7490}
7491
7492
7493
7494/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7495/// integer types. This function implements the common transforms for all those
7496/// cases.
7497/// @brief Implement the transforms common to CastInst with integer operands
7498Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7499 if (Instruction *Result = commonCastTransforms(CI))
7500 return Result;
7501
7502 Value *Src = CI.getOperand(0);
7503 const Type *SrcTy = Src->getType();
7504 const Type *DestTy = CI.getType();
7505 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7506 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7507
7508 // See if we can simplify any instructions used by the LHS whose sole
7509 // purpose is to compute bits we don't care about.
7510 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7511 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7512 KnownZero, KnownOne))
7513 return &CI;
7514
7515 // If the source isn't an instruction or has more than one use then we
7516 // can't do anything more.
7517 Instruction *SrcI = dyn_cast<Instruction>(Src);
7518 if (!SrcI || !Src->hasOneUse())
7519 return 0;
7520
7521 // Attempt to propagate the cast into the instruction for int->int casts.
7522 int NumCastsRemoved = 0;
7523 if (!isa<BitCastInst>(CI) &&
7524 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007525 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007526 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007527 // eliminates the cast, so it is always a win. If this is a zero-extension,
7528 // we need to do an AND to maintain the clear top-part of the computation,
7529 // so we require that the input have eliminated at least one cast. If this
7530 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 // require that two casts have been eliminated.
7532 bool DoXForm;
7533 switch (CI.getOpcode()) {
7534 default:
7535 // All the others use floating point so we shouldn't actually
7536 // get here because of the check above.
7537 assert(0 && "Unknown cast type");
7538 case Instruction::Trunc:
7539 DoXForm = true;
7540 break;
7541 case Instruction::ZExt:
7542 DoXForm = NumCastsRemoved >= 1;
7543 break;
7544 case Instruction::SExt:
7545 DoXForm = NumCastsRemoved >= 2;
7546 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 }
7548
7549 if (DoXForm) {
7550 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7551 CI.getOpcode() == Instruction::SExt);
7552 assert(Res->getType() == DestTy);
7553 switch (CI.getOpcode()) {
7554 default: assert(0 && "Unknown cast type!");
7555 case Instruction::Trunc:
7556 case Instruction::BitCast:
7557 // Just replace this cast with the result.
7558 return ReplaceInstUsesWith(CI, Res);
7559 case Instruction::ZExt: {
7560 // We need to emit an AND to clear the high bits.
7561 assert(SrcBitSize < DestBitSize && "Not a zext?");
7562 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7563 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007565 }
7566 case Instruction::SExt:
7567 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007568 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007569 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7570 CI), DestTy);
7571 }
7572 }
7573 }
7574
7575 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7576 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7577
7578 switch (SrcI->getOpcode()) {
7579 case Instruction::Add:
7580 case Instruction::Mul:
7581 case Instruction::And:
7582 case Instruction::Or:
7583 case Instruction::Xor:
7584 // If we are discarding information, rewrite.
7585 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7586 // Don't insert two casts if they cannot be eliminated. We allow
7587 // two casts to be inserted if the sizes are the same. This could
7588 // only be converting signedness, which is a noop.
7589 if (DestBitSize == SrcBitSize ||
7590 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7591 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7592 Instruction::CastOps opcode = CI.getOpcode();
7593 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7594 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007595 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007596 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7597 }
7598 }
7599
7600 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7601 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7602 SrcI->getOpcode() == Instruction::Xor &&
7603 Op1 == ConstantInt::getTrue() &&
7604 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7605 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007606 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007607 }
7608 break;
7609 case Instruction::SDiv:
7610 case Instruction::UDiv:
7611 case Instruction::SRem:
7612 case Instruction::URem:
7613 // If we are just changing the sign, rewrite.
7614 if (DestBitSize == SrcBitSize) {
7615 // Don't insert two casts if they cannot be eliminated. We allow
7616 // two casts to be inserted if the sizes are the same. This could
7617 // only be converting signedness, which is a noop.
7618 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7619 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7620 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7621 Op0, DestTy, SrcI);
7622 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7623 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007624 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007625 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7626 }
7627 }
7628 break;
7629
7630 case Instruction::Shl:
7631 // Allow changing the sign of the source operand. Do not allow
7632 // changing the size of the shift, UNLESS the shift amount is a
7633 // constant. We must not change variable sized shifts to a smaller
7634 // size, because it is undefined to shift more bits out than exist
7635 // in the value.
7636 if (DestBitSize == SrcBitSize ||
7637 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7638 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7639 Instruction::BitCast : Instruction::Trunc);
7640 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7641 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007642 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007643 }
7644 break;
7645 case Instruction::AShr:
7646 // If this is a signed shr, and if all bits shifted in are about to be
7647 // truncated off, turn it into an unsigned shr to allow greater
7648 // simplifications.
7649 if (DestBitSize < SrcBitSize &&
7650 isa<ConstantInt>(Op1)) {
7651 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7652 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7653 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656 }
7657 break;
7658 }
7659 return 0;
7660}
7661
7662Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7663 if (Instruction *Result = commonIntCastTransforms(CI))
7664 return Result;
7665
7666 Value *Src = CI.getOperand(0);
7667 const Type *Ty = CI.getType();
7668 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7669 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7670
7671 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7672 switch (SrcI->getOpcode()) {
7673 default: break;
7674 case Instruction::LShr:
7675 // We can shrink lshr to something smaller if we know the bits shifted in
7676 // are already zeros.
7677 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7678 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7679
7680 // Get a mask for the bits shifting in.
7681 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7682 Value* SrcIOp0 = SrcI->getOperand(0);
7683 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7684 if (ShAmt >= DestBitWidth) // All zeros.
7685 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7686
7687 // Okay, we can shrink this. Truncate the input, then return a new
7688 // shift.
7689 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7690 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7691 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007692 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007693 }
7694 } else { // This is a variable shr.
7695
7696 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7697 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7698 // loop-invariant and CSE'd.
7699 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7700 Value *One = ConstantInt::get(SrcI->getType(), 1);
7701
7702 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007703 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007704 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007705 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007706 SrcI->getOperand(0),
7707 "tmp"), CI);
7708 Value *Zero = Constant::getNullValue(V->getType());
7709 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7710 }
7711 }
7712 break;
7713 }
7714 }
7715
7716 return 0;
7717}
7718
Evan Chenge3779cf2008-03-24 00:21:34 +00007719/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7720/// in order to eliminate the icmp.
7721Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7722 bool DoXform) {
7723 // If we are just checking for a icmp eq of a single bit and zext'ing it
7724 // to an integer, then shift the bit to the appropriate place and then
7725 // cast to integer to avoid the comparison.
7726 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7727 const APInt &Op1CV = Op1C->getValue();
7728
7729 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7730 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7731 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7732 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7733 if (!DoXform) return ICI;
7734
7735 Value *In = ICI->getOperand(0);
7736 Value *Sh = ConstantInt::get(In->getType(),
7737 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007738 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007739 In->getName()+".lobit"),
7740 CI);
7741 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007742 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007743 false/*ZExt*/, "tmp", &CI);
7744
7745 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7746 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007747 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007748 In->getName()+".not"),
7749 CI);
7750 }
7751
7752 return ReplaceInstUsesWith(CI, In);
7753 }
7754
7755
7756
7757 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7758 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7759 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7760 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7761 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7762 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7763 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7764 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7765 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7766 // This only works for EQ and NE
7767 ICI->isEquality()) {
7768 // If Op1C some other power of two, convert:
7769 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7770 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7771 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7772 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7773
7774 APInt KnownZeroMask(~KnownZero);
7775 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7776 if (!DoXform) return ICI;
7777
7778 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7779 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7780 // (X&4) == 2 --> false
7781 // (X&4) != 2 --> true
7782 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7783 Res = ConstantExpr::getZExt(Res, CI.getType());
7784 return ReplaceInstUsesWith(CI, Res);
7785 }
7786
7787 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7788 Value *In = ICI->getOperand(0);
7789 if (ShiftAmt) {
7790 // Perform a logical shr by shiftamt.
7791 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007792 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007793 ConstantInt::get(In->getType(), ShiftAmt),
7794 In->getName()+".lobit"), CI);
7795 }
7796
7797 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7798 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007799 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007800 InsertNewInstBefore(cast<Instruction>(In), CI);
7801 }
7802
7803 if (CI.getType() == In->getType())
7804 return ReplaceInstUsesWith(CI, In);
7805 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007806 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007807 }
7808 }
7809 }
7810
7811 return 0;
7812}
7813
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007814Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7815 // If one of the common conversion will work ..
7816 if (Instruction *Result = commonIntCastTransforms(CI))
7817 return Result;
7818
7819 Value *Src = CI.getOperand(0);
7820
7821 // If this is a cast of a cast
7822 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7823 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7824 // types and if the sizes are just right we can convert this into a logical
7825 // 'and' which will be much cheaper than the pair of casts.
7826 if (isa<TruncInst>(CSrc)) {
7827 // Get the sizes of the types involved
7828 Value *A = CSrc->getOperand(0);
7829 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7830 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7831 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7832 // If we're actually extending zero bits and the trunc is a no-op
7833 if (MidSize < DstSize && SrcSize == DstSize) {
7834 // Replace both of the casts with an And of the type mask.
7835 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7836 Constant *AndConst = ConstantInt::get(AndValue);
7837 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007838 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007839 // Unfortunately, if the type changed, we need to cast it back.
7840 if (And->getType() != CI.getType()) {
7841 And->setName(CSrc->getName()+".mask");
7842 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007843 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007844 }
7845 return And;
7846 }
7847 }
7848 }
7849
Evan Chenge3779cf2008-03-24 00:21:34 +00007850 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7851 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007852
Evan Chenge3779cf2008-03-24 00:21:34 +00007853 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7854 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7855 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7856 // of the (zext icmp) will be transformed.
7857 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7858 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7859 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7860 (transformZExtICmp(LHS, CI, false) ||
7861 transformZExtICmp(RHS, CI, false))) {
7862 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7863 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007864 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007865 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007866 }
7867
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007868 return 0;
7869}
7870
7871Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7872 if (Instruction *I = commonIntCastTransforms(CI))
7873 return I;
7874
7875 Value *Src = CI.getOperand(0);
7876
7877 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7878 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7879 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7880 // If we are just checking for a icmp eq of a single bit and zext'ing it
7881 // to an integer, then shift the bit to the appropriate place and then
7882 // cast to integer to avoid the comparison.
7883 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7884 const APInt &Op1CV = Op1C->getValue();
7885
7886 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7887 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7888 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7889 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7890 Value *In = ICI->getOperand(0);
7891 Value *Sh = ConstantInt::get(In->getType(),
7892 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007893 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 In->getName()+".lobit"),
7895 CI);
7896 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007897 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007898 true/*SExt*/, "tmp", &CI);
7899
7900 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007901 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902 In->getName()+".not"), CI);
7903
7904 return ReplaceInstUsesWith(CI, In);
7905 }
7906 }
7907 }
7908
7909 return 0;
7910}
7911
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007912/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7913/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007914static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007915 APFloat F = CFP->getValueAPF();
7916 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007917 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007918 return 0;
7919}
7920
7921/// LookThroughFPExtensions - If this is an fp extension instruction, look
7922/// through it until we get the source value.
7923static Value *LookThroughFPExtensions(Value *V) {
7924 if (Instruction *I = dyn_cast<Instruction>(V))
7925 if (I->getOpcode() == Instruction::FPExt)
7926 return LookThroughFPExtensions(I->getOperand(0));
7927
7928 // If this value is a constant, return the constant in the smallest FP type
7929 // that can accurately represent it. This allows us to turn
7930 // (float)((double)X+2.0) into x+2.0f.
7931 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7932 if (CFP->getType() == Type::PPC_FP128Ty)
7933 return V; // No constant folding of this.
7934 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007935 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007936 return V;
7937 if (CFP->getType() == Type::DoubleTy)
7938 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007939 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007940 return V;
7941 // Don't try to shrink to various long double types.
7942 }
7943
7944 return V;
7945}
7946
7947Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7948 if (Instruction *I = commonCastTransforms(CI))
7949 return I;
7950
7951 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7952 // smaller than the destination type, we can eliminate the truncate by doing
7953 // the add as the smaller type. This applies to add/sub/mul/div as well as
7954 // many builtins (sqrt, etc).
7955 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7956 if (OpI && OpI->hasOneUse()) {
7957 switch (OpI->getOpcode()) {
7958 default: break;
7959 case Instruction::Add:
7960 case Instruction::Sub:
7961 case Instruction::Mul:
7962 case Instruction::FDiv:
7963 case Instruction::FRem:
7964 const Type *SrcTy = OpI->getType();
7965 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7966 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7967 if (LHSTrunc->getType() != SrcTy &&
7968 RHSTrunc->getType() != SrcTy) {
7969 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7970 // If the source types were both smaller than the destination type of
7971 // the cast, do this xform.
7972 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7973 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7974 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7975 CI.getType(), CI);
7976 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7977 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007978 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007979 }
7980 }
7981 break;
7982 }
7983 }
7984 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985}
7986
7987Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7988 return commonCastTransforms(CI);
7989}
7990
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007991Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7992 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7993 // mantissa to accurately represent all values of X. For example, do not
7994 // do this with i64->float->i64.
7995 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7996 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7997 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner9ce836b2008-05-19 21:17:23 +00007998 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007999 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8000
8001 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008002}
8003
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008004Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8005 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8006 // mantissa to accurately represent all values of X. For example, do not
8007 // do this with i64->float->i64.
8008 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8009 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8010 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner9ce836b2008-05-19 21:17:23 +00008011 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008012 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8013
8014 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008015}
8016
8017Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8018 return commonCastTransforms(CI);
8019}
8020
8021Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8022 return commonCastTransforms(CI);
8023}
8024
8025Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8026 return commonPointerCastTransforms(CI);
8027}
8028
Chris Lattner7c1626482008-01-08 07:23:51 +00008029Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8030 if (Instruction *I = commonCastTransforms(CI))
8031 return I;
8032
8033 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8034 if (!DestPointee->isSized()) return 0;
8035
8036 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8037 ConstantInt *Cst;
8038 Value *X;
8039 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8040 m_ConstantInt(Cst)))) {
8041 // If the source and destination operands have the same type, see if this
8042 // is a single-index GEP.
8043 if (X->getType() == CI.getType()) {
8044 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00008045 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008046
8047 // Convert the constant to intptr type.
8048 APInt Offset = Cst->getValue();
8049 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8050
8051 // If Offset is evenly divisible by Size, we can do this xform.
8052 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8053 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008054 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008055 }
8056 }
8057 // TODO: Could handle other cases, e.g. where add is indexing into field of
8058 // struct etc.
8059 } else if (CI.getOperand(0)->hasOneUse() &&
8060 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8061 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8062 // "inttoptr+GEP" instead of "add+intptr".
8063
8064 // Get the size of the pointee type.
8065 uint64_t Size = TD->getABITypeSize(DestPointee);
8066
8067 // Convert the constant to intptr type.
8068 APInt Offset = Cst->getValue();
8069 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8070
8071 // If Offset is evenly divisible by Size, we can do this xform.
8072 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8073 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8074
8075 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8076 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008077 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008078 }
8079 }
8080 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008081}
8082
8083Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8084 // If the operands are integer typed then apply the integer transforms,
8085 // otherwise just apply the common ones.
8086 Value *Src = CI.getOperand(0);
8087 const Type *SrcTy = Src->getType();
8088 const Type *DestTy = CI.getType();
8089
8090 if (SrcTy->isInteger() && DestTy->isInteger()) {
8091 if (Instruction *Result = commonIntCastTransforms(CI))
8092 return Result;
8093 } else if (isa<PointerType>(SrcTy)) {
8094 if (Instruction *I = commonPointerCastTransforms(CI))
8095 return I;
8096 } else {
8097 if (Instruction *Result = commonCastTransforms(CI))
8098 return Result;
8099 }
8100
8101
8102 // Get rid of casts from one type to the same type. These are useless and can
8103 // be replaced by the operand.
8104 if (DestTy == Src->getType())
8105 return ReplaceInstUsesWith(CI, Src);
8106
8107 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8108 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8109 const Type *DstElTy = DstPTy->getElementType();
8110 const Type *SrcElTy = SrcPTy->getElementType();
8111
Nate Begemandf5b3612008-03-31 00:22:16 +00008112 // If the address spaces don't match, don't eliminate the bitcast, which is
8113 // required for changing types.
8114 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8115 return 0;
8116
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008117 // If we are casting a malloc or alloca to a pointer to a type of the same
8118 // size, rewrite the allocation instruction to allocate the "right" type.
8119 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8120 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8121 return V;
8122
8123 // If the source and destination are pointers, and this cast is equivalent
8124 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8125 // This can enhance SROA and other transforms that want type-safe pointers.
8126 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8127 unsigned NumZeros = 0;
8128 while (SrcElTy != DstElTy &&
8129 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8130 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8131 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8132 ++NumZeros;
8133 }
8134
8135 // If we found a path from the src to dest, create the getelementptr now.
8136 if (SrcElTy == DstElTy) {
8137 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008138 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8139 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008140 }
8141 }
8142
8143 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8144 if (SVI->hasOneUse()) {
8145 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8146 // a bitconvert to a vector with the same # elts.
8147 if (isa<VectorType>(DestTy) &&
8148 cast<VectorType>(DestTy)->getNumElements() ==
8149 SVI->getType()->getNumElements()) {
8150 CastInst *Tmp;
8151 // If either of the operands is a cast from CI.getType(), then
8152 // evaluating the shuffle in the casted destination's type will allow
8153 // us to eliminate at least one cast.
8154 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8155 Tmp->getOperand(0)->getType() == DestTy) ||
8156 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8157 Tmp->getOperand(0)->getType() == DestTy)) {
8158 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8159 SVI->getOperand(0), DestTy, &CI);
8160 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8161 SVI->getOperand(1), DestTy, &CI);
8162 // Return a new shuffle vector. Use the same element ID's, as we
8163 // know the vector types match #elts.
8164 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8165 }
8166 }
8167 }
8168 }
8169 return 0;
8170}
8171
8172/// GetSelectFoldableOperands - We want to turn code that looks like this:
8173/// %C = or %A, %B
8174/// %D = select %cond, %C, %A
8175/// into:
8176/// %C = select %cond, %B, 0
8177/// %D = or %A, %C
8178///
8179/// Assuming that the specified instruction is an operand to the select, return
8180/// a bitmask indicating which operands of this instruction are foldable if they
8181/// equal the other incoming value of the select.
8182///
8183static unsigned GetSelectFoldableOperands(Instruction *I) {
8184 switch (I->getOpcode()) {
8185 case Instruction::Add:
8186 case Instruction::Mul:
8187 case Instruction::And:
8188 case Instruction::Or:
8189 case Instruction::Xor:
8190 return 3; // Can fold through either operand.
8191 case Instruction::Sub: // Can only fold on the amount subtracted.
8192 case Instruction::Shl: // Can only fold on the shift amount.
8193 case Instruction::LShr:
8194 case Instruction::AShr:
8195 return 1;
8196 default:
8197 return 0; // Cannot fold
8198 }
8199}
8200
8201/// GetSelectFoldableConstant - For the same transformation as the previous
8202/// function, return the identity constant that goes into the select.
8203static Constant *GetSelectFoldableConstant(Instruction *I) {
8204 switch (I->getOpcode()) {
8205 default: assert(0 && "This cannot happen!"); abort();
8206 case Instruction::Add:
8207 case Instruction::Sub:
8208 case Instruction::Or:
8209 case Instruction::Xor:
8210 case Instruction::Shl:
8211 case Instruction::LShr:
8212 case Instruction::AShr:
8213 return Constant::getNullValue(I->getType());
8214 case Instruction::And:
8215 return Constant::getAllOnesValue(I->getType());
8216 case Instruction::Mul:
8217 return ConstantInt::get(I->getType(), 1);
8218 }
8219}
8220
8221/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8222/// have the same opcode and only one use each. Try to simplify this.
8223Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8224 Instruction *FI) {
8225 if (TI->getNumOperands() == 1) {
8226 // If this is a non-volatile load or a cast from the same type,
8227 // merge.
8228 if (TI->isCast()) {
8229 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8230 return 0;
8231 } else {
8232 return 0; // unknown unary op.
8233 }
8234
8235 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008236 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8237 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008238 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008239 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008240 TI->getType());
8241 }
8242
8243 // Only handle binary operators here.
8244 if (!isa<BinaryOperator>(TI))
8245 return 0;
8246
8247 // Figure out if the operations have any operands in common.
8248 Value *MatchOp, *OtherOpT, *OtherOpF;
8249 bool MatchIsOpZero;
8250 if (TI->getOperand(0) == FI->getOperand(0)) {
8251 MatchOp = TI->getOperand(0);
8252 OtherOpT = TI->getOperand(1);
8253 OtherOpF = FI->getOperand(1);
8254 MatchIsOpZero = true;
8255 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8256 MatchOp = TI->getOperand(1);
8257 OtherOpT = TI->getOperand(0);
8258 OtherOpF = FI->getOperand(0);
8259 MatchIsOpZero = false;
8260 } else if (!TI->isCommutative()) {
8261 return 0;
8262 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8263 MatchOp = TI->getOperand(0);
8264 OtherOpT = TI->getOperand(1);
8265 OtherOpF = FI->getOperand(0);
8266 MatchIsOpZero = true;
8267 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8268 MatchOp = TI->getOperand(1);
8269 OtherOpT = TI->getOperand(0);
8270 OtherOpF = FI->getOperand(1);
8271 MatchIsOpZero = true;
8272 } else {
8273 return 0;
8274 }
8275
8276 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008277 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8278 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008279 InsertNewInstBefore(NewSI, SI);
8280
8281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8282 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008283 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008285 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008286 }
8287 assert(0 && "Shouldn't get here");
8288 return 0;
8289}
8290
8291Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8292 Value *CondVal = SI.getCondition();
8293 Value *TrueVal = SI.getTrueValue();
8294 Value *FalseVal = SI.getFalseValue();
8295
8296 // select true, X, Y -> X
8297 // select false, X, Y -> Y
8298 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8299 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8300
8301 // select C, X, X -> X
8302 if (TrueVal == FalseVal)
8303 return ReplaceInstUsesWith(SI, TrueVal);
8304
8305 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8306 return ReplaceInstUsesWith(SI, FalseVal);
8307 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8308 return ReplaceInstUsesWith(SI, TrueVal);
8309 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8310 if (isa<Constant>(TrueVal))
8311 return ReplaceInstUsesWith(SI, TrueVal);
8312 else
8313 return ReplaceInstUsesWith(SI, FalseVal);
8314 }
8315
8316 if (SI.getType() == Type::Int1Ty) {
8317 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8318 if (C->getZExtValue()) {
8319 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008320 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008321 } else {
8322 // Change: A = select B, false, C --> A = and !B, C
8323 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008326 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327 }
8328 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8329 if (C->getZExtValue() == false) {
8330 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008331 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008332 } else {
8333 // Change: A = select B, C, true --> A = or !B, C
8334 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008335 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008336 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008337 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008338 }
8339 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008340
8341 // select a, b, a -> a&b
8342 // select a, a, b -> a|b
8343 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008344 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008345 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008346 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008347 }
8348
8349 // Selecting between two integer constants?
8350 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8351 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8352 // select C, 1, 0 -> zext C to int
8353 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008354 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008355 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8356 // select C, 0, 1 -> zext !C to int
8357 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008358 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008359 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008360 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008361 }
8362
8363 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8364
8365 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8366
8367 // (x <s 0) ? -1 : 0 -> ashr x, 31
8368 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8369 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8370 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8371 // The comparison constant and the result are not neccessarily the
8372 // same width. Make an all-ones value by inserting a AShr.
8373 Value *X = IC->getOperand(0);
8374 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8375 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008376 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008377 ShAmt, "ones");
8378 InsertNewInstBefore(SRA, SI);
8379
8380 // Finally, convert to the type of the select RHS. We figure out
8381 // if this requires a SExt, Trunc or BitCast based on the sizes.
8382 Instruction::CastOps opc = Instruction::BitCast;
8383 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8384 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8385 if (SRASize < SISize)
8386 opc = Instruction::SExt;
8387 else if (SRASize > SISize)
8388 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008389 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008390 }
8391 }
8392
8393
8394 // If one of the constants is zero (we know they can't both be) and we
8395 // have an icmp instruction with zero, and we have an 'and' with the
8396 // non-constant value, eliminate this whole mess. This corresponds to
8397 // cases like this: ((X & 27) ? 27 : 0)
8398 if (TrueValC->isZero() || FalseValC->isZero())
8399 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8400 cast<Constant>(IC->getOperand(1))->isNullValue())
8401 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8402 if (ICA->getOpcode() == Instruction::And &&
8403 isa<ConstantInt>(ICA->getOperand(1)) &&
8404 (ICA->getOperand(1) == TrueValC ||
8405 ICA->getOperand(1) == FalseValC) &&
8406 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8407 // Okay, now we know that everything is set up, we just don't
8408 // know whether we have a icmp_ne or icmp_eq and whether the
8409 // true or false val is the zero.
8410 bool ShouldNotVal = !TrueValC->isZero();
8411 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8412 Value *V = ICA;
8413 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008414 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008415 Instruction::Xor, V, ICA->getOperand(1)), SI);
8416 return ReplaceInstUsesWith(SI, V);
8417 }
8418 }
8419 }
8420
8421 // See if we are selecting two values based on a comparison of the two values.
8422 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8423 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8424 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008425 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8426 // This is not safe in general for floating point:
8427 // consider X== -0, Y== +0.
8428 // It becomes safe if either operand is a nonzero constant.
8429 ConstantFP *CFPt, *CFPf;
8430 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8431 !CFPt->getValueAPF().isZero()) ||
8432 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8433 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008434 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008436 // Transform (X != Y) ? X : Y -> X
8437 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8438 return ReplaceInstUsesWith(SI, TrueVal);
8439 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8440
8441 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8442 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008443 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8444 // This is not safe in general for floating point:
8445 // consider X== -0, Y== +0.
8446 // It becomes safe if either operand is a nonzero constant.
8447 ConstantFP *CFPt, *CFPf;
8448 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8449 !CFPt->getValueAPF().isZero()) ||
8450 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8451 !CFPf->getValueAPF().isZero()))
8452 return ReplaceInstUsesWith(SI, FalseVal);
8453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008454 // Transform (X != Y) ? Y : X -> Y
8455 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8456 return ReplaceInstUsesWith(SI, TrueVal);
8457 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8458 }
8459 }
8460
8461 // See if we are selecting two values based on a comparison of the two values.
8462 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8463 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8464 // Transform (X == Y) ? X : Y -> Y
8465 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8466 return ReplaceInstUsesWith(SI, FalseVal);
8467 // Transform (X != Y) ? X : Y -> X
8468 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8469 return ReplaceInstUsesWith(SI, TrueVal);
8470 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8471
8472 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8473 // Transform (X == Y) ? Y : X -> X
8474 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8475 return ReplaceInstUsesWith(SI, FalseVal);
8476 // Transform (X != Y) ? Y : X -> Y
8477 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8478 return ReplaceInstUsesWith(SI, TrueVal);
8479 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8480 }
8481 }
8482
8483 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8484 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8485 if (TI->hasOneUse() && FI->hasOneUse()) {
8486 Instruction *AddOp = 0, *SubOp = 0;
8487
8488 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8489 if (TI->getOpcode() == FI->getOpcode())
8490 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8491 return IV;
8492
8493 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8494 // even legal for FP.
8495 if (TI->getOpcode() == Instruction::Sub &&
8496 FI->getOpcode() == Instruction::Add) {
8497 AddOp = FI; SubOp = TI;
8498 } else if (FI->getOpcode() == Instruction::Sub &&
8499 TI->getOpcode() == Instruction::Add) {
8500 AddOp = TI; SubOp = FI;
8501 }
8502
8503 if (AddOp) {
8504 Value *OtherAddOp = 0;
8505 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8506 OtherAddOp = AddOp->getOperand(1);
8507 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8508 OtherAddOp = AddOp->getOperand(0);
8509 }
8510
8511 if (OtherAddOp) {
8512 // So at this point we know we have (Y -> OtherAddOp):
8513 // select C, (add X, Y), (sub X, Z)
8514 Value *NegVal; // Compute -Z
8515 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8516 NegVal = ConstantExpr::getNeg(C);
8517 } else {
8518 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008519 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008520 }
8521
8522 Value *NewTrueOp = OtherAddOp;
8523 Value *NewFalseOp = NegVal;
8524 if (AddOp != TI)
8525 std::swap(NewTrueOp, NewFalseOp);
8526 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008527 SelectInst::Create(CondVal, NewTrueOp,
8528 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008529
8530 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008531 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008532 }
8533 }
8534 }
8535
8536 // See if we can fold the select into one of our operands.
8537 if (SI.getType()->isInteger()) {
8538 // See the comment above GetSelectFoldableOperands for a description of the
8539 // transformation we are doing here.
8540 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8541 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8542 !isa<Constant>(FalseVal))
8543 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8544 unsigned OpToFold = 0;
8545 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8546 OpToFold = 1;
8547 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8548 OpToFold = 2;
8549 }
8550
8551 if (OpToFold) {
8552 Constant *C = GetSelectFoldableConstant(TVI);
8553 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008554 SelectInst::Create(SI.getCondition(),
8555 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008556 InsertNewInstBefore(NewSel, SI);
8557 NewSel->takeName(TVI);
8558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008559 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008560 else {
8561 assert(0 && "Unknown instruction!!");
8562 }
8563 }
8564 }
8565
8566 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8567 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8568 !isa<Constant>(TrueVal))
8569 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8570 unsigned OpToFold = 0;
8571 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8572 OpToFold = 1;
8573 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8574 OpToFold = 2;
8575 }
8576
8577 if (OpToFold) {
8578 Constant *C = GetSelectFoldableConstant(FVI);
8579 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008580 SelectInst::Create(SI.getCondition(), C,
8581 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008582 InsertNewInstBefore(NewSel, SI);
8583 NewSel->takeName(FVI);
8584 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008585 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008586 else
8587 assert(0 && "Unknown instruction!!");
8588 }
8589 }
8590 }
8591
8592 if (BinaryOperator::isNot(CondVal)) {
8593 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8594 SI.setOperand(1, FalseVal);
8595 SI.setOperand(2, TrueVal);
8596 return &SI;
8597 }
8598
8599 return 0;
8600}
8601
Dan Gohman2d648bb2008-04-10 18:43:06 +00008602/// EnforceKnownAlignment - If the specified pointer points to an object that
8603/// we control, modify the object's alignment to PrefAlign. This isn't
8604/// often possible though. If alignment is important, a more reliable approach
8605/// is to simply align all global variables and allocation instructions to
8606/// their preferred alignment from the beginning.
8607///
8608static unsigned EnforceKnownAlignment(Value *V,
8609 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008610
Dan Gohman2d648bb2008-04-10 18:43:06 +00008611 User *U = dyn_cast<User>(V);
8612 if (!U) return Align;
8613
8614 switch (getOpcode(U)) {
8615 default: break;
8616 case Instruction::BitCast:
8617 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8618 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008619 // If all indexes are zero, it is just the alignment of the base pointer.
8620 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008621 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8622 if (!isa<Constant>(U->getOperand(i)) ||
8623 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008624 AllZeroOperands = false;
8625 break;
8626 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008627
8628 if (AllZeroOperands) {
8629 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008630 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008631 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008632 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008633 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008634 }
8635
8636 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8637 // If there is a large requested alignment and we can, bump up the alignment
8638 // of the global.
8639 if (!GV->isDeclaration()) {
8640 GV->setAlignment(PrefAlign);
8641 Align = PrefAlign;
8642 }
8643 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8644 // If there is a requested alignment and if this is an alloca, round up. We
8645 // don't do this for malloc, because some systems can't respect the request.
8646 if (isa<AllocaInst>(AI)) {
8647 AI->setAlignment(PrefAlign);
8648 Align = PrefAlign;
8649 }
8650 }
8651
8652 return Align;
8653}
8654
8655/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8656/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8657/// and it is more than the alignment of the ultimate object, see if we can
8658/// increase the alignment of the ultimate object, making this check succeed.
8659unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8660 unsigned PrefAlign) {
8661 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8662 sizeof(PrefAlign) * CHAR_BIT;
8663 APInt Mask = APInt::getAllOnesValue(BitWidth);
8664 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8665 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8666 unsigned TrailZ = KnownZero.countTrailingOnes();
8667 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8668
8669 if (PrefAlign > Align)
8670 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8671
8672 // We don't need to make any adjustment.
8673 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008674}
8675
Chris Lattner00ae5132008-01-13 23:50:23 +00008676Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008677 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8678 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008679 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8680 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8681
8682 if (CopyAlign < MinAlign) {
8683 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8684 return MI;
8685 }
8686
8687 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8688 // load/store.
8689 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8690 if (MemOpLength == 0) return 0;
8691
Chris Lattnerc669fb62008-01-14 00:28:35 +00008692 // Source and destination pointer types are always "i8*" for intrinsic. See
8693 // if the size is something we can handle with a single primitive load/store.
8694 // A single load+store correctly handles overlapping memory in the memmove
8695 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008696 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008697 if (Size == 0) return MI; // Delete this mem transfer.
8698
8699 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008700 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008701
Chris Lattnerc669fb62008-01-14 00:28:35 +00008702 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008703 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008704
8705 // Memcpy forces the use of i8* for the source and destination. That means
8706 // that if you're using memcpy to move one double around, you'll get a cast
8707 // from double* to i8*. We'd much rather use a double load+store rather than
8708 // an i64 load+store, here because this improves the odds that the source or
8709 // dest address will be promotable. See if we can find a better type than the
8710 // integer datatype.
8711 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8712 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8713 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8714 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8715 // down through these levels if so.
8716 while (!SrcETy->isFirstClassType()) {
8717 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8718 if (STy->getNumElements() == 1)
8719 SrcETy = STy->getElementType(0);
8720 else
8721 break;
8722 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8723 if (ATy->getNumElements() == 1)
8724 SrcETy = ATy->getElementType();
8725 else
8726 break;
8727 } else
8728 break;
8729 }
8730
8731 if (SrcETy->isFirstClassType())
8732 NewPtrTy = PointerType::getUnqual(SrcETy);
8733 }
8734 }
8735
8736
Chris Lattner00ae5132008-01-13 23:50:23 +00008737 // If the memcpy/memmove provides better alignment info than we can
8738 // infer, use it.
8739 SrcAlign = std::max(SrcAlign, CopyAlign);
8740 DstAlign = std::max(DstAlign, CopyAlign);
8741
8742 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8743 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008744 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8745 InsertNewInstBefore(L, *MI);
8746 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8747
8748 // Set the size of the copy to 0, it will be deleted on the next iteration.
8749 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8750 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008751}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008752
Chris Lattner5af8a912008-04-30 06:39:11 +00008753Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8754 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8755 if (MI->getAlignment()->getZExtValue() < Alignment) {
8756 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8757 return MI;
8758 }
8759
8760 // Extract the length and alignment and fill if they are constant.
8761 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8762 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8763 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8764 return 0;
8765 uint64_t Len = LenC->getZExtValue();
8766 Alignment = MI->getAlignment()->getZExtValue();
8767
8768 // If the length is zero, this is a no-op
8769 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8770
8771 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8772 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8773 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8774
8775 Value *Dest = MI->getDest();
8776 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8777
8778 // Alignment 0 is identity for alignment 1 for memset, but not store.
8779 if (Alignment == 0) Alignment = 1;
8780
8781 // Extract the fill value and store.
8782 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8783 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8784 Alignment), *MI);
8785
8786 // Set the size of the copy to 0, it will be deleted on the next iteration.
8787 MI->setLength(Constant::getNullValue(LenC->getType()));
8788 return MI;
8789 }
8790
8791 return 0;
8792}
8793
8794
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008795/// visitCallInst - CallInst simplification. This mostly only handles folding
8796/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8797/// the heavy lifting.
8798///
8799Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8800 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8801 if (!II) return visitCallSite(&CI);
8802
8803 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8804 // visitCallSite.
8805 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8806 bool Changed = false;
8807
8808 // memmove/cpy/set of zero bytes is a noop.
8809 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8810 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8811
8812 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8813 if (CI->getZExtValue() == 1) {
8814 // Replace the instruction with just byte operations. We would
8815 // transform other cases to loads/stores, but we don't know if
8816 // alignment is sufficient.
8817 }
8818 }
8819
8820 // If we have a memmove and the source operation is a constant global,
8821 // then the source and dest pointers can't alias, so we can change this
8822 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008823 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008824 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8825 if (GVSrc->isConstant()) {
8826 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008827 Intrinsic::ID MemCpyID;
8828 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8829 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008830 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008831 MemCpyID = Intrinsic::memcpy_i64;
8832 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008833 Changed = true;
8834 }
8835 }
8836
8837 // If we can determine a pointer alignment that is bigger than currently
8838 // set, update the alignment.
8839 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008840 if (Instruction *I = SimplifyMemTransfer(MI))
8841 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008842 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8843 if (Instruction *I = SimplifyMemSet(MSI))
8844 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008845 }
8846
8847 if (Changed) return II;
8848 } else {
8849 switch (II->getIntrinsicID()) {
8850 default: break;
8851 case Intrinsic::ppc_altivec_lvx:
8852 case Intrinsic::ppc_altivec_lvxl:
8853 case Intrinsic::x86_sse_loadu_ps:
8854 case Intrinsic::x86_sse2_loadu_pd:
8855 case Intrinsic::x86_sse2_loadu_dq:
8856 // Turn PPC lvx -> load if the pointer is known aligned.
8857 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008858 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008859 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8860 PointerType::getUnqual(II->getType()),
8861 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008862 return new LoadInst(Ptr);
8863 }
8864 break;
8865 case Intrinsic::ppc_altivec_stvx:
8866 case Intrinsic::ppc_altivec_stvxl:
8867 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008868 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008869 const Type *OpPtrTy =
8870 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008871 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008872 return new StoreInst(II->getOperand(1), Ptr);
8873 }
8874 break;
8875 case Intrinsic::x86_sse_storeu_ps:
8876 case Intrinsic::x86_sse2_storeu_pd:
8877 case Intrinsic::x86_sse2_storeu_dq:
8878 case Intrinsic::x86_sse2_storel_dq:
8879 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008880 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008881 const Type *OpPtrTy =
8882 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008883 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008884 return new StoreInst(II->getOperand(2), Ptr);
8885 }
8886 break;
8887
8888 case Intrinsic::x86_sse_cvttss2si: {
8889 // These intrinsics only demands the 0th element of its input vector. If
8890 // we can simplify the input based on that, do so now.
8891 uint64_t UndefElts;
8892 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8893 UndefElts)) {
8894 II->setOperand(1, V);
8895 return II;
8896 }
8897 break;
8898 }
8899
8900 case Intrinsic::ppc_altivec_vperm:
8901 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8902 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8903 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8904
8905 // Check that all of the elements are integer constants or undefs.
8906 bool AllEltsOk = true;
8907 for (unsigned i = 0; i != 16; ++i) {
8908 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8909 !isa<UndefValue>(Mask->getOperand(i))) {
8910 AllEltsOk = false;
8911 break;
8912 }
8913 }
8914
8915 if (AllEltsOk) {
8916 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008917 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8918 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008919 Value *Result = UndefValue::get(Op0->getType());
8920
8921 // Only extract each element once.
8922 Value *ExtractedElts[32];
8923 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8924
8925 for (unsigned i = 0; i != 16; ++i) {
8926 if (isa<UndefValue>(Mask->getOperand(i)))
8927 continue;
8928 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8929 Idx &= 31; // Match the hardware behavior.
8930
8931 if (ExtractedElts[Idx] == 0) {
8932 Instruction *Elt =
8933 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8934 InsertNewInstBefore(Elt, CI);
8935 ExtractedElts[Idx] = Elt;
8936 }
8937
8938 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008939 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8940 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008941 InsertNewInstBefore(cast<Instruction>(Result), CI);
8942 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008943 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008944 }
8945 }
8946 break;
8947
8948 case Intrinsic::stackrestore: {
8949 // If the save is right next to the restore, remove the restore. This can
8950 // happen when variable allocas are DCE'd.
8951 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8952 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8953 BasicBlock::iterator BI = SS;
8954 if (&*++BI == II)
8955 return EraseInstFromFunction(CI);
8956 }
8957 }
8958
Chris Lattner416d91c2008-02-18 06:12:38 +00008959 // Scan down this block to see if there is another stack restore in the
8960 // same block without an intervening call/alloca.
8961 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008962 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008963 bool CannotRemove = false;
8964 for (++BI; &*BI != TI; ++BI) {
8965 if (isa<AllocaInst>(BI)) {
8966 CannotRemove = true;
8967 break;
8968 }
8969 if (isa<CallInst>(BI)) {
8970 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008971 CannotRemove = true;
8972 break;
8973 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008974 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008975 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008976 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008977 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008978
8979 // If the stack restore is in a return/unwind block and if there are no
8980 // allocas or calls between the restore and the return, nuke the restore.
8981 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8982 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008983 break;
8984 }
8985 }
8986 }
8987
8988 return visitCallSite(II);
8989}
8990
8991// InvokeInst simplification
8992//
8993Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8994 return visitCallSite(&II);
8995}
8996
Dale Johannesen96021832008-04-25 21:16:07 +00008997/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8998/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008999static bool isSafeToEliminateVarargsCast(const CallSite CS,
9000 const CastInst * const CI,
9001 const TargetData * const TD,
9002 const int ix) {
9003 if (!CI->isLosslessCast())
9004 return false;
9005
9006 // The size of ByVal arguments is derived from the type, so we
9007 // can't change to a type with a different size. If the size were
9008 // passed explicitly we could avoid this check.
9009 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9010 return true;
9011
9012 const Type* SrcTy =
9013 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9014 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9015 if (!SrcTy->isSized() || !DstTy->isSized())
9016 return false;
9017 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9018 return false;
9019 return true;
9020}
9021
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009022// visitCallSite - Improvements for call and invoke instructions.
9023//
9024Instruction *InstCombiner::visitCallSite(CallSite CS) {
9025 bool Changed = false;
9026
9027 // If the callee is a constexpr cast of a function, attempt to move the cast
9028 // to the arguments of the call/invoke.
9029 if (transformConstExprCastCall(CS)) return 0;
9030
9031 Value *Callee = CS.getCalledValue();
9032
9033 if (Function *CalleeF = dyn_cast<Function>(Callee))
9034 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9035 Instruction *OldCall = CS.getInstruction();
9036 // If the call and callee calling conventions don't match, this call must
9037 // be unreachable, as the call is undefined.
9038 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009039 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9040 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009041 if (!OldCall->use_empty())
9042 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9043 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9044 return EraseInstFromFunction(*OldCall);
9045 return 0;
9046 }
9047
9048 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9049 // This instruction is not reachable, just remove it. We insert a store to
9050 // undef so that we know that this code is not reachable, despite the fact
9051 // that we can't modify the CFG here.
9052 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009053 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009054 CS.getInstruction());
9055
9056 if (!CS.getInstruction()->use_empty())
9057 CS.getInstruction()->
9058 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9059
9060 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9061 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009062 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9063 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009064 }
9065 return EraseInstFromFunction(*CS.getInstruction());
9066 }
9067
Duncan Sands74833f22007-09-17 10:26:40 +00009068 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9069 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9070 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9071 return transformCallThroughTrampoline(CS);
9072
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009073 const PointerType *PTy = cast<PointerType>(Callee->getType());
9074 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9075 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009076 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009077 // See if we can optimize any arguments passed through the varargs area of
9078 // the call.
9079 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009080 E = CS.arg_end(); I != E; ++I, ++ix) {
9081 CastInst *CI = dyn_cast<CastInst>(*I);
9082 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9083 *I = CI->getOperand(0);
9084 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009085 }
Dale Johannesen35615462008-04-23 18:34:37 +00009086 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009087 }
9088
Duncan Sands2937e352007-12-19 21:13:37 +00009089 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009090 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009091 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009092 Changed = true;
9093 }
9094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009095 return Changed ? CS.getInstruction() : 0;
9096}
9097
9098// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9099// attempt to move the cast to the arguments of the call/invoke.
9100//
9101bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9102 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9103 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9104 if (CE->getOpcode() != Instruction::BitCast ||
9105 !isa<Function>(CE->getOperand(0)))
9106 return false;
9107 Function *Callee = cast<Function>(CE->getOperand(0));
9108 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009109 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009110
9111 // Okay, this is a cast from a function to a different type. Unless doing so
9112 // would cause a type conversion of one of our arguments, change this call to
9113 // be a direct call with arguments casted to the appropriate types.
9114 //
9115 const FunctionType *FT = Callee->getFunctionType();
9116 const Type *OldRetTy = Caller->getType();
9117
Devang Pateld091d322008-03-11 18:04:06 +00009118 if (isa<StructType>(FT->getReturnType()))
9119 return false; // TODO: Handle multiple return values.
9120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121 // Check to see if we are changing the return type...
9122 if (OldRetTy != FT->getReturnType()) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009123 if (Callee->isDeclaration() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009124 // Conversion is ok if changing from pointer to int of same size.
9125 !(isa<PointerType>(FT->getReturnType()) &&
9126 TD->getIntPtrType() == OldRetTy))
9127 return false; // Cannot transform this return value.
9128
Duncan Sands5c489582008-01-06 10:12:28 +00009129 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009130 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00009131 FT->getReturnType() != Type::VoidTy &&
9132 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009133 return false; // Cannot transform this return value.
9134
Chris Lattner1c8733e2008-03-12 17:45:29 +00009135 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9136 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009137 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9138 return false; // Attribute not compatible with transformed value.
9139 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009141 // If the callsite is an invoke instruction, and the return value is used by
9142 // a PHI node in a successor, we cannot change the return type of the call
9143 // because there is no place to put the cast instruction (without breaking
9144 // the critical edge). Bail out in this case.
9145 if (!Caller->use_empty())
9146 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9147 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9148 UI != E; ++UI)
9149 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9150 if (PN->getParent() == II->getNormalDest() ||
9151 PN->getParent() == II->getUnwindDest())
9152 return false;
9153 }
9154
9155 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9156 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9157
9158 CallSite::arg_iterator AI = CS.arg_begin();
9159 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9160 const Type *ParamTy = FT->getParamType(i);
9161 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009162
9163 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009164 return false; // Cannot transform this parameter value.
9165
Chris Lattner1c8733e2008-03-12 17:45:29 +00009166 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9167 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009169 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00009170 // Some conversions are safe even if we do not have a body.
9171 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009172 bool isConvertible = ActTy == ParamTy ||
9173 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9174 (ParamTy->isInteger() && ActTy->isInteger() &&
9175 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9176 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9177 && c->getValue().isStrictlyPositive());
9178 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009179 }
9180
9181 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9182 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009183 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009184
Chris Lattner1c8733e2008-03-12 17:45:29 +00009185 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9186 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009187 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009188 // won't be dropping them. Check that these extra arguments have attributes
9189 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009190 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9191 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009192 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009193 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009194 if (PAttrs & ParamAttr::VarArgsIncompatible)
9195 return false;
9196 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009197
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009198 // Okay, we decided that this is a safe thing to do: go ahead and start
9199 // inserting cast instructions as necessary...
9200 std::vector<Value*> Args;
9201 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009202 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009203 attrVec.reserve(NumCommonArgs);
9204
9205 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009206 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009207
9208 // If the return value is not being used, the type may not be compatible
9209 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009210 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00009211
9212 // Add the new return attributes.
9213 if (RAttrs)
9214 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009215
9216 AI = CS.arg_begin();
9217 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9218 const Type *ParamTy = FT->getParamType(i);
9219 if ((*AI)->getType() == ParamTy) {
9220 Args.push_back(*AI);
9221 } else {
9222 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9223 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009224 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009225 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9226 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009227
9228 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009229 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009230 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009231 }
9232
9233 // If the function takes more arguments than the call was taking, add them
9234 // now...
9235 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9236 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9237
9238 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009239 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009240 if (!FT->isVarArg()) {
9241 cerr << "WARNING: While resolving call to function '"
9242 << Callee->getName() << "' arguments were dropped!\n";
9243 } else {
9244 // Add all of the arguments in their promoted form to the arg list...
9245 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9246 const Type *PTy = getPromotedType((*AI)->getType());
9247 if (PTy != (*AI)->getType()) {
9248 // Must promote to pass through va_arg area!
9249 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9250 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009251 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009252 InsertNewInstBefore(Cast, *Caller);
9253 Args.push_back(Cast);
9254 } else {
9255 Args.push_back(*AI);
9256 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009257
Duncan Sands4ced1f82008-01-13 08:02:44 +00009258 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009259 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009260 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009262 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009263 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009264
9265 if (FT->getReturnType() == Type::VoidTy)
9266 Caller->setName(""); // Void type should not have a name.
9267
Chris Lattner1c8733e2008-03-12 17:45:29 +00009268 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009270 Instruction *NC;
9271 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009272 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009273 Args.begin(), Args.end(),
9274 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009275 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009276 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009277 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009278 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9279 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009280 CallInst *CI = cast<CallInst>(Caller);
9281 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009282 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009283 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009284 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009285 }
9286
9287 // Insert a cast of the return type as necessary.
9288 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009289 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009290 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009291 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009292 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009293 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294
9295 // If this is an invoke instruction, we should insert it after the first
9296 // non-phi, instruction in the normal successor block.
9297 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9298 BasicBlock::iterator I = II->getNormalDest()->begin();
9299 while (isa<PHINode>(I)) ++I;
9300 InsertNewInstBefore(NC, *I);
9301 } else {
9302 // Otherwise, it's a call, just insert cast right after the call instr
9303 InsertNewInstBefore(NC, *Caller);
9304 }
9305 AddUsersToWorkList(*Caller);
9306 } else {
9307 NV = UndefValue::get(Caller->getType());
9308 }
9309 }
9310
9311 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9312 Caller->replaceAllUsesWith(NV);
9313 Caller->eraseFromParent();
9314 RemoveFromWorkList(Caller);
9315 return true;
9316}
9317
Duncan Sands74833f22007-09-17 10:26:40 +00009318// transformCallThroughTrampoline - Turn a call to a function created by the
9319// init_trampoline intrinsic into a direct call to the underlying function.
9320//
9321Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9322 Value *Callee = CS.getCalledValue();
9323 const PointerType *PTy = cast<PointerType>(Callee->getType());
9324 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009325 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009326
9327 // If the call already has the 'nest' attribute somewhere then give up -
9328 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009329 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009330 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009331
9332 IntrinsicInst *Tramp =
9333 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9334
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009335 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009336 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9337 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9338
Chris Lattner1c8733e2008-03-12 17:45:29 +00009339 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9340 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009341 unsigned NestIdx = 1;
9342 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009343 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009344
9345 // Look for a parameter marked with the 'nest' attribute.
9346 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9347 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009348 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009349 // Record the parameter type and any other attributes.
9350 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009351 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009352 break;
9353 }
9354
9355 if (NestTy) {
9356 Instruction *Caller = CS.getInstruction();
9357 std::vector<Value*> NewArgs;
9358 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9359
Chris Lattner1c8733e2008-03-12 17:45:29 +00009360 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9361 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009362
Duncan Sands74833f22007-09-17 10:26:40 +00009363 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009364 // mean appending it. Likewise for attributes.
9365
9366 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009367 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9368 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009369
Duncan Sands74833f22007-09-17 10:26:40 +00009370 {
9371 unsigned Idx = 1;
9372 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9373 do {
9374 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009375 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009376 Value *NestVal = Tramp->getOperand(3);
9377 if (NestVal->getType() != NestTy)
9378 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9379 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009380 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009381 }
9382
9383 if (I == E)
9384 break;
9385
Duncan Sands48b81112008-01-14 19:52:09 +00009386 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009387 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009388 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009389 NewAttrs.push_back
9390 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009391
9392 ++Idx, ++I;
9393 } while (1);
9394 }
9395
9396 // The trampoline may have been bitcast to a bogus type (FTy).
9397 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009398 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009399
Duncan Sands74833f22007-09-17 10:26:40 +00009400 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009401 NewTypes.reserve(FTy->getNumParams()+1);
9402
Duncan Sands74833f22007-09-17 10:26:40 +00009403 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009404 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009405 {
9406 unsigned Idx = 1;
9407 FunctionType::param_iterator I = FTy->param_begin(),
9408 E = FTy->param_end();
9409
9410 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009411 if (Idx == NestIdx)
9412 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009413 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009414
9415 if (I == E)
9416 break;
9417
Duncan Sands48b81112008-01-14 19:52:09 +00009418 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009419 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009420
9421 ++Idx, ++I;
9422 } while (1);
9423 }
9424
9425 // Replace the trampoline call with a direct call. Let the generic
9426 // code sort out any function type mismatches.
9427 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009428 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009429 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9430 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009431 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009432
9433 Instruction *NewCaller;
9434 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009435 NewCaller = InvokeInst::Create(NewCallee,
9436 II->getNormalDest(), II->getUnwindDest(),
9437 NewArgs.begin(), NewArgs.end(),
9438 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009439 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009440 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009441 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009442 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9443 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009444 if (cast<CallInst>(Caller)->isTailCall())
9445 cast<CallInst>(NewCaller)->setTailCall();
9446 cast<CallInst>(NewCaller)->
9447 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009448 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009449 }
9450 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9451 Caller->replaceAllUsesWith(NewCaller);
9452 Caller->eraseFromParent();
9453 RemoveFromWorkList(Caller);
9454 return 0;
9455 }
9456 }
9457
9458 // Replace the trampoline call with a direct call. Since there is no 'nest'
9459 // parameter, there is no need to adjust the argument list. Let the generic
9460 // code sort out any function type mismatches.
9461 Constant *NewCallee =
9462 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9463 CS.setCalledFunction(NewCallee);
9464 return CS.getInstruction();
9465}
9466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009467/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9468/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9469/// and a single binop.
9470Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9471 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9472 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9473 isa<CmpInst>(FirstInst));
9474 unsigned Opc = FirstInst->getOpcode();
9475 Value *LHSVal = FirstInst->getOperand(0);
9476 Value *RHSVal = FirstInst->getOperand(1);
9477
9478 const Type *LHSType = LHSVal->getType();
9479 const Type *RHSType = RHSVal->getType();
9480
9481 // Scan to see if all operands are the same opcode, all have one use, and all
9482 // kill their operands (i.e. the operands have one use).
9483 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9484 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9485 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9486 // Verify type of the LHS matches so we don't fold cmp's of different
9487 // types or GEP's with different index types.
9488 I->getOperand(0)->getType() != LHSType ||
9489 I->getOperand(1)->getType() != RHSType)
9490 return 0;
9491
9492 // If they are CmpInst instructions, check their predicates
9493 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9494 if (cast<CmpInst>(I)->getPredicate() !=
9495 cast<CmpInst>(FirstInst)->getPredicate())
9496 return 0;
9497
9498 // Keep track of which operand needs a phi node.
9499 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9500 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9501 }
9502
9503 // Otherwise, this is safe to transform, determine if it is profitable.
9504
9505 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9506 // Indexes are often folded into load/store instructions, so we don't want to
9507 // hide them behind a phi.
9508 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9509 return 0;
9510
9511 Value *InLHS = FirstInst->getOperand(0);
9512 Value *InRHS = FirstInst->getOperand(1);
9513 PHINode *NewLHS = 0, *NewRHS = 0;
9514 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009515 NewLHS = PHINode::Create(LHSType,
9516 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009517 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9518 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9519 InsertNewInstBefore(NewLHS, PN);
9520 LHSVal = NewLHS;
9521 }
9522
9523 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009524 NewRHS = PHINode::Create(RHSType,
9525 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9527 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9528 InsertNewInstBefore(NewRHS, PN);
9529 RHSVal = NewRHS;
9530 }
9531
9532 // Add all operands to the new PHIs.
9533 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9534 if (NewLHS) {
9535 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9536 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9537 }
9538 if (NewRHS) {
9539 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9540 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9541 }
9542 }
9543
9544 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009545 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009547 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 RHSVal);
9549 else {
9550 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009551 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009552 }
9553}
9554
9555/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9556/// of the block that defines it. This means that it must be obvious the value
9557/// of the load is not changed from the point of the load to the end of the
9558/// block it is in.
9559///
9560/// Finally, it is safe, but not profitable, to sink a load targetting a
9561/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9562/// to a register.
9563static bool isSafeToSinkLoad(LoadInst *L) {
9564 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9565
9566 for (++BBI; BBI != E; ++BBI)
9567 if (BBI->mayWriteToMemory())
9568 return false;
9569
9570 // Check for non-address taken alloca. If not address-taken already, it isn't
9571 // profitable to do this xform.
9572 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9573 bool isAddressTaken = false;
9574 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9575 UI != E; ++UI) {
9576 if (isa<LoadInst>(UI)) continue;
9577 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9578 // If storing TO the alloca, then the address isn't taken.
9579 if (SI->getOperand(1) == AI) continue;
9580 }
9581 isAddressTaken = true;
9582 break;
9583 }
9584
9585 if (!isAddressTaken)
9586 return false;
9587 }
9588
9589 return true;
9590}
9591
9592
9593// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9594// operator and they all are only used by the PHI, PHI together their
9595// inputs, and do the operation once, to the result of the PHI.
9596Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9597 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9598
9599 // Scan the instruction, looking for input operations that can be folded away.
9600 // If all input operands to the phi are the same instruction (e.g. a cast from
9601 // the same type or "+42") we can pull the operation through the PHI, reducing
9602 // code size and simplifying code.
9603 Constant *ConstantOp = 0;
9604 const Type *CastSrcTy = 0;
9605 bool isVolatile = false;
9606 if (isa<CastInst>(FirstInst)) {
9607 CastSrcTy = FirstInst->getOperand(0)->getType();
9608 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9609 // Can fold binop, compare or shift here if the RHS is a constant,
9610 // otherwise call FoldPHIArgBinOpIntoPHI.
9611 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9612 if (ConstantOp == 0)
9613 return FoldPHIArgBinOpIntoPHI(PN);
9614 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9615 isVolatile = LI->isVolatile();
9616 // We can't sink the load if the loaded value could be modified between the
9617 // load and the PHI.
9618 if (LI->getParent() != PN.getIncomingBlock(0) ||
9619 !isSafeToSinkLoad(LI))
9620 return 0;
9621 } else if (isa<GetElementPtrInst>(FirstInst)) {
9622 if (FirstInst->getNumOperands() == 2)
9623 return FoldPHIArgBinOpIntoPHI(PN);
9624 // Can't handle general GEPs yet.
9625 return 0;
9626 } else {
9627 return 0; // Cannot fold this operation.
9628 }
9629
9630 // Check to see if all arguments are the same operation.
9631 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9632 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9633 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9634 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9635 return 0;
9636 if (CastSrcTy) {
9637 if (I->getOperand(0)->getType() != CastSrcTy)
9638 return 0; // Cast operation must match.
9639 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9640 // We can't sink the load if the loaded value could be modified between
9641 // the load and the PHI.
9642 if (LI->isVolatile() != isVolatile ||
9643 LI->getParent() != PN.getIncomingBlock(i) ||
9644 !isSafeToSinkLoad(LI))
9645 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009646
9647 // If the PHI is volatile and its block has multiple successors, sinking
9648 // it would remove a load of the volatile value from the path through the
9649 // other successor.
9650 if (isVolatile &&
9651 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9652 return 0;
9653
9654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009655 } else if (I->getOperand(1) != ConstantOp) {
9656 return 0;
9657 }
9658 }
9659
9660 // Okay, they are all the same operation. Create a new PHI node of the
9661 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009662 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9663 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009664 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9665
9666 Value *InVal = FirstInst->getOperand(0);
9667 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9668
9669 // Add all operands to the new PHI.
9670 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9671 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9672 if (NewInVal != InVal)
9673 InVal = 0;
9674 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9675 }
9676
9677 Value *PhiVal;
9678 if (InVal) {
9679 // The new PHI unions all of the same values together. This is really
9680 // common, so we handle it intelligently here for compile-time speed.
9681 PhiVal = InVal;
9682 delete NewPN;
9683 } else {
9684 InsertNewInstBefore(NewPN, PN);
9685 PhiVal = NewPN;
9686 }
9687
9688 // Insert and return the new operation.
9689 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009690 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009691 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009692 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009693 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009694 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009695 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009696 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9697
9698 // If this was a volatile load that we are merging, make sure to loop through
9699 // and mark all the input loads as non-volatile. If we don't do this, we will
9700 // insert a new volatile load and the old ones will not be deletable.
9701 if (isVolatile)
9702 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9703 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9704
9705 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009706}
9707
9708/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9709/// that is dead.
9710static bool DeadPHICycle(PHINode *PN,
9711 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9712 if (PN->use_empty()) return true;
9713 if (!PN->hasOneUse()) return false;
9714
9715 // Remember this node, and if we find the cycle, return.
9716 if (!PotentiallyDeadPHIs.insert(PN))
9717 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009718
9719 // Don't scan crazily complex things.
9720 if (PotentiallyDeadPHIs.size() == 16)
9721 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722
9723 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9724 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9725
9726 return false;
9727}
9728
Chris Lattner27b695d2007-11-06 21:52:06 +00009729/// PHIsEqualValue - Return true if this phi node is always equal to
9730/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9731/// z = some value; x = phi (y, z); y = phi (x, z)
9732static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9733 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9734 // See if we already saw this PHI node.
9735 if (!ValueEqualPHIs.insert(PN))
9736 return true;
9737
9738 // Don't scan crazily complex things.
9739 if (ValueEqualPHIs.size() == 16)
9740 return false;
9741
9742 // Scan the operands to see if they are either phi nodes or are equal to
9743 // the value.
9744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9745 Value *Op = PN->getIncomingValue(i);
9746 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9747 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9748 return false;
9749 } else if (Op != NonPhiInVal)
9750 return false;
9751 }
9752
9753 return true;
9754}
9755
9756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009757// PHINode simplification
9758//
9759Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9760 // If LCSSA is around, don't mess with Phi nodes
9761 if (MustPreserveLCSSA) return 0;
9762
9763 if (Value *V = PN.hasConstantValue())
9764 return ReplaceInstUsesWith(PN, V);
9765
9766 // If all PHI operands are the same operation, pull them through the PHI,
9767 // reducing code size.
9768 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9769 PN.getIncomingValue(0)->hasOneUse())
9770 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9771 return Result;
9772
9773 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9774 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9775 // PHI)... break the cycle.
9776 if (PN.hasOneUse()) {
9777 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9778 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9779 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9780 PotentiallyDeadPHIs.insert(&PN);
9781 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9782 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9783 }
9784
9785 // If this phi has a single use, and if that use just computes a value for
9786 // the next iteration of a loop, delete the phi. This occurs with unused
9787 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9788 // common case here is good because the only other things that catch this
9789 // are induction variable analysis (sometimes) and ADCE, which is only run
9790 // late.
9791 if (PHIUser->hasOneUse() &&
9792 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9793 PHIUser->use_back() == &PN) {
9794 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9795 }
9796 }
9797
Chris Lattner27b695d2007-11-06 21:52:06 +00009798 // We sometimes end up with phi cycles that non-obviously end up being the
9799 // same value, for example:
9800 // z = some value; x = phi (y, z); y = phi (x, z)
9801 // where the phi nodes don't necessarily need to be in the same block. Do a
9802 // quick check to see if the PHI node only contains a single non-phi value, if
9803 // so, scan to see if the phi cycle is actually equal to that value.
9804 {
9805 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9806 // Scan for the first non-phi operand.
9807 while (InValNo != NumOperandVals &&
9808 isa<PHINode>(PN.getIncomingValue(InValNo)))
9809 ++InValNo;
9810
9811 if (InValNo != NumOperandVals) {
9812 Value *NonPhiInVal = PN.getOperand(InValNo);
9813
9814 // Scan the rest of the operands to see if there are any conflicts, if so
9815 // there is no need to recursively scan other phis.
9816 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9817 Value *OpVal = PN.getIncomingValue(InValNo);
9818 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9819 break;
9820 }
9821
9822 // If we scanned over all operands, then we have one unique value plus
9823 // phi values. Scan PHI nodes to see if they all merge in each other or
9824 // the value.
9825 if (InValNo == NumOperandVals) {
9826 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9827 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9828 return ReplaceInstUsesWith(PN, NonPhiInVal);
9829 }
9830 }
9831 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009832 return 0;
9833}
9834
9835static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9836 Instruction *InsertPoint,
9837 InstCombiner *IC) {
9838 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9839 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9840 // We must cast correctly to the pointer type. Ensure that we
9841 // sign extend the integer value if it is smaller as this is
9842 // used for address computation.
9843 Instruction::CastOps opcode =
9844 (VTySize < PtrSize ? Instruction::SExt :
9845 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9846 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9847}
9848
9849
9850Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9851 Value *PtrOp = GEP.getOperand(0);
9852 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9853 // If so, eliminate the noop.
9854 if (GEP.getNumOperands() == 1)
9855 return ReplaceInstUsesWith(GEP, PtrOp);
9856
9857 if (isa<UndefValue>(GEP.getOperand(0)))
9858 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9859
9860 bool HasZeroPointerIndex = false;
9861 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9862 HasZeroPointerIndex = C->isNullValue();
9863
9864 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9865 return ReplaceInstUsesWith(GEP, PtrOp);
9866
9867 // Eliminate unneeded casts for indices.
9868 bool MadeChange = false;
9869
9870 gep_type_iterator GTI = gep_type_begin(GEP);
9871 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9872 if (isa<SequentialType>(*GTI)) {
9873 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9874 if (CI->getOpcode() == Instruction::ZExt ||
9875 CI->getOpcode() == Instruction::SExt) {
9876 const Type *SrcTy = CI->getOperand(0)->getType();
9877 // We can eliminate a cast from i32 to i64 iff the target
9878 // is a 32-bit pointer target.
9879 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9880 MadeChange = true;
9881 GEP.setOperand(i, CI->getOperand(0));
9882 }
9883 }
9884 }
9885 // If we are using a wider index than needed for this platform, shrink it
9886 // to what we need. If the incoming value needs a cast instruction,
9887 // insert it. This explicit cast can make subsequent optimizations more
9888 // obvious.
9889 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009890 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009891 if (Constant *C = dyn_cast<Constant>(Op)) {
9892 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9893 MadeChange = true;
9894 } else {
9895 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9896 GEP);
9897 GEP.setOperand(i, Op);
9898 MadeChange = true;
9899 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009900 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009901 }
9902 }
9903 if (MadeChange) return &GEP;
9904
9905 // If this GEP instruction doesn't move the pointer, and if the input operand
9906 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9907 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009908 if (GEP.hasAllZeroIndices()) {
9909 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9910 // If the bitcast is of an allocation, and the allocation will be
9911 // converted to match the type of the cast, don't touch this.
9912 if (isa<AllocationInst>(BCI->getOperand(0))) {
9913 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009914 if (Instruction *I = visitBitCast(*BCI)) {
9915 if (I != BCI) {
9916 I->takeName(BCI);
9917 BCI->getParent()->getInstList().insert(BCI, I);
9918 ReplaceInstUsesWith(*BCI, I);
9919 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009920 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009921 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009922 }
9923 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9924 }
9925 }
9926
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009927 // Combine Indices - If the source pointer to this getelementptr instruction
9928 // is a getelementptr instruction, combine the indices of the two
9929 // getelementptr instructions into a single instruction.
9930 //
9931 SmallVector<Value*, 8> SrcGEPOperands;
9932 if (User *Src = dyn_castGetElementPtr(PtrOp))
9933 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9934
9935 if (!SrcGEPOperands.empty()) {
9936 // Note that if our source is a gep chain itself that we wait for that
9937 // chain to be resolved before we perform this transformation. This
9938 // avoids us creating a TON of code in some cases.
9939 //
9940 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9941 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9942 return 0; // Wait until our source is folded to completion.
9943
9944 SmallVector<Value*, 8> Indices;
9945
9946 // Find out whether the last index in the source GEP is a sequential idx.
9947 bool EndsWithSequential = false;
9948 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9949 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9950 EndsWithSequential = !isa<StructType>(*I);
9951
9952 // Can we combine the two pointer arithmetics offsets?
9953 if (EndsWithSequential) {
9954 // Replace: gep (gep %P, long B), long A, ...
9955 // With: T = long A+B; gep %P, T, ...
9956 //
9957 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9958 if (SO1 == Constant::getNullValue(SO1->getType())) {
9959 Sum = GO1;
9960 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9961 Sum = SO1;
9962 } else {
9963 // If they aren't the same type, convert both to an integer of the
9964 // target's pointer size.
9965 if (SO1->getType() != GO1->getType()) {
9966 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9967 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9968 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9969 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9970 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009971 unsigned PS = TD->getPointerSizeInBits();
9972 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009973 // Convert GO1 to SO1's type.
9974 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9975
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009976 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009977 // Convert SO1 to GO1's type.
9978 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9979 } else {
9980 const Type *PT = TD->getIntPtrType();
9981 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9982 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9983 }
9984 }
9985 }
9986 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9987 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9988 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009989 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009990 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9991 }
9992 }
9993
9994 // Recycle the GEP we already have if possible.
9995 if (SrcGEPOperands.size() == 2) {
9996 GEP.setOperand(0, SrcGEPOperands[0]);
9997 GEP.setOperand(1, Sum);
9998 return &GEP;
9999 } else {
10000 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10001 SrcGEPOperands.end()-1);
10002 Indices.push_back(Sum);
10003 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10004 }
10005 } else if (isa<Constant>(*GEP.idx_begin()) &&
10006 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10007 SrcGEPOperands.size() != 1) {
10008 // Otherwise we can do the fold if the first index of the GEP is a zero
10009 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10010 SrcGEPOperands.end());
10011 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10012 }
10013
10014 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010015 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10016 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010017
10018 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10019 // GEP of global variable. If all of the indices for this GEP are
10020 // constants, we can promote this to a constexpr instead of an instruction.
10021
10022 // Scan for nonconstants...
10023 SmallVector<Constant*, 8> Indices;
10024 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10025 for (; I != E && isa<Constant>(*I); ++I)
10026 Indices.push_back(cast<Constant>(*I));
10027
10028 if (I == E) { // If they are all constants...
10029 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10030 &Indices[0],Indices.size());
10031
10032 // Replace all uses of the GEP with the new constexpr...
10033 return ReplaceInstUsesWith(GEP, CE);
10034 }
10035 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10036 if (!isa<PointerType>(X->getType())) {
10037 // Not interesting. Source pointer must be a cast from pointer.
10038 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010039 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10040 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010041 //
10042 // This occurs when the program declares an array extern like "int X[];"
10043 //
10044 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10045 const PointerType *XTy = cast<PointerType>(X->getType());
10046 if (const ArrayType *XATy =
10047 dyn_cast<ArrayType>(XTy->getElementType()))
10048 if (const ArrayType *CATy =
10049 dyn_cast<ArrayType>(CPTy->getElementType()))
10050 if (CATy->getElementType() == XATy->getElementType()) {
10051 // At this point, we know that the cast source type is a pointer
10052 // to an array of the same type as the destination pointer
10053 // array. Because the array type is never stepped over (there
10054 // is a leading zero) we can fold the cast into this GEP.
10055 GEP.setOperand(0, X);
10056 return &GEP;
10057 }
10058 } else if (GEP.getNumOperands() == 2) {
10059 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010060 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10061 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010062 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10063 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10064 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010065 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10066 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010067 Value *Idx[2];
10068 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10069 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010070 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010071 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010072 // V and GEP are both pointer types --> BitCast
10073 return new BitCastInst(V, GEP.getType());
10074 }
10075
10076 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010077 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010078 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010079 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010080
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010081 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010083 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010084
10085 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10086 // allow either a mul, shift, or constant here.
10087 Value *NewIdx = 0;
10088 ConstantInt *Scale = 0;
10089 if (ArrayEltSize == 1) {
10090 NewIdx = GEP.getOperand(1);
10091 Scale = ConstantInt::get(NewIdx->getType(), 1);
10092 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10093 NewIdx = ConstantInt::get(CI->getType(), 1);
10094 Scale = CI;
10095 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10096 if (Inst->getOpcode() == Instruction::Shl &&
10097 isa<ConstantInt>(Inst->getOperand(1))) {
10098 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10099 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10100 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10101 NewIdx = Inst->getOperand(0);
10102 } else if (Inst->getOpcode() == Instruction::Mul &&
10103 isa<ConstantInt>(Inst->getOperand(1))) {
10104 Scale = cast<ConstantInt>(Inst->getOperand(1));
10105 NewIdx = Inst->getOperand(0);
10106 }
10107 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010108
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010109 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010110 // out, perform the transformation. Note, we don't know whether Scale is
10111 // signed or not. We'll use unsigned version of division/modulo
10112 // operation after making sure Scale doesn't have the sign bit set.
10113 if (Scale && Scale->getSExtValue() >= 0LL &&
10114 Scale->getZExtValue() % ArrayEltSize == 0) {
10115 Scale = ConstantInt::get(Scale->getType(),
10116 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010117 if (Scale->getZExtValue() != 1) {
10118 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010119 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010120 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010121 NewIdx = InsertNewInstBefore(Sc, GEP);
10122 }
10123
10124 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010125 Value *Idx[2];
10126 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10127 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010128 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010129 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10131 // The NewGEP must be pointer typed, so must the old one -> BitCast
10132 return new BitCastInst(NewGEP, GEP.getType());
10133 }
10134 }
10135 }
10136 }
10137
10138 return 0;
10139}
10140
10141Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10142 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010143 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010144 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10145 const Type *NewTy =
10146 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10147 AllocationInst *New = 0;
10148
10149 // Create and insert the replacement instruction...
10150 if (isa<MallocInst>(AI))
10151 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10152 else {
10153 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10154 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10155 }
10156
10157 InsertNewInstBefore(New, AI);
10158
10159 // Scan to the end of the allocation instructions, to skip over a block of
10160 // allocas if possible...
10161 //
10162 BasicBlock::iterator It = New;
10163 while (isa<AllocationInst>(*It)) ++It;
10164
10165 // Now that I is pointing to the first non-allocation-inst in the block,
10166 // insert our getelementptr instruction...
10167 //
10168 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010169 Value *Idx[2];
10170 Idx[0] = NullIdx;
10171 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010172 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10173 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010174
10175 // Now make everything use the getelementptr instead of the original
10176 // allocation.
10177 return ReplaceInstUsesWith(AI, V);
10178 } else if (isa<UndefValue>(AI.getArraySize())) {
10179 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10180 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010181 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010182
10183 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10184 // Note that we only do this for alloca's, because malloc should allocate and
10185 // return a unique pointer, even for a zero byte allocation.
10186 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010187 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010188 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10189
10190 return 0;
10191}
10192
10193Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10194 Value *Op = FI.getOperand(0);
10195
10196 // free undef -> unreachable.
10197 if (isa<UndefValue>(Op)) {
10198 // Insert a new store to null because we cannot modify the CFG here.
10199 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010200 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010201 return EraseInstFromFunction(FI);
10202 }
10203
10204 // If we have 'free null' delete the instruction. This can happen in stl code
10205 // when lots of inlining happens.
10206 if (isa<ConstantPointerNull>(Op))
10207 return EraseInstFromFunction(FI);
10208
10209 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10210 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10211 FI.setOperand(0, CI->getOperand(0));
10212 return &FI;
10213 }
10214
10215 // Change free (gep X, 0,0,0,0) into free(X)
10216 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10217 if (GEPI->hasAllZeroIndices()) {
10218 AddToWorkList(GEPI);
10219 FI.setOperand(0, GEPI->getOperand(0));
10220 return &FI;
10221 }
10222 }
10223
10224 // Change free(malloc) into nothing, if the malloc has a single use.
10225 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10226 if (MI->hasOneUse()) {
10227 EraseInstFromFunction(FI);
10228 return EraseInstFromFunction(*MI);
10229 }
10230
10231 return 0;
10232}
10233
10234
10235/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010236static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010237 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010238 User *CI = cast<User>(LI.getOperand(0));
10239 Value *CastOp = CI->getOperand(0);
10240
Devang Patela0f8ea82007-10-18 19:52:32 +000010241 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10242 // Instead of loading constant c string, use corresponding integer value
10243 // directly if string length is small enough.
10244 const std::string &Str = CE->getOperand(0)->getStringValue();
10245 if (!Str.empty()) {
10246 unsigned len = Str.length();
10247 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10248 unsigned numBits = Ty->getPrimitiveSizeInBits();
10249 // Replace LI with immediate integer store.
10250 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010251 APInt StrVal(numBits, 0);
10252 APInt SingleChar(numBits, 0);
10253 if (TD->isLittleEndian()) {
10254 for (signed i = len-1; i >= 0; i--) {
10255 SingleChar = (uint64_t) Str[i];
10256 StrVal = (StrVal << 8) | SingleChar;
10257 }
10258 } else {
10259 for (unsigned i = 0; i < len; i++) {
10260 SingleChar = (uint64_t) Str[i];
10261 StrVal = (StrVal << 8) | SingleChar;
10262 }
10263 // Append NULL at the end.
10264 SingleChar = 0;
10265 StrVal = (StrVal << 8) | SingleChar;
10266 }
10267 Value *NL = ConstantInt::get(StrVal);
10268 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010269 }
10270 }
10271 }
10272
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010273 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10274 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10275 const Type *SrcPTy = SrcTy->getElementType();
10276
10277 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10278 isa<VectorType>(DestPTy)) {
10279 // If the source is an array, the code below will not succeed. Check to
10280 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10281 // constants.
10282 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10283 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10284 if (ASrcTy->getNumElements() != 0) {
10285 Value *Idxs[2];
10286 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10287 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10288 SrcTy = cast<PointerType>(CastOp->getType());
10289 SrcPTy = SrcTy->getElementType();
10290 }
10291
10292 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10293 isa<VectorType>(SrcPTy)) &&
10294 // Do not allow turning this into a load of an integer, which is then
10295 // casted to a pointer, this pessimizes pointer analysis a lot.
10296 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10297 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10298 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10299
10300 // Okay, we are casting from one integer or pointer type to another of
10301 // the same size. Instead of casting the pointer before the load, cast
10302 // the result of the loaded value.
10303 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10304 CI->getName(),
10305 LI.isVolatile()),LI);
10306 // Now cast the result of the load.
10307 return new BitCastInst(NewLoad, LI.getType());
10308 }
10309 }
10310 }
10311 return 0;
10312}
10313
10314/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10315/// from this value cannot trap. If it is not obviously safe to load from the
10316/// specified pointer, we do a quick local scan of the basic block containing
10317/// ScanFrom, to determine if the address is already accessed.
10318static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010319 // If it is an alloca it is always safe to load from.
10320 if (isa<AllocaInst>(V)) return true;
10321
Duncan Sandse40a94a2007-09-19 10:25:38 +000010322 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010323 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010324 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010325 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010326
10327 // Otherwise, be a little bit agressive by scanning the local block where we
10328 // want to check to see if the pointer is already being loaded or stored
10329 // from/to. If so, the previous load or store would have already trapped,
10330 // so there is no harm doing an extra load (also, CSE will later eliminate
10331 // the load entirely).
10332 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10333
10334 while (BBI != E) {
10335 --BBI;
10336
10337 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10338 if (LI->getOperand(0) == V) return true;
10339 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10340 if (SI->getOperand(1) == V) return true;
10341
10342 }
10343 return false;
10344}
10345
Chris Lattner0270a112007-08-11 18:48:48 +000010346/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10347/// until we find the underlying object a pointer is referring to or something
10348/// we don't understand. Note that the returned pointer may be offset from the
10349/// input, because we ignore GEP indices.
10350static Value *GetUnderlyingObject(Value *Ptr) {
10351 while (1) {
10352 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10353 if (CE->getOpcode() == Instruction::BitCast ||
10354 CE->getOpcode() == Instruction::GetElementPtr)
10355 Ptr = CE->getOperand(0);
10356 else
10357 return Ptr;
10358 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10359 Ptr = BCI->getOperand(0);
10360 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10361 Ptr = GEP->getOperand(0);
10362 } else {
10363 return Ptr;
10364 }
10365 }
10366}
10367
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010368Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10369 Value *Op = LI.getOperand(0);
10370
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010371 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010372 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10373 if (KnownAlign >
10374 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10375 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010376 LI.setAlignment(KnownAlign);
10377
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010378 // load (cast X) --> cast (load X) iff safe
10379 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010380 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010381 return Res;
10382
10383 // None of the following transforms are legal for volatile loads.
10384 if (LI.isVolatile()) return 0;
10385
10386 if (&LI.getParent()->front() != &LI) {
10387 BasicBlock::iterator BBI = &LI; --BBI;
10388 // If the instruction immediately before this is a store to the same
10389 // address, do a simple form of store->load forwarding.
10390 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10391 if (SI->getOperand(1) == LI.getOperand(0))
10392 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10393 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10394 if (LIB->getOperand(0) == LI.getOperand(0))
10395 return ReplaceInstUsesWith(LI, LIB);
10396 }
10397
Christopher Lamb2c175392007-12-29 07:56:53 +000010398 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10399 const Value *GEPI0 = GEPI->getOperand(0);
10400 // TODO: Consider a target hook for valid address spaces for this xform.
10401 if (isa<ConstantPointerNull>(GEPI0) &&
10402 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010403 // Insert a new store to null instruction before the load to indicate
10404 // that this code is not reachable. We do this instead of inserting
10405 // an unreachable instruction directly because we cannot modify the
10406 // CFG.
10407 new StoreInst(UndefValue::get(LI.getType()),
10408 Constant::getNullValue(Op->getType()), &LI);
10409 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10410 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010412
10413 if (Constant *C = dyn_cast<Constant>(Op)) {
10414 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010415 // TODO: Consider a target hook for valid address spaces for this xform.
10416 if (isa<UndefValue>(C) || (C->isNullValue() &&
10417 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010418 // Insert a new store to null instruction before the load to indicate that
10419 // this code is not reachable. We do this instead of inserting an
10420 // unreachable instruction directly because we cannot modify the CFG.
10421 new StoreInst(UndefValue::get(LI.getType()),
10422 Constant::getNullValue(Op->getType()), &LI);
10423 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10424 }
10425
10426 // Instcombine load (constant global) into the value loaded.
10427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10428 if (GV->isConstant() && !GV->isDeclaration())
10429 return ReplaceInstUsesWith(LI, GV->getInitializer());
10430
10431 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010432 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010433 if (CE->getOpcode() == Instruction::GetElementPtr) {
10434 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10435 if (GV->isConstant() && !GV->isDeclaration())
10436 if (Constant *V =
10437 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10438 return ReplaceInstUsesWith(LI, V);
10439 if (CE->getOperand(0)->isNullValue()) {
10440 // Insert a new store to null instruction before the load to indicate
10441 // that this code is not reachable. We do this instead of inserting
10442 // an unreachable instruction directly because we cannot modify the
10443 // CFG.
10444 new StoreInst(UndefValue::get(LI.getType()),
10445 Constant::getNullValue(Op->getType()), &LI);
10446 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10447 }
10448
10449 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010450 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010451 return Res;
10452 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010454 }
Chris Lattner0270a112007-08-11 18:48:48 +000010455
10456 // If this load comes from anywhere in a constant global, and if the global
10457 // is all undef or zero, we know what it loads.
10458 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10459 if (GV->isConstant() && GV->hasInitializer()) {
10460 if (GV->getInitializer()->isNullValue())
10461 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10462 else if (isa<UndefValue>(GV->getInitializer()))
10463 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10464 }
10465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010466
10467 if (Op->hasOneUse()) {
10468 // Change select and PHI nodes to select values instead of addresses: this
10469 // helps alias analysis out a lot, allows many others simplifications, and
10470 // exposes redundancy in the code.
10471 //
10472 // Note that we cannot do the transformation unless we know that the
10473 // introduced loads cannot trap! Something like this is valid as long as
10474 // the condition is always false: load (select bool %C, int* null, int* %G),
10475 // but it would not be valid if we transformed it to load from null
10476 // unconditionally.
10477 //
10478 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10479 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10480 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10481 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10482 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10483 SI->getOperand(1)->getName()+".val"), LI);
10484 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10485 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010486 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010487 }
10488
10489 // load (select (cond, null, P)) -> load P
10490 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10491 if (C->isNullValue()) {
10492 LI.setOperand(0, SI->getOperand(2));
10493 return &LI;
10494 }
10495
10496 // load (select (cond, P, null)) -> load P
10497 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10498 if (C->isNullValue()) {
10499 LI.setOperand(0, SI->getOperand(1));
10500 return &LI;
10501 }
10502 }
10503 }
10504 return 0;
10505}
10506
10507/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10508/// when possible.
10509static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10510 User *CI = cast<User>(SI.getOperand(1));
10511 Value *CastOp = CI->getOperand(0);
10512
10513 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10514 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10515 const Type *SrcPTy = SrcTy->getElementType();
10516
10517 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10518 // If the source is an array, the code below will not succeed. Check to
10519 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10520 // constants.
10521 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10522 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10523 if (ASrcTy->getNumElements() != 0) {
10524 Value* Idxs[2];
10525 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10526 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10527 SrcTy = cast<PointerType>(CastOp->getType());
10528 SrcPTy = SrcTy->getElementType();
10529 }
10530
10531 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10532 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10533 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10534
10535 // Okay, we are casting from one integer or pointer type to another of
10536 // the same size. Instead of casting the pointer before
10537 // the store, cast the value to be stored.
10538 Value *NewCast;
10539 Value *SIOp0 = SI.getOperand(0);
10540 Instruction::CastOps opcode = Instruction::BitCast;
10541 const Type* CastSrcTy = SIOp0->getType();
10542 const Type* CastDstTy = SrcPTy;
10543 if (isa<PointerType>(CastDstTy)) {
10544 if (CastSrcTy->isInteger())
10545 opcode = Instruction::IntToPtr;
10546 } else if (isa<IntegerType>(CastDstTy)) {
10547 if (isa<PointerType>(SIOp0->getType()))
10548 opcode = Instruction::PtrToInt;
10549 }
10550 if (Constant *C = dyn_cast<Constant>(SIOp0))
10551 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10552 else
10553 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010554 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010555 SI);
10556 return new StoreInst(NewCast, CastOp);
10557 }
10558 }
10559 }
10560 return 0;
10561}
10562
10563Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10564 Value *Val = SI.getOperand(0);
10565 Value *Ptr = SI.getOperand(1);
10566
10567 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10568 EraseInstFromFunction(SI);
10569 ++NumCombined;
10570 return 0;
10571 }
10572
10573 // If the RHS is an alloca with a single use, zapify the store, making the
10574 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010575 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010576 if (isa<AllocaInst>(Ptr)) {
10577 EraseInstFromFunction(SI);
10578 ++NumCombined;
10579 return 0;
10580 }
10581
10582 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10583 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10584 GEP->getOperand(0)->hasOneUse()) {
10585 EraseInstFromFunction(SI);
10586 ++NumCombined;
10587 return 0;
10588 }
10589 }
10590
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010591 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010592 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10593 if (KnownAlign >
10594 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10595 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010596 SI.setAlignment(KnownAlign);
10597
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010598 // Do really simple DSE, to catch cases where there are several consequtive
10599 // stores to the same location, separated by a few arithmetic operations. This
10600 // situation often occurs with bitfield accesses.
10601 BasicBlock::iterator BBI = &SI;
10602 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10603 --ScanInsts) {
10604 --BBI;
10605
10606 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10607 // Prev store isn't volatile, and stores to the same location?
10608 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10609 ++NumDeadStore;
10610 ++BBI;
10611 EraseInstFromFunction(*PrevSI);
10612 continue;
10613 }
10614 break;
10615 }
10616
10617 // If this is a load, we have to stop. However, if the loaded value is from
10618 // the pointer we're loading and is producing the pointer we're storing,
10619 // then *this* store is dead (X = load P; store X -> P).
10620 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010621 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010622 EraseInstFromFunction(SI);
10623 ++NumCombined;
10624 return 0;
10625 }
10626 // Otherwise, this is a load from some other location. Stores before it
10627 // may not be dead.
10628 break;
10629 }
10630
10631 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010632 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010633 break;
10634 }
10635
10636
10637 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10638
10639 // store X, null -> turns into 'unreachable' in SimplifyCFG
10640 if (isa<ConstantPointerNull>(Ptr)) {
10641 if (!isa<UndefValue>(Val)) {
10642 SI.setOperand(0, UndefValue::get(Val->getType()));
10643 if (Instruction *U = dyn_cast<Instruction>(Val))
10644 AddToWorkList(U); // Dropped a use.
10645 ++NumCombined;
10646 }
10647 return 0; // Do not modify these!
10648 }
10649
10650 // store undef, Ptr -> noop
10651 if (isa<UndefValue>(Val)) {
10652 EraseInstFromFunction(SI);
10653 ++NumCombined;
10654 return 0;
10655 }
10656
10657 // If the pointer destination is a cast, see if we can fold the cast into the
10658 // source instead.
10659 if (isa<CastInst>(Ptr))
10660 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10661 return Res;
10662 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10663 if (CE->isCast())
10664 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10665 return Res;
10666
10667
10668 // If this store is the last instruction in the basic block, and if the block
10669 // ends with an unconditional branch, try to move it to the successor block.
10670 BBI = &SI; ++BBI;
10671 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10672 if (BI->isUnconditional())
10673 if (SimplifyStoreAtEndOfBlock(SI))
10674 return 0; // xform done!
10675
10676 return 0;
10677}
10678
10679/// SimplifyStoreAtEndOfBlock - Turn things like:
10680/// if () { *P = v1; } else { *P = v2 }
10681/// into a phi node with a store in the successor.
10682///
10683/// Simplify things like:
10684/// *P = v1; if () { *P = v2; }
10685/// into a phi node with a store in the successor.
10686///
10687bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10688 BasicBlock *StoreBB = SI.getParent();
10689
10690 // Check to see if the successor block has exactly two incoming edges. If
10691 // so, see if the other predecessor contains a store to the same location.
10692 // if so, insert a PHI node (if needed) and move the stores down.
10693 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10694
10695 // Determine whether Dest has exactly two predecessors and, if so, compute
10696 // the other predecessor.
10697 pred_iterator PI = pred_begin(DestBB);
10698 BasicBlock *OtherBB = 0;
10699 if (*PI != StoreBB)
10700 OtherBB = *PI;
10701 ++PI;
10702 if (PI == pred_end(DestBB))
10703 return false;
10704
10705 if (*PI != StoreBB) {
10706 if (OtherBB)
10707 return false;
10708 OtherBB = *PI;
10709 }
10710 if (++PI != pred_end(DestBB))
10711 return false;
10712
10713
10714 // Verify that the other block ends in a branch and is not otherwise empty.
10715 BasicBlock::iterator BBI = OtherBB->getTerminator();
10716 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10717 if (!OtherBr || BBI == OtherBB->begin())
10718 return false;
10719
10720 // If the other block ends in an unconditional branch, check for the 'if then
10721 // else' case. there is an instruction before the branch.
10722 StoreInst *OtherStore = 0;
10723 if (OtherBr->isUnconditional()) {
10724 // If this isn't a store, or isn't a store to the same location, bail out.
10725 --BBI;
10726 OtherStore = dyn_cast<StoreInst>(BBI);
10727 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10728 return false;
10729 } else {
10730 // Otherwise, the other block ended with a conditional branch. If one of the
10731 // destinations is StoreBB, then we have the if/then case.
10732 if (OtherBr->getSuccessor(0) != StoreBB &&
10733 OtherBr->getSuccessor(1) != StoreBB)
10734 return false;
10735
10736 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10737 // if/then triangle. See if there is a store to the same ptr as SI that
10738 // lives in OtherBB.
10739 for (;; --BBI) {
10740 // Check to see if we find the matching store.
10741 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10742 if (OtherStore->getOperand(1) != SI.getOperand(1))
10743 return false;
10744 break;
10745 }
10746 // If we find something that may be using the stored value, or if we run
10747 // out of instructions, we can't do the xform.
10748 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10749 BBI == OtherBB->begin())
10750 return false;
10751 }
10752
10753 // In order to eliminate the store in OtherBr, we have to
10754 // make sure nothing reads the stored value in StoreBB.
10755 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10756 // FIXME: This should really be AA driven.
10757 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10758 return false;
10759 }
10760 }
10761
10762 // Insert a PHI node now if we need it.
10763 Value *MergedVal = OtherStore->getOperand(0);
10764 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010765 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010766 PN->reserveOperandSpace(2);
10767 PN->addIncoming(SI.getOperand(0), SI.getParent());
10768 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10769 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10770 }
10771
10772 // Advance to a place where it is safe to insert the new store and
10773 // insert it.
10774 BBI = DestBB->begin();
10775 while (isa<PHINode>(BBI)) ++BBI;
10776 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10777 OtherStore->isVolatile()), *BBI);
10778
10779 // Nuke the old stores.
10780 EraseInstFromFunction(SI);
10781 EraseInstFromFunction(*OtherStore);
10782 ++NumCombined;
10783 return true;
10784}
10785
10786
10787Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10788 // Change br (not X), label True, label False to: br X, label False, True
10789 Value *X = 0;
10790 BasicBlock *TrueDest;
10791 BasicBlock *FalseDest;
10792 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10793 !isa<Constant>(X)) {
10794 // Swap Destinations and condition...
10795 BI.setCondition(X);
10796 BI.setSuccessor(0, FalseDest);
10797 BI.setSuccessor(1, TrueDest);
10798 return &BI;
10799 }
10800
10801 // Cannonicalize fcmp_one -> fcmp_oeq
10802 FCmpInst::Predicate FPred; Value *Y;
10803 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10804 TrueDest, FalseDest)))
10805 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10806 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10807 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10808 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10809 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10810 NewSCC->takeName(I);
10811 // Swap Destinations and condition...
10812 BI.setCondition(NewSCC);
10813 BI.setSuccessor(0, FalseDest);
10814 BI.setSuccessor(1, TrueDest);
10815 RemoveFromWorkList(I);
10816 I->eraseFromParent();
10817 AddToWorkList(NewSCC);
10818 return &BI;
10819 }
10820
10821 // Cannonicalize icmp_ne -> icmp_eq
10822 ICmpInst::Predicate IPred;
10823 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10824 TrueDest, FalseDest)))
10825 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10826 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10827 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10828 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10829 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10830 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10831 NewSCC->takeName(I);
10832 // Swap Destinations and condition...
10833 BI.setCondition(NewSCC);
10834 BI.setSuccessor(0, FalseDest);
10835 BI.setSuccessor(1, TrueDest);
10836 RemoveFromWorkList(I);
10837 I->eraseFromParent();;
10838 AddToWorkList(NewSCC);
10839 return &BI;
10840 }
10841
10842 return 0;
10843}
10844
10845Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10846 Value *Cond = SI.getCondition();
10847 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10848 if (I->getOpcode() == Instruction::Add)
10849 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10850 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10851 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10852 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10853 AddRHS));
10854 SI.setOperand(0, I->getOperand(0));
10855 AddToWorkList(I);
10856 return &SI;
10857 }
10858 }
10859 return 0;
10860}
10861
10862/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10863/// is to leave as a vector operation.
10864static bool CheapToScalarize(Value *V, bool isConstant) {
10865 if (isa<ConstantAggregateZero>(V))
10866 return true;
10867 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10868 if (isConstant) return true;
10869 // If all elts are the same, we can extract.
10870 Constant *Op0 = C->getOperand(0);
10871 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10872 if (C->getOperand(i) != Op0)
10873 return false;
10874 return true;
10875 }
10876 Instruction *I = dyn_cast<Instruction>(V);
10877 if (!I) return false;
10878
10879 // Insert element gets simplified to the inserted element or is deleted if
10880 // this is constant idx extract element and its a constant idx insertelt.
10881 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10882 isa<ConstantInt>(I->getOperand(2)))
10883 return true;
10884 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10885 return true;
10886 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10887 if (BO->hasOneUse() &&
10888 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10889 CheapToScalarize(BO->getOperand(1), isConstant)))
10890 return true;
10891 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10892 if (CI->hasOneUse() &&
10893 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10894 CheapToScalarize(CI->getOperand(1), isConstant)))
10895 return true;
10896
10897 return false;
10898}
10899
10900/// Read and decode a shufflevector mask.
10901///
10902/// It turns undef elements into values that are larger than the number of
10903/// elements in the input.
10904static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10905 unsigned NElts = SVI->getType()->getNumElements();
10906 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10907 return std::vector<unsigned>(NElts, 0);
10908 if (isa<UndefValue>(SVI->getOperand(2)))
10909 return std::vector<unsigned>(NElts, 2*NElts);
10910
10911 std::vector<unsigned> Result;
10912 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10913 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10914 if (isa<UndefValue>(CP->getOperand(i)))
10915 Result.push_back(NElts*2); // undef -> 8
10916 else
10917 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10918 return Result;
10919}
10920
10921/// FindScalarElement - Given a vector and an element number, see if the scalar
10922/// value is already around as a register, for example if it were inserted then
10923/// extracted from the vector.
10924static Value *FindScalarElement(Value *V, unsigned EltNo) {
10925 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10926 const VectorType *PTy = cast<VectorType>(V->getType());
10927 unsigned Width = PTy->getNumElements();
10928 if (EltNo >= Width) // Out of range access.
10929 return UndefValue::get(PTy->getElementType());
10930
10931 if (isa<UndefValue>(V))
10932 return UndefValue::get(PTy->getElementType());
10933 else if (isa<ConstantAggregateZero>(V))
10934 return Constant::getNullValue(PTy->getElementType());
10935 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10936 return CP->getOperand(EltNo);
10937 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10938 // If this is an insert to a variable element, we don't know what it is.
10939 if (!isa<ConstantInt>(III->getOperand(2)))
10940 return 0;
10941 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10942
10943 // If this is an insert to the element we are looking for, return the
10944 // inserted value.
10945 if (EltNo == IIElt)
10946 return III->getOperand(1);
10947
10948 // Otherwise, the insertelement doesn't modify the value, recurse on its
10949 // vector input.
10950 return FindScalarElement(III->getOperand(0), EltNo);
10951 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10952 unsigned InEl = getShuffleMask(SVI)[EltNo];
10953 if (InEl < Width)
10954 return FindScalarElement(SVI->getOperand(0), InEl);
10955 else if (InEl < Width*2)
10956 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10957 else
10958 return UndefValue::get(PTy->getElementType());
10959 }
10960
10961 // Otherwise, we don't know.
10962 return 0;
10963}
10964
10965Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10966
10967 // If vector val is undef, replace extract with scalar undef.
10968 if (isa<UndefValue>(EI.getOperand(0)))
10969 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10970
10971 // If vector val is constant 0, replace extract with scalar 0.
10972 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10973 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10974
10975 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10976 // If vector val is constant with uniform operands, replace EI
10977 // with that operand
10978 Constant *op0 = C->getOperand(0);
10979 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10980 if (C->getOperand(i) != op0) {
10981 op0 = 0;
10982 break;
10983 }
10984 if (op0)
10985 return ReplaceInstUsesWith(EI, op0);
10986 }
10987
10988 // If extracting a specified index from the vector, see if we can recursively
10989 // find a previously computed scalar that was inserted into the vector.
10990 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10991 unsigned IndexVal = IdxC->getZExtValue();
10992 unsigned VectorWidth =
10993 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10994
10995 // If this is extracting an invalid index, turn this into undef, to avoid
10996 // crashing the code below.
10997 if (IndexVal >= VectorWidth)
10998 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10999
11000 // This instruction only demands the single element from the input vector.
11001 // If the input vector has a single use, simplify it based on this use
11002 // property.
11003 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11004 uint64_t UndefElts;
11005 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11006 1 << IndexVal,
11007 UndefElts)) {
11008 EI.setOperand(0, V);
11009 return &EI;
11010 }
11011 }
11012
11013 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11014 return ReplaceInstUsesWith(EI, Elt);
11015
11016 // If the this extractelement is directly using a bitcast from a vector of
11017 // the same number of elements, see if we can find the source element from
11018 // it. In this case, we will end up needing to bitcast the scalars.
11019 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11020 if (const VectorType *VT =
11021 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11022 if (VT->getNumElements() == VectorWidth)
11023 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11024 return new BitCastInst(Elt, EI.getType());
11025 }
11026 }
11027
11028 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11029 if (I->hasOneUse()) {
11030 // Push extractelement into predecessor operation if legal and
11031 // profitable to do so
11032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11033 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11034 if (CheapToScalarize(BO, isConstantElt)) {
11035 ExtractElementInst *newEI0 =
11036 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11037 EI.getName()+".lhs");
11038 ExtractElementInst *newEI1 =
11039 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11040 EI.getName()+".rhs");
11041 InsertNewInstBefore(newEI0, EI);
11042 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011043 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011044 }
11045 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011046 unsigned AS =
11047 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011048 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11049 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011050 GetElementPtrInst *GEP =
11051 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011052 InsertNewInstBefore(GEP, EI);
11053 return new LoadInst(GEP);
11054 }
11055 }
11056 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11057 // Extracting the inserted element?
11058 if (IE->getOperand(2) == EI.getOperand(1))
11059 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11060 // If the inserted and extracted elements are constants, they must not
11061 // be the same value, extract from the pre-inserted value instead.
11062 if (isa<Constant>(IE->getOperand(2)) &&
11063 isa<Constant>(EI.getOperand(1))) {
11064 AddUsesToWorkList(EI);
11065 EI.setOperand(0, IE->getOperand(0));
11066 return &EI;
11067 }
11068 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11069 // If this is extracting an element from a shufflevector, figure out where
11070 // it came from and extract from the appropriate input element instead.
11071 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11072 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11073 Value *Src;
11074 if (SrcIdx < SVI->getType()->getNumElements())
11075 Src = SVI->getOperand(0);
11076 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11077 SrcIdx -= SVI->getType()->getNumElements();
11078 Src = SVI->getOperand(1);
11079 } else {
11080 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11081 }
11082 return new ExtractElementInst(Src, SrcIdx);
11083 }
11084 }
11085 }
11086 return 0;
11087}
11088
11089/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11090/// elements from either LHS or RHS, return the shuffle mask and true.
11091/// Otherwise, return false.
11092static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11093 std::vector<Constant*> &Mask) {
11094 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11095 "Invalid CollectSingleShuffleElements");
11096 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11097
11098 if (isa<UndefValue>(V)) {
11099 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11100 return true;
11101 } else if (V == LHS) {
11102 for (unsigned i = 0; i != NumElts; ++i)
11103 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11104 return true;
11105 } else if (V == RHS) {
11106 for (unsigned i = 0; i != NumElts; ++i)
11107 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11108 return true;
11109 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11110 // If this is an insert of an extract from some other vector, include it.
11111 Value *VecOp = IEI->getOperand(0);
11112 Value *ScalarOp = IEI->getOperand(1);
11113 Value *IdxOp = IEI->getOperand(2);
11114
11115 if (!isa<ConstantInt>(IdxOp))
11116 return false;
11117 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11118
11119 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11120 // Okay, we can handle this if the vector we are insertinting into is
11121 // transitively ok.
11122 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11123 // If so, update the mask to reflect the inserted undef.
11124 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11125 return true;
11126 }
11127 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11128 if (isa<ConstantInt>(EI->getOperand(1)) &&
11129 EI->getOperand(0)->getType() == V->getType()) {
11130 unsigned ExtractedIdx =
11131 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11132
11133 // This must be extracting from either LHS or RHS.
11134 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11135 // Okay, we can handle this if the vector we are insertinting into is
11136 // transitively ok.
11137 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11138 // If so, update the mask to reflect the inserted value.
11139 if (EI->getOperand(0) == LHS) {
11140 Mask[InsertedIdx & (NumElts-1)] =
11141 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11142 } else {
11143 assert(EI->getOperand(0) == RHS);
11144 Mask[InsertedIdx & (NumElts-1)] =
11145 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11146
11147 }
11148 return true;
11149 }
11150 }
11151 }
11152 }
11153 }
11154 // TODO: Handle shufflevector here!
11155
11156 return false;
11157}
11158
11159/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11160/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11161/// that computes V and the LHS value of the shuffle.
11162static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11163 Value *&RHS) {
11164 assert(isa<VectorType>(V->getType()) &&
11165 (RHS == 0 || V->getType() == RHS->getType()) &&
11166 "Invalid shuffle!");
11167 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11168
11169 if (isa<UndefValue>(V)) {
11170 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11171 return V;
11172 } else if (isa<ConstantAggregateZero>(V)) {
11173 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11174 return V;
11175 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11176 // If this is an insert of an extract from some other vector, include it.
11177 Value *VecOp = IEI->getOperand(0);
11178 Value *ScalarOp = IEI->getOperand(1);
11179 Value *IdxOp = IEI->getOperand(2);
11180
11181 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11182 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11183 EI->getOperand(0)->getType() == V->getType()) {
11184 unsigned ExtractedIdx =
11185 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11186 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11187
11188 // Either the extracted from or inserted into vector must be RHSVec,
11189 // otherwise we'd end up with a shuffle of three inputs.
11190 if (EI->getOperand(0) == RHS || RHS == 0) {
11191 RHS = EI->getOperand(0);
11192 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11193 Mask[InsertedIdx & (NumElts-1)] =
11194 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11195 return V;
11196 }
11197
11198 if (VecOp == RHS) {
11199 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11200 // Everything but the extracted element is replaced with the RHS.
11201 for (unsigned i = 0; i != NumElts; ++i) {
11202 if (i != InsertedIdx)
11203 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11204 }
11205 return V;
11206 }
11207
11208 // If this insertelement is a chain that comes from exactly these two
11209 // vectors, return the vector and the effective shuffle.
11210 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11211 return EI->getOperand(0);
11212
11213 }
11214 }
11215 }
11216 // TODO: Handle shufflevector here!
11217
11218 // Otherwise, can't do anything fancy. Return an identity vector.
11219 for (unsigned i = 0; i != NumElts; ++i)
11220 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11221 return V;
11222}
11223
11224Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11225 Value *VecOp = IE.getOperand(0);
11226 Value *ScalarOp = IE.getOperand(1);
11227 Value *IdxOp = IE.getOperand(2);
11228
11229 // Inserting an undef or into an undefined place, remove this.
11230 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11231 ReplaceInstUsesWith(IE, VecOp);
11232
11233 // If the inserted element was extracted from some other vector, and if the
11234 // indexes are constant, try to turn this into a shufflevector operation.
11235 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11236 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11237 EI->getOperand(0)->getType() == IE.getType()) {
11238 unsigned NumVectorElts = IE.getType()->getNumElements();
11239 unsigned ExtractedIdx =
11240 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11241 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11242
11243 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11244 return ReplaceInstUsesWith(IE, VecOp);
11245
11246 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11247 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11248
11249 // If we are extracting a value from a vector, then inserting it right
11250 // back into the same place, just use the input vector.
11251 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11252 return ReplaceInstUsesWith(IE, VecOp);
11253
11254 // We could theoretically do this for ANY input. However, doing so could
11255 // turn chains of insertelement instructions into a chain of shufflevector
11256 // instructions, and right now we do not merge shufflevectors. As such,
11257 // only do this in a situation where it is clear that there is benefit.
11258 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11259 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11260 // the values of VecOp, except then one read from EIOp0.
11261 // Build a new shuffle mask.
11262 std::vector<Constant*> Mask;
11263 if (isa<UndefValue>(VecOp))
11264 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11265 else {
11266 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11267 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11268 NumVectorElts));
11269 }
11270 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11271 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11272 ConstantVector::get(Mask));
11273 }
11274
11275 // If this insertelement isn't used by some other insertelement, turn it
11276 // (and any insertelements it points to), into one big shuffle.
11277 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11278 std::vector<Constant*> Mask;
11279 Value *RHS = 0;
11280 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11281 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11282 // We now have a shuffle of LHS, RHS, Mask.
11283 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11284 }
11285 }
11286 }
11287
11288 return 0;
11289}
11290
11291
11292Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11293 Value *LHS = SVI.getOperand(0);
11294 Value *RHS = SVI.getOperand(1);
11295 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11296
11297 bool MadeChange = false;
11298
11299 // Undefined shuffle mask -> undefined value.
11300 if (isa<UndefValue>(SVI.getOperand(2)))
11301 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11302
11303 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11304 // the undef, change them to undefs.
11305 if (isa<UndefValue>(SVI.getOperand(1))) {
11306 // Scan to see if there are any references to the RHS. If so, replace them
11307 // with undef element refs and set MadeChange to true.
11308 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11309 if (Mask[i] >= e && Mask[i] != 2*e) {
11310 Mask[i] = 2*e;
11311 MadeChange = true;
11312 }
11313 }
11314
11315 if (MadeChange) {
11316 // Remap any references to RHS to use LHS.
11317 std::vector<Constant*> Elts;
11318 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11319 if (Mask[i] == 2*e)
11320 Elts.push_back(UndefValue::get(Type::Int32Ty));
11321 else
11322 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11323 }
11324 SVI.setOperand(2, ConstantVector::get(Elts));
11325 }
11326 }
11327
11328 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11329 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11330 if (LHS == RHS || isa<UndefValue>(LHS)) {
11331 if (isa<UndefValue>(LHS) && LHS == RHS) {
11332 // shuffle(undef,undef,mask) -> undef.
11333 return ReplaceInstUsesWith(SVI, LHS);
11334 }
11335
11336 // Remap any references to RHS to use LHS.
11337 std::vector<Constant*> Elts;
11338 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11339 if (Mask[i] >= 2*e)
11340 Elts.push_back(UndefValue::get(Type::Int32Ty));
11341 else {
11342 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11343 (Mask[i] < e && isa<UndefValue>(LHS)))
11344 Mask[i] = 2*e; // Turn into undef.
11345 else
11346 Mask[i] &= (e-1); // Force to LHS.
11347 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11348 }
11349 }
11350 SVI.setOperand(0, SVI.getOperand(1));
11351 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11352 SVI.setOperand(2, ConstantVector::get(Elts));
11353 LHS = SVI.getOperand(0);
11354 RHS = SVI.getOperand(1);
11355 MadeChange = true;
11356 }
11357
11358 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11359 bool isLHSID = true, isRHSID = true;
11360
11361 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11362 if (Mask[i] >= e*2) continue; // Ignore undef values.
11363 // Is this an identity shuffle of the LHS value?
11364 isLHSID &= (Mask[i] == i);
11365
11366 // Is this an identity shuffle of the RHS value?
11367 isRHSID &= (Mask[i]-e == i);
11368 }
11369
11370 // Eliminate identity shuffles.
11371 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11372 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11373
11374 // If the LHS is a shufflevector itself, see if we can combine it with this
11375 // one without producing an unusual shuffle. Here we are really conservative:
11376 // we are absolutely afraid of producing a shuffle mask not in the input
11377 // program, because the code gen may not be smart enough to turn a merged
11378 // shuffle into two specific shuffles: it may produce worse code. As such,
11379 // we only merge two shuffles if the result is one of the two input shuffle
11380 // masks. In this case, merging the shuffles just removes one instruction,
11381 // which we know is safe. This is good for things like turning:
11382 // (splat(splat)) -> splat.
11383 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11384 if (isa<UndefValue>(RHS)) {
11385 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11386
11387 std::vector<unsigned> NewMask;
11388 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11389 if (Mask[i] >= 2*e)
11390 NewMask.push_back(2*e);
11391 else
11392 NewMask.push_back(LHSMask[Mask[i]]);
11393
11394 // If the result mask is equal to the src shuffle or this shuffle mask, do
11395 // the replacement.
11396 if (NewMask == LHSMask || NewMask == Mask) {
11397 std::vector<Constant*> Elts;
11398 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11399 if (NewMask[i] >= e*2) {
11400 Elts.push_back(UndefValue::get(Type::Int32Ty));
11401 } else {
11402 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11403 }
11404 }
11405 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11406 LHSSVI->getOperand(1),
11407 ConstantVector::get(Elts));
11408 }
11409 }
11410 }
11411
11412 return MadeChange ? &SVI : 0;
11413}
11414
11415
11416
11417
11418/// TryToSinkInstruction - Try to move the specified instruction from its
11419/// current block into the beginning of DestBlock, which can only happen if it's
11420/// safe to move the instruction past all of the instructions between it and the
11421/// end of its block.
11422static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11423 assert(I->hasOneUse() && "Invariants didn't hold!");
11424
11425 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011426 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11427 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011428
11429 // Do not sink alloca instructions out of the entry block.
11430 if (isa<AllocaInst>(I) && I->getParent() ==
11431 &DestBlock->getParent()->getEntryBlock())
11432 return false;
11433
11434 // We can only sink load instructions if there is nothing between the load and
11435 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011436 if (I->mayReadFromMemory()) {
11437 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011438 Scan != E; ++Scan)
11439 if (Scan->mayWriteToMemory())
11440 return false;
11441 }
11442
11443 BasicBlock::iterator InsertPos = DestBlock->begin();
11444 while (isa<PHINode>(InsertPos)) ++InsertPos;
11445
11446 I->moveBefore(InsertPos);
11447 ++NumSunkInst;
11448 return true;
11449}
11450
11451
11452/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11453/// all reachable code to the worklist.
11454///
11455/// This has a couple of tricks to make the code faster and more powerful. In
11456/// particular, we constant fold and DCE instructions as we go, to avoid adding
11457/// them to the worklist (this significantly speeds up instcombine on code where
11458/// many instructions are dead or constant). Additionally, if we find a branch
11459/// whose condition is a known constant, we only visit the reachable successors.
11460///
11461static void AddReachableCodeToWorklist(BasicBlock *BB,
11462 SmallPtrSet<BasicBlock*, 64> &Visited,
11463 InstCombiner &IC,
11464 const TargetData *TD) {
11465 std::vector<BasicBlock*> Worklist;
11466 Worklist.push_back(BB);
11467
11468 while (!Worklist.empty()) {
11469 BB = Worklist.back();
11470 Worklist.pop_back();
11471
11472 // We have now visited this block! If we've already been here, ignore it.
11473 if (!Visited.insert(BB)) continue;
11474
11475 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11476 Instruction *Inst = BBI++;
11477
11478 // DCE instruction if trivially dead.
11479 if (isInstructionTriviallyDead(Inst)) {
11480 ++NumDeadInst;
11481 DOUT << "IC: DCE: " << *Inst;
11482 Inst->eraseFromParent();
11483 continue;
11484 }
11485
11486 // ConstantProp instruction if trivially constant.
11487 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11488 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11489 Inst->replaceAllUsesWith(C);
11490 ++NumConstProp;
11491 Inst->eraseFromParent();
11492 continue;
11493 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011494
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011495 IC.AddToWorkList(Inst);
11496 }
11497
11498 // Recursively visit successors. If this is a branch or switch on a
11499 // constant, only visit the reachable successor.
11500 TerminatorInst *TI = BB->getTerminator();
11501 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11502 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11503 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011504 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011505 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011506 continue;
11507 }
11508 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11509 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11510 // See if this is an explicit destination.
11511 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11512 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011513 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011514 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011515 continue;
11516 }
11517
11518 // Otherwise it is the default destination.
11519 Worklist.push_back(SI->getSuccessor(0));
11520 continue;
11521 }
11522 }
11523
11524 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11525 Worklist.push_back(TI->getSuccessor(i));
11526 }
11527}
11528
11529bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11530 bool Changed = false;
11531 TD = &getAnalysis<TargetData>();
11532
11533 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11534 << F.getNameStr() << "\n");
11535
11536 {
11537 // Do a depth-first traversal of the function, populate the worklist with
11538 // the reachable instructions. Ignore blocks that are not reachable. Keep
11539 // track of which blocks we visit.
11540 SmallPtrSet<BasicBlock*, 64> Visited;
11541 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11542
11543 // Do a quick scan over the function. If we find any blocks that are
11544 // unreachable, remove any instructions inside of them. This prevents
11545 // the instcombine code from having to deal with some bad special cases.
11546 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11547 if (!Visited.count(BB)) {
11548 Instruction *Term = BB->getTerminator();
11549 while (Term != BB->begin()) { // Remove instrs bottom-up
11550 BasicBlock::iterator I = Term; --I;
11551
11552 DOUT << "IC: DCE: " << *I;
11553 ++NumDeadInst;
11554
11555 if (!I->use_empty())
11556 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11557 I->eraseFromParent();
11558 }
11559 }
11560 }
11561
11562 while (!Worklist.empty()) {
11563 Instruction *I = RemoveOneFromWorkList();
11564 if (I == 0) continue; // skip null values.
11565
11566 // Check to see if we can DCE the instruction.
11567 if (isInstructionTriviallyDead(I)) {
11568 // Add operands to the worklist.
11569 if (I->getNumOperands() < 4)
11570 AddUsesToWorkList(*I);
11571 ++NumDeadInst;
11572
11573 DOUT << "IC: DCE: " << *I;
11574
11575 I->eraseFromParent();
11576 RemoveFromWorkList(I);
11577 continue;
11578 }
11579
11580 // Instruction isn't dead, see if we can constant propagate it.
11581 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11582 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11583
11584 // Add operands to the worklist.
11585 AddUsesToWorkList(*I);
11586 ReplaceInstUsesWith(*I, C);
11587
11588 ++NumConstProp;
11589 I->eraseFromParent();
11590 RemoveFromWorkList(I);
11591 continue;
11592 }
11593
11594 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011595 // FIXME: Remove GetResultInst test when first class support for aggregates
11596 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011597 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011598 BasicBlock *BB = I->getParent();
11599 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11600 if (UserParent != BB) {
11601 bool UserIsSuccessor = false;
11602 // See if the user is one of our successors.
11603 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11604 if (*SI == UserParent) {
11605 UserIsSuccessor = true;
11606 break;
11607 }
11608
11609 // If the user is one of our immediate successors, and if that successor
11610 // only has us as a predecessors (we'd have to split the critical edge
11611 // otherwise), we can keep going.
11612 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11613 next(pred_begin(UserParent)) == pred_end(UserParent))
11614 // Okay, the CFG is simple enough, try to sink this instruction.
11615 Changed |= TryToSinkInstruction(I, UserParent);
11616 }
11617 }
11618
11619 // Now that we have an instruction, try combining it to simplify it...
11620#ifndef NDEBUG
11621 std::string OrigI;
11622#endif
11623 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11624 if (Instruction *Result = visit(*I)) {
11625 ++NumCombined;
11626 // Should we replace the old instruction with a new one?
11627 if (Result != I) {
11628 DOUT << "IC: Old = " << *I
11629 << " New = " << *Result;
11630
11631 // Everything uses the new instruction now.
11632 I->replaceAllUsesWith(Result);
11633
11634 // Push the new instruction and any users onto the worklist.
11635 AddToWorkList(Result);
11636 AddUsersToWorkList(*Result);
11637
11638 // Move the name to the new instruction first.
11639 Result->takeName(I);
11640
11641 // Insert the new instruction into the basic block...
11642 BasicBlock *InstParent = I->getParent();
11643 BasicBlock::iterator InsertPos = I;
11644
11645 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11646 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11647 ++InsertPos;
11648
11649 InstParent->getInstList().insert(InsertPos, Result);
11650
11651 // Make sure that we reprocess all operands now that we reduced their
11652 // use counts.
11653 AddUsesToWorkList(*I);
11654
11655 // Instructions can end up on the worklist more than once. Make sure
11656 // we do not process an instruction that has been deleted.
11657 RemoveFromWorkList(I);
11658
11659 // Erase the old instruction.
11660 InstParent->getInstList().erase(I);
11661 } else {
11662#ifndef NDEBUG
11663 DOUT << "IC: Mod = " << OrigI
11664 << " New = " << *I;
11665#endif
11666
11667 // If the instruction was modified, it's possible that it is now dead.
11668 // if so, remove it.
11669 if (isInstructionTriviallyDead(I)) {
11670 // Make sure we process all operands now that we are reducing their
11671 // use counts.
11672 AddUsesToWorkList(*I);
11673
11674 // Instructions may end up in the worklist more than once. Erase all
11675 // occurrences of this instruction.
11676 RemoveFromWorkList(I);
11677 I->eraseFromParent();
11678 } else {
11679 AddToWorkList(I);
11680 AddUsersToWorkList(*I);
11681 }
11682 }
11683 Changed = true;
11684 }
11685 }
11686
11687 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011688
11689 // Do an explicit clear, this shrinks the map if needed.
11690 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011691 return Changed;
11692}
11693
11694
11695bool InstCombiner::runOnFunction(Function &F) {
11696 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11697
11698 bool EverMadeChange = false;
11699
11700 // Iterate while there is work to do.
11701 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011702 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011703 EverMadeChange = true;
11704 return EverMadeChange;
11705}
11706
11707FunctionPass *llvm::createInstructionCombiningPass() {
11708 return new InstCombiner();
11709}
11710