blob: 05d935e1a9d1cac3fe8868b6975fcbe41a6b2361 [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"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
125 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
139 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
143 I.setOperand(i, UndefValue::get(Op->getType()));
144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195 Instruction *LHS,
196 ConstantInt *RHS);
197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
199
200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203 BinaryOperator &I);
204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
206 Instruction *commonPointerCastTransforms(CastInst &CI);
207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000210 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000217 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 Instruction *visitBitCast(BitCastInst &CI);
219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *FI);
221 Instruction *visitSelectInst(SelectInst &CI);
222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226 Instruction *visitAllocationInst(AllocationInst &AI);
227 Instruction *visitFreeInst(FreeInst &FI);
228 Instruction *visitLoadInst(LoadInst &LI);
229 Instruction *visitStoreInst(StoreInst &SI);
230 Instruction *visitBranchInst(BranchInst &BI);
231 Instruction *visitSwitchInst(SwitchInst &SI);
232 Instruction *visitInsertElementInst(InsertElementInst &IE);
233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235
236 // visitInstruction - Specify what to return for unhandled instructions...
237 Instruction *visitInstruction(Instruction &I) { return 0; }
238
239 private:
240 Instruction *visitCallSite(CallSite CS);
241 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000242 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000243 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
244 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000245 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
247 public:
248 // InsertNewInstBefore - insert an instruction New before instruction Old
249 // in the program. Add the new instruction to the worklist.
250 //
251 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
252 assert(New && New->getParent() == 0 &&
253 "New instruction already inserted into a basic block!");
254 BasicBlock *BB = Old.getParent();
255 BB->getInstList().insert(&Old, New); // Insert inst
256 AddToWorkList(New);
257 return New;
258 }
259
260 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
261 /// This also adds the cast to the worklist. Finally, this returns the
262 /// cast.
263 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
264 Instruction &Pos) {
265 if (V->getType() == Ty) return V;
266
267 if (Constant *CV = dyn_cast<Constant>(V))
268 return ConstantExpr::getCast(opc, CV, Ty);
269
Gabor Greifa645dd32008-05-16 19:29:10 +0000270 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 AddToWorkList(C);
272 return C;
273 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000274
275 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
276 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
277 }
278
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 // ReplaceInstUsesWith - This method is to be used when an instruction is
281 // found to be dead, replacable with another preexisting expression. Here
282 // we add all uses of I to the worklist, replace all uses of I with the new
283 // value, then return I, so that the inst combiner will know that I was
284 // modified.
285 //
286 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
287 AddUsersToWorkList(I); // Add all modified instrs to worklist
288 if (&I != V) {
289 I.replaceAllUsesWith(V);
290 return &I;
291 } else {
292 // If we are replacing the instruction with itself, this must be in a
293 // segment of unreachable code, so just clobber the instruction.
294 I.replaceAllUsesWith(UndefValue::get(I.getType()));
295 return &I;
296 }
297 }
298
299 // UpdateValueUsesWith - This method is to be used when an value is
300 // found to be replacable with another preexisting expression or was
301 // updated. Here we add all uses of I to the worklist, replace all uses of
302 // I with the new value (unless the instruction was just updated), then
303 // return true, so that the inst combiner will know that I was modified.
304 //
305 bool UpdateValueUsesWith(Value *Old, Value *New) {
306 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
307 if (Old != New)
308 Old->replaceAllUsesWith(New);
309 if (Instruction *I = dyn_cast<Instruction>(Old))
310 AddToWorkList(I);
311 if (Instruction *I = dyn_cast<Instruction>(New))
312 AddToWorkList(I);
313 return true;
314 }
315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
323 RemoveFromWorkList(&I);
324 I.eraseFromParent();
325 return 0; // Don't do anything with FI
326 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
341 private:
342 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
343 /// InsertBefore instruction. This is specialized a bit to avoid inserting
344 /// casts that are known to not do anything...
345 ///
346 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
347 Value *V, const Type *DestTy,
348 Instruction *InsertBefore);
349
350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
352 bool SimplifyCommutative(BinaryOperator &I);
353
354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
357
358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
362 unsigned Depth = 0);
363
364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
366
367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
371
372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377
378
379 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
380 ConstantInt *AndRHS, BinaryOperator &TheAnd);
381
382 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
383 bool isSub, Instruction &I);
384 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
385 bool isSigned, bool Inside, Instruction &IB);
386 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
387 Instruction *MatchBSwap(BinaryOperator &I);
388 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000389 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000390 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000391
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392
393 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000394
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
396 unsigned CastOpc,
397 int &NumCastsRemoved);
398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401}
402
Dan Gohman089efff2008-05-13 00:00:25 +0000403char InstCombiner::ID = 0;
404static RegisterPass<InstCombiner>
405X("instcombine", "Combine redundant instructions");
406
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407// getComplexity: Assign a complexity or rank value to LLVM Values...
408// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
409static unsigned getComplexity(Value *V) {
410 if (isa<Instruction>(V)) {
411 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
412 return 3;
413 return 4;
414 }
415 if (isa<Argument>(V)) return 3;
416 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
417}
418
419// isOnlyUse - Return true if this instruction will be deleted if we stop using
420// it.
421static bool isOnlyUse(Value *V) {
422 return V->hasOneUse() || isa<Constant>(V);
423}
424
425// getPromotedType - Return the specified type promoted as it would be to pass
426// though a va_arg area...
427static const Type *getPromotedType(const Type *Ty) {
428 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
429 if (ITy->getBitWidth() < 32)
430 return Type::Int32Ty;
431 }
432 return Ty;
433}
434
435/// getBitCastOperand - If the specified operand is a CastInst or a constant
436/// expression bitcast, return the operand value, otherwise return null.
437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439 return I->getOperand(0);
440 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
441 if (CE->getOpcode() == Instruction::BitCast)
442 return CE->getOperand(0);
443 return 0;
444}
445
446/// This function is a wrapper around CastInst::isEliminableCastPair. It
447/// simply extracts arguments and returns what that function returns.
448static Instruction::CastOps
449isEliminableCastPair(
450 const CastInst *CI, ///< The first cast instruction
451 unsigned opcode, ///< The opcode of the second cast instruction
452 const Type *DstTy, ///< The target type for the second cast instruction
453 TargetData *TD ///< The target data for pointer size
454) {
455
456 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
457 const Type *MidTy = CI->getType(); // B from above
458
459 // Get the opcodes of the two Cast instructions
460 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
461 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
462
463 return Instruction::CastOps(
464 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
465 DstTy, TD->getIntPtrType()));
466}
467
468/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
469/// in any code being generated. It does not require codegen if V is simple
470/// enough or if the cast can be folded into other casts.
471static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
472 const Type *Ty, TargetData *TD) {
473 if (V->getType() == Ty || isa<Constant>(V)) return false;
474
475 // If this is another cast that can be eliminated, it isn't codegen either.
476 if (const CastInst *CI = dyn_cast<CastInst>(V))
477 if (isEliminableCastPair(CI, opcode, Ty, TD))
478 return false;
479 return true;
480}
481
482/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
483/// InsertBefore instruction. This is specialized a bit to avoid inserting
484/// casts that are known to not do anything...
485///
486Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
487 Value *V, const Type *DestTy,
488 Instruction *InsertBefore) {
489 if (V->getType() == DestTy) return V;
490 if (Constant *C = dyn_cast<Constant>(V))
491 return ConstantExpr::getCast(opcode, C, DestTy);
492
493 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
494}
495
496// SimplifyCommutative - This performs a few simplifications for commutative
497// operators:
498//
499// 1. Order operands such that they are listed from right (least complex) to
500// left (most complex). This puts constants before unary operators before
501// binary operators.
502//
503// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505//
506bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
507 bool Changed = false;
508 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509 Changed = !I.swapOperands();
510
511 if (!I.isAssociative()) return Changed;
512 Instruction::BinaryOps Opcode = I.getOpcode();
513 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515 if (isa<Constant>(I.getOperand(1))) {
516 Constant *Folded = ConstantExpr::get(I.getOpcode(),
517 cast<Constant>(I.getOperand(1)),
518 cast<Constant>(Op->getOperand(1)));
519 I.setOperand(0, Op->getOperand(0));
520 I.setOperand(1, Folded);
521 return true;
522 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524 isOnlyUse(Op) && isOnlyUse(Op1)) {
525 Constant *C1 = cast<Constant>(Op->getOperand(1));
526 Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
529 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000530 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 Op1->getOperand(0),
532 Op1->getName(), &I);
533 AddToWorkList(New);
534 I.setOperand(0, New);
535 I.setOperand(1, Folded);
536 return true;
537 }
538 }
539 return Changed;
540}
541
542/// SimplifyCompare - For a CmpInst this function just orders the operands
543/// so that theyare listed from right (least complex) to left (most complex).
544/// This puts constants before unary operators before binary operators.
545bool InstCombiner::SimplifyCompare(CmpInst &I) {
546 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547 return false;
548 I.swapOperands();
549 // Compare instructions are not associative so there's nothing else we can do.
550 return true;
551}
552
553// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554// if the LHS is a constant zero (which is the 'negate' form).
555//
556static inline Value *dyn_castNegVal(Value *V) {
557 if (BinaryOperator::isNeg(V))
558 return BinaryOperator::getNegArgument(V);
559
560 // Constants can be considered to be negated values if they can be folded.
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000563
564 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
565 if (C->getType()->getElementType()->isInteger())
566 return ConstantExpr::getNeg(C);
567
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 return 0;
569}
570
571static inline Value *dyn_castNotVal(Value *V) {
572 if (BinaryOperator::isNot(V))
573 return BinaryOperator::getNotArgument(V);
574
575 // Constants can be considered to be not'ed values...
576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577 return ConstantInt::get(~C->getValue());
578 return 0;
579}
580
581// dyn_castFoldableMul - If this value is a multiply that can be folded into
582// other computations (because it has a constant operand), return the
583// non-constant operand of the multiply, and set CST to point to the multiplier.
584// Otherwise, return null.
585//
586static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
587 if (V->hasOneUse() && V->getType()->isInteger())
588 if (Instruction *I = dyn_cast<Instruction>(V)) {
589 if (I->getOpcode() == Instruction::Mul)
590 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
591 return I->getOperand(0);
592 if (I->getOpcode() == Instruction::Shl)
593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
594 // The multiplier is really 1 << CST.
595 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
596 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
597 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
598 return I->getOperand(0);
599 }
600 }
601 return 0;
602}
603
604/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
605/// expression, return it.
606static User *dyn_castGetElementPtr(Value *V) {
607 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
609 if (CE->getOpcode() == Instruction::GetElementPtr)
610 return cast<User>(V);
611 return false;
612}
613
Dan Gohman2d648bb2008-04-10 18:43:06 +0000614/// getOpcode - If this is an Instruction or a ConstantExpr, return the
615/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000616static unsigned getOpcode(const Value *V) {
617 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000618 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000619 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000620 return CE->getOpcode();
621 // Use UserOp1 to mean there's no opcode.
622 return Instruction::UserOp1;
623}
624
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625/// AddOne - Add one to a ConstantInt
626static ConstantInt *AddOne(ConstantInt *C) {
627 APInt Val(C->getValue());
628 return ConstantInt::get(++Val);
629}
630/// SubOne - Subtract one from a ConstantInt
631static ConstantInt *SubOne(ConstantInt *C) {
632 APInt Val(C->getValue());
633 return ConstantInt::get(--Val);
634}
635/// Add - Add two ConstantInts together
636static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
637 return ConstantInt::get(C1->getValue() + C2->getValue());
638}
639/// And - Bitwise AND two ConstantInts together
640static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
641 return ConstantInt::get(C1->getValue() & C2->getValue());
642}
643/// Subtract - Subtract one ConstantInt from another
644static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() - C2->getValue());
646}
647/// Multiply - Multiply two ConstantInts together
648static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() * C2->getValue());
650}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000651/// MultiplyOverflows - True if the multiply can not be expressed in an int
652/// this size.
653static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
654 uint32_t W = C1->getBitWidth();
655 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656 if (sign) {
657 LHSExt.sext(W * 2);
658 RHSExt.sext(W * 2);
659 } else {
660 LHSExt.zext(W * 2);
661 RHSExt.zext(W * 2);
662 }
663
664 APInt MulExt = LHSExt * RHSExt;
665
666 if (sign) {
667 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669 return MulExt.slt(Min) || MulExt.sgt(Max);
670 } else
671 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674
675/// ShrinkDemandedConstant - Check to see if the specified operand of the
676/// specified instruction is a constant integer. If so, check to see if there
677/// are any bits set in the constant that are not demanded. If so, shrink the
678/// constant and return true.
679static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
680 APInt Demanded) {
681 assert(I && "No instruction?");
682 assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684 // If the operand is not a constant integer, nothing to do.
685 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686 if (!OpC) return false;
687
688 // If there are no bits set that aren't demanded, nothing to do.
689 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690 if ((~Demanded & OpC->getValue()) == 0)
691 return false;
692
693 // This instruction is producing bits that are not demanded. Shrink the RHS.
694 Demanded &= OpC->getValue();
695 I->setOperand(OpNo, ConstantInt::get(Demanded));
696 return true;
697}
698
699// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
700// set of known zero and one bits, compute the maximum and minimum values that
701// could have the specified known zero and known one bits, returning them in
702// min/max.
703static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
704 const APInt& KnownZero,
705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
707 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
708 assert(KnownZero.getBitWidth() == BitWidth &&
709 KnownOne.getBitWidth() == BitWidth &&
710 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
711 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
712 APInt UnknownBits = ~(KnownZero|KnownOne);
713
714 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
715 // bit if it is unknown.
716 Min = KnownOne;
717 Max = KnownOne|UnknownBits;
718
719 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
720 Min.set(BitWidth-1);
721 Max.clear(BitWidth-1);
722 }
723}
724
725// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
726// a set of known zero and one bits, compute the maximum and minimum values that
727// could have the specified known zero and known one bits, returning them in
728// min/max.
729static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000730 const APInt &KnownZero,
731 const APInt &KnownOne,
732 APInt &Min, APInt &Max) {
733 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 assert(KnownZero.getBitWidth() == BitWidth &&
735 KnownOne.getBitWidth() == BitWidth &&
736 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
737 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
738 APInt UnknownBits = ~(KnownZero|KnownOne);
739
740 // The minimum value is when the unknown bits are all zeros.
741 Min = KnownOne;
742 // The maximum value is when the unknown bits are all ones.
743 Max = KnownOne|UnknownBits;
744}
745
746/// SimplifyDemandedBits - This function attempts to replace V with a simpler
747/// value based on the demanded bits. When this function is called, it is known
748/// that only the bits set in DemandedMask of the result of V are ever used
749/// downstream. Consequently, depending on the mask and V, it may be possible
750/// to replace V with a constant or one of its operands. In such cases, this
751/// function does the replacement and returns true. In all other cases, it
752/// returns false after analyzing the expression and setting KnownOne and known
753/// to be one in the expression. KnownZero contains all the bits that are known
754/// to be zero in the expression. These are provided to potentially allow the
755/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
756/// the expression. KnownOne and KnownZero always follow the invariant that
757/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
758/// the bits in KnownOne and KnownZero may only be accurate for those bits set
759/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
760/// and KnownOne must all be the same.
761bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
762 APInt& KnownZero, APInt& KnownOne,
763 unsigned Depth) {
764 assert(V != 0 && "Null pointer of Value???");
765 assert(Depth <= 6 && "Limit Search Depth");
766 uint32_t BitWidth = DemandedMask.getBitWidth();
767 const IntegerType *VTy = cast<IntegerType>(V->getType());
768 assert(VTy->getBitWidth() == BitWidth &&
769 KnownZero.getBitWidth() == BitWidth &&
770 KnownOne.getBitWidth() == BitWidth &&
771 "Value *V, DemandedMask, KnownZero and KnownOne \
772 must have same BitWidth");
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
774 // We know all of the bits for a constant!
775 KnownOne = CI->getValue() & DemandedMask;
776 KnownZero = ~KnownOne & DemandedMask;
777 return false;
778 }
779
780 KnownZero.clear();
781 KnownOne.clear();
782 if (!V->hasOneUse()) { // Other users may use these bits.
783 if (Depth != 0) { // Not at the root.
784 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
785 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
786 return false;
787 }
788 // If this is the root being simplified, allow it to have multiple uses,
789 // just set the DemandedMask to all bits.
790 DemandedMask = APInt::getAllOnesValue(BitWidth);
791 } else if (DemandedMask == 0) { // Not demanding any bits from V.
792 if (V != UndefValue::get(VTy))
793 return UpdateValueUsesWith(V, UndefValue::get(VTy));
794 return false;
795 } else if (Depth == 6) { // Limit search depth.
796 return false;
797 }
798
799 Instruction *I = dyn_cast<Instruction>(V);
800 if (!I) return false; // Only analyze instructions.
801
802 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
803 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
804 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000805 default:
806 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
807 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 case Instruction::And:
809 // If either the LHS or the RHS are Zero, the result is zero.
810 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
811 RHSKnownZero, RHSKnownOne, Depth+1))
812 return true;
813 assert((RHSKnownZero & RHSKnownOne) == 0 &&
814 "Bits known to be one AND zero?");
815
816 // If something is known zero on the RHS, the bits aren't demanded on the
817 // LHS.
818 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
819 LHSKnownZero, LHSKnownOne, Depth+1))
820 return true;
821 assert((LHSKnownZero & LHSKnownOne) == 0 &&
822 "Bits known to be one AND zero?");
823
824 // If all of the demanded bits are known 1 on one side, return the other.
825 // These bits cannot contribute to the result of the 'and'.
826 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
827 (DemandedMask & ~LHSKnownZero))
828 return UpdateValueUsesWith(I, I->getOperand(0));
829 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
830 (DemandedMask & ~RHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(1));
832
833 // If all of the demanded bits in the inputs are known zeros, return zero.
834 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
835 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
836
837 // If the RHS is a constant, see if we can simplify it.
838 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
839 return UpdateValueUsesWith(I, I);
840
841 // Output known-1 bits are only known if set in both the LHS & RHS.
842 RHSKnownOne &= LHSKnownOne;
843 // Output known-0 are known to be clear if zero in either the LHS | RHS.
844 RHSKnownZero |= LHSKnownZero;
845 break;
846 case Instruction::Or:
847 // If either the LHS or the RHS are One, the result is One.
848 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
849 RHSKnownZero, RHSKnownOne, Depth+1))
850 return true;
851 assert((RHSKnownZero & RHSKnownOne) == 0 &&
852 "Bits known to be one AND zero?");
853 // If something is known one on the RHS, the bits aren't demanded on the
854 // LHS.
855 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
856 LHSKnownZero, LHSKnownOne, Depth+1))
857 return true;
858 assert((LHSKnownZero & LHSKnownOne) == 0 &&
859 "Bits known to be one AND zero?");
860
861 // If all of the demanded bits are known zero on one side, return the other.
862 // These bits cannot contribute to the result of the 'or'.
863 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
864 (DemandedMask & ~LHSKnownOne))
865 return UpdateValueUsesWith(I, I->getOperand(0));
866 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
867 (DemandedMask & ~RHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(1));
869
870 // If all of the potentially set bits on one side are known to be set on
871 // the other side, just use the 'other' side.
872 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
873 (DemandedMask & (~RHSKnownZero)))
874 return UpdateValueUsesWith(I, I->getOperand(0));
875 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
876 (DemandedMask & (~LHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(1));
878
879 // If the RHS is a constant, see if we can simplify it.
880 if (ShrinkDemandedConstant(I, 1, DemandedMask))
881 return UpdateValueUsesWith(I, I);
882
883 // Output known-0 bits are only known if clear in both the LHS & RHS.
884 RHSKnownZero &= LHSKnownZero;
885 // Output known-1 are known to be set if set in either the LHS | RHS.
886 RHSKnownOne |= LHSKnownOne;
887 break;
888 case Instruction::Xor: {
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1))
891 return true;
892 assert((RHSKnownZero & RHSKnownOne) == 0 &&
893 "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
895 LHSKnownZero, LHSKnownOne, Depth+1))
896 return true;
897 assert((LHSKnownZero & LHSKnownOne) == 0 &&
898 "Bits known to be one AND zero?");
899
900 // If all of the demanded bits are known zero on one side, return the other.
901 // These bits cannot contribute to the result of the 'xor'.
902 if ((DemandedMask & RHSKnownZero) == DemandedMask)
903 return UpdateValueUsesWith(I, I->getOperand(0));
904 if ((DemandedMask & LHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(1));
906
907 // Output known-0 bits are known if clear or set in both the LHS & RHS.
908 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
909 (RHSKnownOne & LHSKnownOne);
910 // Output known-1 are known to be set if set in only one of the LHS, RHS.
911 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
912 (RHSKnownOne & LHSKnownZero);
913
914 // If all of the demanded bits are known to be zero on one side or the
915 // other, turn this into an *inclusive* or.
916 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
917 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
918 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000919 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 I->getName());
921 InsertNewInstBefore(Or, *I);
922 return UpdateValueUsesWith(I, Or);
923 }
924
925 // If all of the demanded bits on one side are known, and all of the set
926 // bits on that side are also known to be set on the other side, turn this
927 // into an AND, as we know the bits will be cleared.
928 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
929 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
930 // all known
931 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
932 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
933 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000934 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 InsertNewInstBefore(And, *I);
936 return UpdateValueUsesWith(I, And);
937 }
938 }
939
940 // If the RHS is a constant, see if we can simplify it.
941 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask))
943 return UpdateValueUsesWith(I, I);
944
945 RHSKnownZero = KnownZeroOut;
946 RHSKnownOne = KnownOneOut;
947 break;
948 }
949 case Instruction::Select:
950 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1))
952 return true;
953 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954 LHSKnownZero, LHSKnownOne, Depth+1))
955 return true;
956 assert((RHSKnownZero & RHSKnownOne) == 0 &&
957 "Bits known to be one AND zero?");
958 assert((LHSKnownZero & LHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960
961 // If the operands are constants, see if we can simplify them.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
964 if (ShrinkDemandedConstant(I, 2, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966
967 // Only known if known in both the LHS and RHS.
968 RHSKnownOne &= LHSKnownOne;
969 RHSKnownZero &= LHSKnownZero;
970 break;
971 case Instruction::Trunc: {
972 uint32_t truncBf =
973 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
974 DemandedMask.zext(truncBf);
975 RHSKnownZero.zext(truncBf);
976 RHSKnownOne.zext(truncBf);
977 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1))
979 return true;
980 DemandedMask.trunc(BitWidth);
981 RHSKnownZero.trunc(BitWidth);
982 RHSKnownOne.trunc(BitWidth);
983 assert((RHSKnownZero & RHSKnownOne) == 0 &&
984 "Bits known to be one AND zero?");
985 break;
986 }
987 case Instruction::BitCast:
988 if (!I->getOperand(0)->getType()->isInteger())
989 return false;
990
991 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
992 RHSKnownZero, RHSKnownOne, Depth+1))
993 return true;
994 assert((RHSKnownZero & RHSKnownOne) == 0 &&
995 "Bits known to be one AND zero?");
996 break;
997 case Instruction::ZExt: {
998 // Compute the bits in the result that are not present in the input.
999 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1000 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1001
1002 DemandedMask.trunc(SrcBitWidth);
1003 RHSKnownZero.trunc(SrcBitWidth);
1004 RHSKnownOne.trunc(SrcBitWidth);
1005 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1006 RHSKnownZero, RHSKnownOne, Depth+1))
1007 return true;
1008 DemandedMask.zext(BitWidth);
1009 RHSKnownZero.zext(BitWidth);
1010 RHSKnownOne.zext(BitWidth);
1011 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1012 "Bits known to be one AND zero?");
1013 // The top bits are known to be zero.
1014 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1015 break;
1016 }
1017 case Instruction::SExt: {
1018 // Compute the bits in the result that are not present in the input.
1019 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1020 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1021
1022 APInt InputDemandedBits = DemandedMask &
1023 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1024
1025 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1026 // If any of the sign extended bits are demanded, we know that the sign
1027 // bit is demanded.
1028 if ((NewBits & DemandedMask) != 0)
1029 InputDemandedBits.set(SrcBitWidth-1);
1030
1031 InputDemandedBits.trunc(SrcBitWidth);
1032 RHSKnownZero.trunc(SrcBitWidth);
1033 RHSKnownOne.trunc(SrcBitWidth);
1034 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1035 RHSKnownZero, RHSKnownOne, Depth+1))
1036 return true;
1037 InputDemandedBits.zext(BitWidth);
1038 RHSKnownZero.zext(BitWidth);
1039 RHSKnownOne.zext(BitWidth);
1040 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1041 "Bits known to be one AND zero?");
1042
1043 // If the sign bit of the input is known set or clear, then we know the
1044 // top bits of the result.
1045
1046 // If the input sign bit is known zero, or if the NewBits are not demanded
1047 // convert this into a zero extension.
1048 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1049 {
1050 // Convert to ZExt cast
1051 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1052 return UpdateValueUsesWith(I, NewCast);
1053 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1054 RHSKnownOne |= NewBits;
1055 }
1056 break;
1057 }
1058 case Instruction::Add: {
1059 // Figure out what the input bits are. If the top bits of the and result
1060 // are not demanded, then the add doesn't demand them from its input
1061 // either.
1062 uint32_t NLZ = DemandedMask.countLeadingZeros();
1063
1064 // If there is a constant on the RHS, there are a variety of xformations
1065 // we can do.
1066 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1067 // If null, this should be simplified elsewhere. Some of the xforms here
1068 // won't work if the RHS is zero.
1069 if (RHS->isZero())
1070 break;
1071
1072 // If the top bit of the output is demanded, demand everything from the
1073 // input. Otherwise, we demand all the input bits except NLZ top bits.
1074 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1075
1076 // Find information about known zero/one bits in the input.
1077 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1078 LHSKnownZero, LHSKnownOne, Depth+1))
1079 return true;
1080
1081 // If the RHS of the add has bits set that can't affect the input, reduce
1082 // the constant.
1083 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1084 return UpdateValueUsesWith(I, I);
1085
1086 // Avoid excess work.
1087 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1088 break;
1089
1090 // Turn it into OR if input bits are zero.
1091 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1092 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001093 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 I->getName());
1095 InsertNewInstBefore(Or, *I);
1096 return UpdateValueUsesWith(I, Or);
1097 }
1098
1099 // We can say something about the output known-zero and known-one bits,
1100 // depending on potential carries from the input constant and the
1101 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1102 // bits set and the RHS constant is 0x01001, then we know we have a known
1103 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1104
1105 // To compute this, we first compute the potential carry bits. These are
1106 // the bits which may be modified. I'm not aware of a better way to do
1107 // this scan.
1108 const APInt& RHSVal = RHS->getValue();
1109 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1110
1111 // Now that we know which bits have carries, compute the known-1/0 sets.
1112
1113 // Bits are known one if they are known zero in one operand and one in the
1114 // other, and there is no input carry.
1115 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1116 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1117
1118 // Bits are known zero if they are known zero in both operands and there
1119 // is no input carry.
1120 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1121 } else {
1122 // If the high-bits of this ADD are not demanded, then it does not demand
1123 // the high bits of its LHS or RHS.
1124 if (DemandedMask[BitWidth-1] == 0) {
1125 // Right fill the mask of bits for this ADD to demand the most
1126 // significant bit and all those below it.
1127 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1129 LHSKnownZero, LHSKnownOne, Depth+1))
1130 return true;
1131 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1133 return true;
1134 }
1135 }
1136 break;
1137 }
1138 case Instruction::Sub:
1139 // If the high-bits of this SUB are not demanded, then it does not demand
1140 // the high bits of its LHS or RHS.
1141 if (DemandedMask[BitWidth-1] == 0) {
1142 // Right fill the mask of bits for this SUB to demand the most
1143 // significant bit and all those below it.
1144 uint32_t NLZ = DemandedMask.countLeadingZeros();
1145 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1146 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1147 LHSKnownZero, LHSKnownOne, Depth+1))
1148 return true;
1149 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1151 return true;
1152 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001153 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1154 // the known zeros and ones.
1155 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 break;
1157 case Instruction::Shl:
1158 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1160 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1161 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1162 RHSKnownZero, RHSKnownOne, Depth+1))
1163 return true;
1164 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1165 "Bits known to be one AND zero?");
1166 RHSKnownZero <<= ShiftAmt;
1167 RHSKnownOne <<= ShiftAmt;
1168 // low bits known zero.
1169 if (ShiftAmt)
1170 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1171 }
1172 break;
1173 case Instruction::LShr:
1174 // For a logical shift right
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1177
1178 // Unsigned shift right.
1179 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1181 RHSKnownZero, RHSKnownOne, Depth+1))
1182 return true;
1183 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1184 "Bits known to be one AND zero?");
1185 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1186 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1187 if (ShiftAmt) {
1188 // Compute the new bits that are at the top now.
1189 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1190 RHSKnownZero |= HighBits; // high bits known zero.
1191 }
1192 }
1193 break;
1194 case Instruction::AShr:
1195 // If this is an arithmetic shift right and only the low-bit is set, we can
1196 // always convert this into a logical shr, even if the shift amount is
1197 // variable. The low bit of the shift cannot be an input sign bit unless
1198 // the shift amount is >= the size of the datatype, which is undefined.
1199 if (DemandedMask == 1) {
1200 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001201 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 I->getOperand(0), I->getOperand(1), I->getName());
1203 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1204 return UpdateValueUsesWith(I, NewVal);
1205 }
1206
1207 // If the sign bit is the only bit demanded by this ashr, then there is no
1208 // need to do it, the shift doesn't change the high bit.
1209 if (DemandedMask.isSignBit())
1210 return UpdateValueUsesWith(I, I->getOperand(0));
1211
1212 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1213 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1214
1215 // Signed shift right.
1216 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1217 // If any of the "high bits" are demanded, we should set the sign bit as
1218 // demanded.
1219 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1220 DemandedMaskIn.set(BitWidth-1);
1221 if (SimplifyDemandedBits(I->getOperand(0),
1222 DemandedMaskIn,
1223 RHSKnownZero, RHSKnownOne, Depth+1))
1224 return true;
1225 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1226 "Bits known to be one AND zero?");
1227 // Compute the new bits that are at the top now.
1228 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1229 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1230 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1231
1232 // Handle the sign bits.
1233 APInt SignBit(APInt::getSignBit(BitWidth));
1234 // Adjust to where it is now in the mask.
1235 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1236
1237 // If the input sign bit is known to be zero, or if none of the top bits
1238 // are demanded, turn this into an unsigned shift right.
1239 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1240 (HighBits & ~DemandedMask) == HighBits) {
1241 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001242 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 I->getOperand(0), SA, I->getName());
1244 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1245 return UpdateValueUsesWith(I, NewVal);
1246 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1247 RHSKnownOne |= HighBits;
1248 }
1249 }
1250 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001251 case Instruction::SRem:
1252 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1253 APInt RA = Rem->getValue();
1254 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001255 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001256 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1257 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1258 LHSKnownZero, LHSKnownOne, Depth+1))
1259 return true;
1260
1261 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1262 LHSKnownZero |= ~LowBits;
1263 else if (LHSKnownOne[BitWidth-1])
1264 LHSKnownOne |= ~LowBits;
1265
1266 KnownZero |= LHSKnownZero & DemandedMask;
1267 KnownOne |= LHSKnownOne & DemandedMask;
1268
1269 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1270 }
1271 }
1272 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001273 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001274 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1275 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001276 if (RA.isPowerOf2()) {
1277 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001278 APInt Mask2 = LowBits & DemandedMask;
1279 KnownZero |= ~LowBits & DemandedMask;
1280 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1281 KnownZero, KnownOne, Depth+1))
1282 return true;
1283
1284 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001285 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001286 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001287 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001288
1289 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1290 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001291 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1292 KnownZero2, KnownOne2, Depth+1))
1293 return true;
1294
Dan Gohmanbec16052008-04-28 17:02:21 +00001295 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001296 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001297 KnownZero2, KnownOne2, Depth+1))
1298 return true;
1299
1300 Leaders = std::max(Leaders,
1301 KnownZero2.countLeadingOnes());
1302 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001303 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001305 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306
1307 // If the client is only demanding bits that we know, return the known
1308 // constant.
1309 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1310 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1311 return false;
1312}
1313
1314
1315/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1316/// 64 or fewer elements. DemandedElts contains the set of elements that are
1317/// actually used by the caller. This method analyzes which elements of the
1318/// operand are undef and returns that information in UndefElts.
1319///
1320/// If the information about demanded elements can be used to simplify the
1321/// operation, the operation is simplified, then the resultant value is
1322/// returned. This returns null if no change was made.
1323Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1324 uint64_t &UndefElts,
1325 unsigned Depth) {
1326 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1327 assert(VWidth <= 64 && "Vector too wide to analyze!");
1328 uint64_t EltMask = ~0ULL >> (64-VWidth);
1329 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1330 "Invalid DemandedElts!");
1331
1332 if (isa<UndefValue>(V)) {
1333 // If the entire vector is undefined, just return this info.
1334 UndefElts = EltMask;
1335 return 0;
1336 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1337 UndefElts = EltMask;
1338 return UndefValue::get(V->getType());
1339 }
1340
1341 UndefElts = 0;
1342 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1343 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1344 Constant *Undef = UndefValue::get(EltTy);
1345
1346 std::vector<Constant*> Elts;
1347 for (unsigned i = 0; i != VWidth; ++i)
1348 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1349 Elts.push_back(Undef);
1350 UndefElts |= (1ULL << i);
1351 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1352 Elts.push_back(Undef);
1353 UndefElts |= (1ULL << i);
1354 } else { // Otherwise, defined.
1355 Elts.push_back(CP->getOperand(i));
1356 }
1357
1358 // If we changed the constant, return it.
1359 Constant *NewCP = ConstantVector::get(Elts);
1360 return NewCP != CP ? NewCP : 0;
1361 } else if (isa<ConstantAggregateZero>(V)) {
1362 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1363 // set to undef.
1364 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1365 Constant *Zero = Constant::getNullValue(EltTy);
1366 Constant *Undef = UndefValue::get(EltTy);
1367 std::vector<Constant*> Elts;
1368 for (unsigned i = 0; i != VWidth; ++i)
1369 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1370 UndefElts = DemandedElts ^ EltMask;
1371 return ConstantVector::get(Elts);
1372 }
1373
1374 if (!V->hasOneUse()) { // Other users may use these bits.
1375 if (Depth != 0) { // Not at the root.
1376 // TODO: Just compute the UndefElts information recursively.
1377 return false;
1378 }
1379 return false;
1380 } else if (Depth == 10) { // Limit search depth.
1381 return false;
1382 }
1383
1384 Instruction *I = dyn_cast<Instruction>(V);
1385 if (!I) return false; // Only analyze instructions.
1386
1387 bool MadeChange = false;
1388 uint64_t UndefElts2;
1389 Value *TmpV;
1390 switch (I->getOpcode()) {
1391 default: break;
1392
1393 case Instruction::InsertElement: {
1394 // If this is a variable index, we don't know which element it overwrites.
1395 // demand exactly the same input as we produce.
1396 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1397 if (Idx == 0) {
1398 // Note that we can't propagate undef elt info, because we don't know
1399 // which elt is getting updated.
1400 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1401 UndefElts2, Depth+1);
1402 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1403 break;
1404 }
1405
1406 // If this is inserting an element that isn't demanded, remove this
1407 // insertelement.
1408 unsigned IdxNo = Idx->getZExtValue();
1409 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1410 return AddSoonDeadInstToWorklist(*I, 0);
1411
1412 // Otherwise, the element inserted overwrites whatever was there, so the
1413 // input demanded set is simpler than the output set.
1414 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1415 DemandedElts & ~(1ULL << IdxNo),
1416 UndefElts, Depth+1);
1417 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1418
1419 // The inserted element is defined.
1420 UndefElts |= 1ULL << IdxNo;
1421 break;
1422 }
1423 case Instruction::BitCast: {
1424 // Vector->vector casts only.
1425 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1426 if (!VTy) break;
1427 unsigned InVWidth = VTy->getNumElements();
1428 uint64_t InputDemandedElts = 0;
1429 unsigned Ratio;
1430
1431 if (VWidth == InVWidth) {
1432 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1433 // elements as are demanded of us.
1434 Ratio = 1;
1435 InputDemandedElts = DemandedElts;
1436 } else if (VWidth > InVWidth) {
1437 // Untested so far.
1438 break;
1439
1440 // If there are more elements in the result than there are in the source,
1441 // then an input element is live if any of the corresponding output
1442 // elements are live.
1443 Ratio = VWidth/InVWidth;
1444 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1445 if (DemandedElts & (1ULL << OutIdx))
1446 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1447 }
1448 } else {
1449 // Untested so far.
1450 break;
1451
1452 // If there are more elements in the source than there are in the result,
1453 // then an input element is live if the corresponding output element is
1454 // live.
1455 Ratio = InVWidth/VWidth;
1456 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1457 if (DemandedElts & (1ULL << InIdx/Ratio))
1458 InputDemandedElts |= 1ULL << InIdx;
1459 }
1460
1461 // div/rem demand all inputs, because they don't want divide by zero.
1462 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1463 UndefElts2, Depth+1);
1464 if (TmpV) {
1465 I->setOperand(0, TmpV);
1466 MadeChange = true;
1467 }
1468
1469 UndefElts = UndefElts2;
1470 if (VWidth > InVWidth) {
1471 assert(0 && "Unimp");
1472 // If there are more elements in the result than there are in the source,
1473 // then an output element is undef if the corresponding input element is
1474 // undef.
1475 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1476 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1477 UndefElts |= 1ULL << OutIdx;
1478 } else if (VWidth < InVWidth) {
1479 assert(0 && "Unimp");
1480 // If there are more elements in the source than there are in the result,
1481 // then a result element is undef if all of the corresponding input
1482 // elements are undef.
1483 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1484 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1485 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1486 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1487 }
1488 break;
1489 }
1490 case Instruction::And:
1491 case Instruction::Or:
1492 case Instruction::Xor:
1493 case Instruction::Add:
1494 case Instruction::Sub:
1495 case Instruction::Mul:
1496 // div/rem demand all inputs, because they don't want divide by zero.
1497 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1498 UndefElts, Depth+1);
1499 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1500 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1501 UndefElts2, Depth+1);
1502 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1503
1504 // Output elements are undefined if both are undefined. Consider things
1505 // like undef&0. The result is known zero, not undef.
1506 UndefElts &= UndefElts2;
1507 break;
1508
1509 case Instruction::Call: {
1510 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1511 if (!II) break;
1512 switch (II->getIntrinsicID()) {
1513 default: break;
1514
1515 // Binary vector operations that work column-wise. A dest element is a
1516 // function of the corresponding input elements from the two inputs.
1517 case Intrinsic::x86_sse_sub_ss:
1518 case Intrinsic::x86_sse_mul_ss:
1519 case Intrinsic::x86_sse_min_ss:
1520 case Intrinsic::x86_sse_max_ss:
1521 case Intrinsic::x86_sse2_sub_sd:
1522 case Intrinsic::x86_sse2_mul_sd:
1523 case Intrinsic::x86_sse2_min_sd:
1524 case Intrinsic::x86_sse2_max_sd:
1525 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1526 UndefElts, Depth+1);
1527 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1528 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1529 UndefElts2, Depth+1);
1530 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1531
1532 // If only the low elt is demanded and this is a scalarizable intrinsic,
1533 // scalarize it now.
1534 if (DemandedElts == 1) {
1535 switch (II->getIntrinsicID()) {
1536 default: break;
1537 case Intrinsic::x86_sse_sub_ss:
1538 case Intrinsic::x86_sse_mul_ss:
1539 case Intrinsic::x86_sse2_sub_sd:
1540 case Intrinsic::x86_sse2_mul_sd:
1541 // TODO: Lower MIN/MAX/ABS/etc
1542 Value *LHS = II->getOperand(1);
1543 Value *RHS = II->getOperand(2);
1544 // Extract the element as scalars.
1545 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1546 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1547
1548 switch (II->getIntrinsicID()) {
1549 default: assert(0 && "Case stmts out of sync!");
1550 case Intrinsic::x86_sse_sub_ss:
1551 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001552 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001553 II->getName()), *II);
1554 break;
1555 case Intrinsic::x86_sse_mul_ss:
1556 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001557 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 II->getName()), *II);
1559 break;
1560 }
1561
1562 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001563 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1564 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565 InsertNewInstBefore(New, *II);
1566 AddSoonDeadInstToWorklist(*II, 0);
1567 return New;
1568 }
1569 }
1570
1571 // Output elements are undefined if both are undefined. Consider things
1572 // like undef&0. The result is known zero, not undef.
1573 UndefElts &= UndefElts2;
1574 break;
1575 }
1576 break;
1577 }
1578 }
1579 return MadeChange ? I : 0;
1580}
1581
Dan Gohman5d56fd42008-05-19 22:14:15 +00001582
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001583/// AssociativeOpt - Perform an optimization on an associative operator. This
1584/// function is designed to check a chain of associative operators for a
1585/// potential to apply a certain optimization. Since the optimization may be
1586/// applicable if the expression was reassociated, this checks the chain, then
1587/// reassociates the expression as necessary to expose the optimization
1588/// opportunity. This makes use of a special Functor, which must define
1589/// 'shouldApply' and 'apply' methods.
1590///
1591template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001592static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 unsigned Opcode = Root.getOpcode();
1594 Value *LHS = Root.getOperand(0);
1595
1596 // Quick check, see if the immediate LHS matches...
1597 if (F.shouldApply(LHS))
1598 return F.apply(Root);
1599
1600 // Otherwise, if the LHS is not of the same opcode as the root, return.
1601 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1602 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1603 // Should we apply this transform to the RHS?
1604 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1605
1606 // If not to the RHS, check to see if we should apply to the LHS...
1607 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1608 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1609 ShouldApply = true;
1610 }
1611
1612 // If the functor wants to apply the optimization to the RHS of LHSI,
1613 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1614 if (ShouldApply) {
1615 BasicBlock *BB = Root.getParent();
1616
1617 // Now all of the instructions are in the current basic block, go ahead
1618 // and perform the reassociation.
1619 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1620
1621 // First move the selected RHS to the LHS of the root...
1622 Root.setOperand(0, LHSI->getOperand(1));
1623
1624 // Make what used to be the LHS of the root be the user of the root...
1625 Value *ExtraOperand = TmpLHSI->getOperand(1);
1626 if (&Root == TmpLHSI) {
1627 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1628 return 0;
1629 }
1630 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1631 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1632 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1633 BasicBlock::iterator ARI = &Root; ++ARI;
1634 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1635 ARI = Root;
1636
1637 // Now propagate the ExtraOperand down the chain of instructions until we
1638 // get to LHSI.
1639 while (TmpLHSI != LHSI) {
1640 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1641 // Move the instruction to immediately before the chain we are
1642 // constructing to avoid breaking dominance properties.
1643 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1644 BB->getInstList().insert(ARI, NextLHSI);
1645 ARI = NextLHSI;
1646
1647 Value *NextOp = NextLHSI->getOperand(1);
1648 NextLHSI->setOperand(1, ExtraOperand);
1649 TmpLHSI = NextLHSI;
1650 ExtraOperand = NextOp;
1651 }
1652
1653 // Now that the instructions are reassociated, have the functor perform
1654 // the transformation...
1655 return F.apply(Root);
1656 }
1657
1658 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1659 }
1660 return 0;
1661}
1662
Dan Gohman089efff2008-05-13 00:00:25 +00001663namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664
Nick Lewycky27f6c132008-05-23 04:34:58 +00001665// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666struct AddRHS {
1667 Value *RHS;
1668 AddRHS(Value *rhs) : RHS(rhs) {}
1669 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1670 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001671 return BinaryOperator::CreateShl(Add.getOperand(0),
1672 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 }
1674};
1675
1676// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1677// iff C1&C2 == 0
1678struct AddMaskingAnd {
1679 Constant *C2;
1680 AddMaskingAnd(Constant *c) : C2(c) {}
1681 bool shouldApply(Value *LHS) const {
1682 ConstantInt *C1;
1683 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1684 ConstantExpr::getAnd(C1, C2)->isNullValue();
1685 }
1686 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001687 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 }
1689};
1690
Dan Gohman089efff2008-05-13 00:00:25 +00001691}
1692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1694 InstCombiner *IC) {
1695 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1696 if (Constant *SOC = dyn_cast<Constant>(SO))
1697 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1698
Gabor Greifa645dd32008-05-16 19:29:10 +00001699 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1701 }
1702
1703 // Figure out if the constant is the left or the right argument.
1704 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1705 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1706
1707 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1708 if (ConstIsRHS)
1709 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1710 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1711 }
1712
1713 Value *Op0 = SO, *Op1 = ConstOperand;
1714 if (!ConstIsRHS)
1715 std::swap(Op0, Op1);
1716 Instruction *New;
1717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001718 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001720 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 SO->getName()+".cmp");
1722 else {
1723 assert(0 && "Unknown binary instruction type!");
1724 abort();
1725 }
1726 return IC->InsertNewInstBefore(New, I);
1727}
1728
1729// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1730// constant as the other operand, try to fold the binary operator into the
1731// select arguments. This also works for Cast instructions, which obviously do
1732// not have a second operand.
1733static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1734 InstCombiner *IC) {
1735 // Don't modify shared select instructions
1736 if (!SI->hasOneUse()) return 0;
1737 Value *TV = SI->getOperand(1);
1738 Value *FV = SI->getOperand(2);
1739
1740 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1741 // Bool selects with constant operands can be folded to logical ops.
1742 if (SI->getType() == Type::Int1Ty) return 0;
1743
1744 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1745 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1746
Gabor Greifd6da1d02008-04-06 20:25:17 +00001747 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1748 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 }
1750 return 0;
1751}
1752
1753
1754/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1755/// node as operand #0, see if we can fold the instruction into the PHI (which
1756/// is only possible if all operands to the PHI are constants).
1757Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1758 PHINode *PN = cast<PHINode>(I.getOperand(0));
1759 unsigned NumPHIValues = PN->getNumIncomingValues();
1760 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1761
1762 // Check to see if all of the operands of the PHI are constants. If there is
1763 // one non-constant value, remember the BB it is. If there is more than one
1764 // or if *it* is a PHI, bail out.
1765 BasicBlock *NonConstBB = 0;
1766 for (unsigned i = 0; i != NumPHIValues; ++i)
1767 if (!isa<Constant>(PN->getIncomingValue(i))) {
1768 if (NonConstBB) return 0; // More than one non-const value.
1769 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1770 NonConstBB = PN->getIncomingBlock(i);
1771
1772 // If the incoming non-constant value is in I's block, we have an infinite
1773 // loop.
1774 if (NonConstBB == I.getParent())
1775 return 0;
1776 }
1777
1778 // If there is exactly one non-constant value, we can insert a copy of the
1779 // operation in that block. However, if this is a critical edge, we would be
1780 // inserting the computation one some other paths (e.g. inside a loop). Only
1781 // do this if the pred block is unconditionally branching into the phi block.
1782 if (NonConstBB) {
1783 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1784 if (!BI || !BI->isUnconditional()) return 0;
1785 }
1786
1787 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001788 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1790 InsertNewInstBefore(NewPN, *PN);
1791 NewPN->takeName(PN);
1792
1793 // Next, add all of the operands to the PHI.
1794 if (I.getNumOperands() == 2) {
1795 Constant *C = cast<Constant>(I.getOperand(1));
1796 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001797 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1799 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1800 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1801 else
1802 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1803 } else {
1804 assert(PN->getIncomingBlock(i) == NonConstBB);
1805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001806 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 PN->getIncomingValue(i), C, "phitmp",
1808 NonConstBB->getTerminator());
1809 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001810 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 CI->getPredicate(),
1812 PN->getIncomingValue(i), C, "phitmp",
1813 NonConstBB->getTerminator());
1814 else
1815 assert(0 && "Unknown binop!");
1816
1817 AddToWorkList(cast<Instruction>(InV));
1818 }
1819 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1820 }
1821 } else {
1822 CastInst *CI = cast<CastInst>(&I);
1823 const Type *RetTy = CI->getType();
1824 for (unsigned i = 0; i != NumPHIValues; ++i) {
1825 Value *InV;
1826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1827 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1828 } else {
1829 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001830 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 I.getType(), "phitmp",
1832 NonConstBB->getTerminator());
1833 AddToWorkList(cast<Instruction>(InV));
1834 }
1835 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1836 }
1837 }
1838 return ReplaceInstUsesWith(I, NewPN);
1839}
1840
Chris Lattner55476162008-01-29 06:52:45 +00001841
1842/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1843/// value is never equal to -0.0.
1844///
1845/// Note that this function will need to be revisited when we support nondefault
1846/// rounding modes!
1847///
1848static bool CannotBeNegativeZero(const Value *V) {
1849 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1850 return !CFP->getValueAPF().isNegZero();
1851
Chris Lattner55476162008-01-29 06:52:45 +00001852 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnere3061db2008-05-19 20:27:56 +00001853 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner55476162008-01-29 06:52:45 +00001854 if (I->getOpcode() == Instruction::Add &&
1855 isa<ConstantFP>(I->getOperand(1)) &&
1856 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1857 return true;
1858
Chris Lattnere3061db2008-05-19 20:27:56 +00001859 // sitofp and uitofp turn into +0.0 for zero.
1860 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1861 return true;
1862
Chris Lattner55476162008-01-29 06:52:45 +00001863 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1864 if (II->getIntrinsicID() == Intrinsic::sqrt)
1865 return CannotBeNegativeZero(II->getOperand(1));
1866
1867 if (const CallInst *CI = dyn_cast<CallInst>(I))
1868 if (const Function *F = CI->getCalledFunction()) {
1869 if (F->isDeclaration()) {
1870 switch (F->getNameLen()) {
1871 case 3: // abs(x) != -0.0
1872 if (!strcmp(F->getNameStart(), "abs")) return true;
1873 break;
1874 case 4: // abs[lf](x) != -0.0
1875 if (!strcmp(F->getNameStart(), "absf")) return true;
1876 if (!strcmp(F->getNameStart(), "absl")) return true;
1877 break;
1878 }
1879 }
1880 }
1881 }
1882
1883 return false;
1884}
1885
Chris Lattner3554f972008-05-20 05:46:13 +00001886/// WillNotOverflowSignedAdd - Return true if we can prove that:
1887/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1888/// This basically requires proving that the add in the original type would not
1889/// overflow to change the sign bit or have a carry out.
1890bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1891 // There are different heuristics we can use for this. Here are some simple
1892 // ones.
1893
1894 // Add has the property that adding any two 2's complement numbers can only
1895 // have one carry bit which can change a sign. As such, if LHS and RHS each
1896 // have at least two sign bits, we know that the addition of the two values will
1897 // sign extend fine.
1898 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1899 return true;
1900
1901
1902 // If one of the operands only has one non-zero bit, and if the other operand
1903 // has a known-zero bit in a more significant place than it (not including the
1904 // sign bit) the ripple may go up to and fill the zero, but won't change the
1905 // sign. For example, (X & ~4) + 1.
1906
1907 // TODO: Implement.
1908
1909 return false;
1910}
1911
Chris Lattner55476162008-01-29 06:52:45 +00001912
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1914 bool Changed = SimplifyCommutative(I);
1915 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1916
1917 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1918 // X + undef -> undef
1919 if (isa<UndefValue>(RHS))
1920 return ReplaceInstUsesWith(I, RHS);
1921
1922 // X + 0 --> X
1923 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1924 if (RHSC->isNullValue())
1925 return ReplaceInstUsesWith(I, LHS);
1926 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001927 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1928 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001929 return ReplaceInstUsesWith(I, LHS);
1930 }
1931
1932 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1933 // X + (signbit) --> X ^ signbit
1934 const APInt& Val = CI->getValue();
1935 uint32_t BitWidth = Val.getBitWidth();
1936 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001937 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938
1939 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1940 // (X & 254)+1 -> (X&254)|1
1941 if (!isa<VectorType>(I.getType())) {
1942 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1943 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1944 KnownZero, KnownOne))
1945 return &I;
1946 }
1947 }
1948
1949 if (isa<PHINode>(LHS))
1950 if (Instruction *NV = FoldOpIntoPhi(I))
1951 return NV;
1952
1953 ConstantInt *XorRHS = 0;
1954 Value *XorLHS = 0;
1955 if (isa<ConstantInt>(RHSC) &&
1956 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1957 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1958 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1959
1960 uint32_t Size = TySizeBits / 2;
1961 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1962 APInt CFF80Val(-C0080Val);
1963 do {
1964 if (TySizeBits > Size) {
1965 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1966 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1967 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1968 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1969 // This is a sign extend if the top bits are known zero.
1970 if (!MaskedValueIsZero(XorLHS,
1971 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1972 Size = 0; // Not a sign ext, but can't be any others either.
1973 break;
1974 }
1975 }
1976 Size >>= 1;
1977 C0080Val = APIntOps::lshr(C0080Val, Size);
1978 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1979 } while (Size >= 1);
1980
1981 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00001982 // with funny bit widths then this switch statement should be removed. It
1983 // is just here to get the size of the "middle" type back up to something
1984 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985 const Type *MiddleType = 0;
1986 switch (Size) {
1987 default: break;
1988 case 32: MiddleType = Type::Int32Ty; break;
1989 case 16: MiddleType = Type::Int16Ty; break;
1990 case 8: MiddleType = Type::Int8Ty; break;
1991 }
1992 if (MiddleType) {
1993 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1994 InsertNewInstBefore(NewTrunc, I);
1995 return new SExtInst(NewTrunc, I.getType(), I.getName());
1996 }
1997 }
1998 }
1999
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002000 if (I.getType() == Type::Int1Ty)
2001 return BinaryOperator::CreateXor(LHS, RHS);
2002
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002003 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002004 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2006
2007 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2008 if (RHSI->getOpcode() == Instruction::Sub)
2009 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2010 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2011 }
2012 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2013 if (LHSI->getOpcode() == Instruction::Sub)
2014 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2015 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2016 }
2017 }
2018
2019 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002020 // -A + -B --> -(A + B)
2021 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002022 if (LHS->getType()->isIntOrIntVector()) {
2023 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002024 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002025 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002026 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002027 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002028 }
2029
Gabor Greifa645dd32008-05-16 19:29:10 +00002030 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002031 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032
2033 // A + -B --> A - B
2034 if (!isa<Constant>(RHS))
2035 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002036 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037
2038
2039 ConstantInt *C2;
2040 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2041 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002042 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043
2044 // X*C1 + X*C2 --> X * (C1+C2)
2045 ConstantInt *C1;
2046 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002047 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 }
2049
2050 // X + X*C --> X * (C+1)
2051 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002052 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053
2054 // X + ~X --> -1 since ~X = -X-1
2055 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2056 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2057
2058
2059 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2060 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2061 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2062 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002063
2064 // A+B --> A|B iff A and B have no bits set in common.
2065 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2066 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2067 APInt LHSKnownOne(IT->getBitWidth(), 0);
2068 APInt LHSKnownZero(IT->getBitWidth(), 0);
2069 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2070 if (LHSKnownZero != 0) {
2071 APInt RHSKnownOne(IT->getBitWidth(), 0);
2072 APInt RHSKnownZero(IT->getBitWidth(), 0);
2073 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2074
2075 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002076 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002077 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002078 }
2079 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002080
Nick Lewycky83598a72008-02-03 07:42:09 +00002081 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002082 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002083 Value *W, *X, *Y, *Z;
2084 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2085 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2086 if (W != Y) {
2087 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002088 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002089 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002090 std::swap(W, X);
2091 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002092 std::swap(Y, Z);
2093 std::swap(W, X);
2094 }
2095 }
2096
2097 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002098 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002099 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002100 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002101 }
2102 }
2103 }
2104
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002105 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2106 Value *X = 0;
2107 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002108 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109
2110 // (X & FF00) + xx00 -> (X+xx00) & FF00
2111 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2112 Constant *Anded = And(CRHS, C2);
2113 if (Anded == CRHS) {
2114 // See if all bits from the first bit set in the Add RHS up are included
2115 // in the mask. First, get the rightmost bit.
2116 const APInt& AddRHSV = CRHS->getValue();
2117
2118 // Form a mask of all bits from the lowest bit added through the top.
2119 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2120
2121 // See if the and mask includes all of these bits.
2122 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2123
2124 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2125 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002126 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002128 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 }
2130 }
2131 }
2132
2133 // Try to fold constant add into select arguments.
2134 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2136 return R;
2137 }
2138
2139 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002140 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 {
2142 CastInst *CI = dyn_cast<CastInst>(LHS);
2143 Value *Other = RHS;
2144 if (!CI) {
2145 CI = dyn_cast<CastInst>(RHS);
2146 Other = LHS;
2147 }
2148 if (CI && CI->getType()->isSized() &&
2149 (CI->getType()->getPrimitiveSizeInBits() ==
2150 TD->getIntPtrType()->getPrimitiveSizeInBits())
2151 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002152 unsigned AS =
2153 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002154 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2155 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002156 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157 return new PtrToIntInst(I2, CI->getType());
2158 }
2159 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002160
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002161 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002162 {
2163 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2164 Value *Other = RHS;
2165 if (!SI) {
2166 SI = dyn_cast<SelectInst>(RHS);
2167 Other = LHS;
2168 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002169 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002170 Value *TV = SI->getTrueValue();
2171 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002172 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002173
2174 // Can we fold the add into the argument of the select?
2175 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002176 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2177 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002178 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002179 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2180 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002181 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002182 }
2183 }
Chris Lattner55476162008-01-29 06:52:45 +00002184
2185 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2186 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2187 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2188 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189
Chris Lattner3554f972008-05-20 05:46:13 +00002190 // Check for (add (sext x), y), see if we can merge this into an
2191 // integer add followed by a sext.
2192 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2193 // (add (sext x), cst) --> (sext (add x, cst'))
2194 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2195 Constant *CI =
2196 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2197 if (LHSConv->hasOneUse() &&
2198 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2199 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2200 // Insert the new, smaller add.
2201 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2202 CI, "addconv");
2203 InsertNewInstBefore(NewAdd, I);
2204 return new SExtInst(NewAdd, I.getType());
2205 }
2206 }
2207
2208 // (add (sext x), (sext y)) --> (sext (add int x, y))
2209 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2210 // Only do this if x/y have the same type, if at last one of them has a
2211 // single use (so we don't increase the number of sexts), and if the
2212 // integer add will not overflow.
2213 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2214 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2215 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2216 RHSConv->getOperand(0))) {
2217 // Insert the new integer add.
2218 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2219 RHSConv->getOperand(0),
2220 "addconv");
2221 InsertNewInstBefore(NewAdd, I);
2222 return new SExtInst(NewAdd, I.getType());
2223 }
2224 }
2225 }
2226
2227 // Check for (add double (sitofp x), y), see if we can merge this into an
2228 // integer add followed by a promotion.
2229 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2230 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2231 // ... if the constant fits in the integer value. This is useful for things
2232 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2233 // requires a constant pool load, and generally allows the add to be better
2234 // instcombined.
2235 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2236 Constant *CI =
2237 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2238 if (LHSConv->hasOneUse() &&
2239 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2240 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2241 // Insert the new integer add.
2242 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2243 CI, "addconv");
2244 InsertNewInstBefore(NewAdd, I);
2245 return new SIToFPInst(NewAdd, I.getType());
2246 }
2247 }
2248
2249 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2250 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2251 // Only do this if x/y have the same type, if at last one of them has a
2252 // single use (so we don't increase the number of int->fp conversions),
2253 // and if the integer add will not overflow.
2254 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2255 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2256 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2257 RHSConv->getOperand(0))) {
2258 // Insert the new integer add.
2259 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2260 RHSConv->getOperand(0),
2261 "addconv");
2262 InsertNewInstBefore(NewAdd, I);
2263 return new SIToFPInst(NewAdd, I.getType());
2264 }
2265 }
2266 }
2267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 return Changed ? &I : 0;
2269}
2270
2271// isSignBit - Return true if the value represented by the constant only has the
2272// highest order bit set.
2273static bool isSignBit(ConstantInt *CI) {
2274 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2275 return CI->getValue() == APInt::getSignBit(NumBits);
2276}
2277
2278Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2280
2281 if (Op0 == Op1) // sub X, X -> 0
2282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2283
2284 // If this is a 'B = x-(-A)', change to B = x+A...
2285 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002286 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287
2288 if (isa<UndefValue>(Op0))
2289 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2290 if (isa<UndefValue>(Op1))
2291 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2292
2293 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2294 // Replace (-1 - A) with (~A)...
2295 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002296 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297
2298 // C - ~X == X + (1+C)
2299 Value *X = 0;
2300 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002301 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302
2303 // -(X >>u 31) -> (X >>s 31)
2304 // -(X >>s 31) -> (X >>u 31)
2305 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002306 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 if (SI->getOpcode() == Instruction::LShr) {
2308 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2309 // Check to see if we are shifting out everything but the sign bit.
2310 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2311 SI->getType()->getPrimitiveSizeInBits()-1) {
2312 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002313 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 SI->getOperand(0), CU, SI->getName());
2315 }
2316 }
2317 }
2318 else if (SI->getOpcode() == Instruction::AShr) {
2319 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2320 // Check to see if we are shifting out everything but the sign bit.
2321 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2322 SI->getType()->getPrimitiveSizeInBits()-1) {
2323 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 SI->getOperand(0), CU, SI->getName());
2326 }
2327 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002328 }
2329 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 }
2331
2332 // Try to fold constant sub into select arguments.
2333 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2335 return R;
2336
2337 if (isa<PHINode>(Op0))
2338 if (Instruction *NV = FoldOpIntoPhi(I))
2339 return NV;
2340 }
2341
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002342 if (I.getType() == Type::Int1Ty)
2343 return BinaryOperator::CreateXor(Op0, Op1);
2344
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002345 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2346 if (Op1I->getOpcode() == Instruction::Add &&
2347 !Op0->getType()->isFPOrFPVector()) {
2348 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002349 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002351 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002352 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2353 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2354 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002355 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356 Op1I->getOperand(0));
2357 }
2358 }
2359
2360 if (Op1I->hasOneUse()) {
2361 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2362 // is not used by anyone else...
2363 //
2364 if (Op1I->getOpcode() == Instruction::Sub &&
2365 !Op1I->getType()->isFPOrFPVector()) {
2366 // Swap the two operands of the subexpr...
2367 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2368 Op1I->setOperand(0, IIOp1);
2369 Op1I->setOperand(1, IIOp0);
2370
2371 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002372 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373 }
2374
2375 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2376 //
2377 if (Op1I->getOpcode() == Instruction::And &&
2378 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2379 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2380
2381 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002382 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2383 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384 }
2385
2386 // 0 - (X sdiv C) -> (X sdiv -C)
2387 if (Op1I->getOpcode() == Instruction::SDiv)
2388 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2389 if (CSI->isZero())
2390 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002391 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002392 ConstantExpr::getNeg(DivRHS));
2393
2394 // X - X*C --> X * (1-C)
2395 ConstantInt *C2 = 0;
2396 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2397 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002398 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002399 }
Dan Gohmanda338742007-09-17 17:31:57 +00002400
2401 // X - ((X / Y) * Y) --> X % Y
2402 if (Op1I->getOpcode() == Instruction::Mul)
2403 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2404 if (Op0 == I->getOperand(0) &&
2405 Op1I->getOperand(1) == I->getOperand(1)) {
2406 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002407 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002408 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002409 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411 }
2412 }
2413
2414 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002415 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416 if (Op0I->getOpcode() == Instruction::Add) {
2417 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2418 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2419 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2420 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2421 } else if (Op0I->getOpcode() == Instruction::Sub) {
2422 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002423 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002424 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002425 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426
2427 ConstantInt *C1;
2428 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2429 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002430 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431
2432 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2433 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002434 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002435 }
2436 return 0;
2437}
2438
2439/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2440/// comparison only checks the sign bit. If it only checks the sign bit, set
2441/// TrueIfSigned if the result of the comparison is true when the input value is
2442/// signed.
2443static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2444 bool &TrueIfSigned) {
2445 switch (pred) {
2446 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2447 TrueIfSigned = true;
2448 return RHS->isZero();
2449 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2450 TrueIfSigned = true;
2451 return RHS->isAllOnesValue();
2452 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2453 TrueIfSigned = false;
2454 return RHS->isAllOnesValue();
2455 case ICmpInst::ICMP_UGT:
2456 // True if LHS u> RHS and RHS == high-bit-mask - 1
2457 TrueIfSigned = true;
2458 return RHS->getValue() ==
2459 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2460 case ICmpInst::ICMP_UGE:
2461 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2462 TrueIfSigned = true;
2463 return RHS->getValue() ==
2464 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2465 default:
2466 return false;
2467 }
2468}
2469
2470Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2471 bool Changed = SimplifyCommutative(I);
2472 Value *Op0 = I.getOperand(0);
2473
2474 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2475 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2476
2477 // Simplify mul instructions with a constant RHS...
2478 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2479 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2480
2481 // ((X << C1)*C2) == (X * (C2 << C1))
2482 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2483 if (SI->getOpcode() == Instruction::Shl)
2484 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 ConstantExpr::getShl(CI, ShOp));
2487
2488 if (CI->isZero())
2489 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2490 if (CI->equalsInt(1)) // X * 1 == X
2491 return ReplaceInstUsesWith(I, Op0);
2492 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002493 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002494
2495 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2496 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002497 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 ConstantInt::get(Op0->getType(), Val.logBase2()));
2499 }
2500 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2501 if (Op1F->isNullValue())
2502 return ReplaceInstUsesWith(I, Op1);
2503
2504 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2505 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002506 // We need a better interface for long double here.
2507 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2508 if (Op1F->isExactlyValue(1.0))
2509 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002510 }
2511
2512 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2513 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002514 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002516 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 Op1, "tmp");
2518 InsertNewInstBefore(Add, I);
2519 Value *C1C2 = ConstantExpr::getMul(Op1,
2520 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002521 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522
2523 }
2524
2525 // Try to fold constant mul into select arguments.
2526 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2527 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2528 return R;
2529
2530 if (isa<PHINode>(Op0))
2531 if (Instruction *NV = FoldOpIntoPhi(I))
2532 return NV;
2533 }
2534
2535 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2536 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002537 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002538
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002539 if (I.getType() == Type::Int1Ty)
2540 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2541
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002542 // If one of the operands of the multiply is a cast from a boolean value, then
2543 // we know the bool is either zero or one, so this is a 'masking' multiply.
2544 // See if we can simplify things based on how the boolean was originally
2545 // formed.
2546 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002547 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2549 BoolCast = CI;
2550 if (!BoolCast)
2551 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2552 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2553 BoolCast = CI;
2554 if (BoolCast) {
2555 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2556 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2557 const Type *SCOpTy = SCIOp0->getType();
2558 bool TIS = false;
2559
2560 // If the icmp is true iff the sign bit of X is set, then convert this
2561 // multiply into a shift/and combination.
2562 if (isa<ConstantInt>(SCIOp1) &&
2563 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2564 TIS) {
2565 // Shift the X value right to turn it into "all signbits".
2566 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2567 SCOpTy->getPrimitiveSizeInBits()-1);
2568 Value *V =
2569 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002570 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571 BoolCast->getOperand(0)->getName()+
2572 ".mask"), I);
2573
2574 // If the multiply type is not the same as the source type, sign extend
2575 // or truncate to the multiply type.
2576 if (I.getType() != V->getType()) {
2577 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2578 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2579 Instruction::CastOps opcode =
2580 (SrcBits == DstBits ? Instruction::BitCast :
2581 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2582 V = InsertCastBefore(opcode, V, I.getType(), I);
2583 }
2584
2585 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002586 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 }
2588 }
2589 }
2590
2591 return Changed ? &I : 0;
2592}
2593
2594/// This function implements the transforms on div instructions that work
2595/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2596/// used by the visitors to those instructions.
2597/// @brief Transforms common to all three div instructions
2598Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2599 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2600
Chris Lattner653ef3c2008-02-19 06:12:18 +00002601 // undef / X -> 0 for integer.
2602 // undef / X -> undef for FP (the undef could be a snan).
2603 if (isa<UndefValue>(Op0)) {
2604 if (Op0->getType()->isFPOrFPVector())
2605 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002607 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608
2609 // X / undef -> undef
2610 if (isa<UndefValue>(Op1))
2611 return ReplaceInstUsesWith(I, Op1);
2612
Chris Lattner5be238b2008-01-28 00:58:18 +00002613 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2614 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002616 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2617 // the same basic block, then we replace the select with Y, and the
2618 // condition of the select with false (if the cond value is in the same BB).
2619 // If the select has uses other than the div, this allows them to be
2620 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2621 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002622 if (ST->isNullValue()) {
2623 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2624 if (CondI && CondI->getParent() == I.getParent())
2625 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2626 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627 I.setOperand(1, SI->getOperand(2));
2628 else
2629 UpdateValueUsesWith(SI, SI->getOperand(2));
2630 return &I;
2631 }
2632
Chris Lattner5be238b2008-01-28 00:58:18 +00002633 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2634 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635 if (ST->isNullValue()) {
2636 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2637 if (CondI && CondI->getParent() == I.getParent())
2638 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2639 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2640 I.setOperand(1, SI->getOperand(1));
2641 else
2642 UpdateValueUsesWith(SI, SI->getOperand(1));
2643 return &I;
2644 }
2645 }
2646
2647 return 0;
2648}
2649
2650/// This function implements the transforms common to both integer division
2651/// instructions (udiv and sdiv). It is called by the visitors to those integer
2652/// division instructions.
2653/// @brief Common integer divide transforms
2654Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2656
Chris Lattnercefb36c2008-05-16 02:59:42 +00002657 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002658 if (Op0 == Op1) {
2659 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2660 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2661 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2662 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2663 }
2664
2665 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2666 return ReplaceInstUsesWith(I, CI);
2667 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 if (Instruction *Common = commonDivTransforms(I))
2670 return Common;
2671
2672 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2673 // div X, 1 == X
2674 if (RHS->equalsInt(1))
2675 return ReplaceInstUsesWith(I, Op0);
2676
2677 // (X / C1) / C2 -> X / (C1*C2)
2678 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2679 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2680 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002681 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2682 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2683 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002685 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 }
2687
2688 if (!RHS->isZero()) { // avoid X udiv 0
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2691 return R;
2692 if (isa<PHINode>(Op0))
2693 if (Instruction *NV = FoldOpIntoPhi(I))
2694 return NV;
2695 }
2696 }
2697
2698 // 0 / X == 0, we don't need to preserve faults!
2699 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2700 if (LHS->equalsInt(0))
2701 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2702
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002703 // It can't be division by zero, hence it must be division by one.
2704 if (I.getType() == Type::Int1Ty)
2705 return ReplaceInstUsesWith(I, Op0);
2706
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 return 0;
2708}
2709
2710Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2711 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2712
2713 // Handle the integer div common cases
2714 if (Instruction *Common = commonIDivTransforms(I))
2715 return Common;
2716
2717 // X udiv C^2 -> X >> C
2718 // Check to see if this is an unsigned division with an exact power of 2,
2719 // if so, convert to a right shift.
2720 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2721 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002722 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2724 }
2725
2726 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2727 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2728 if (RHSI->getOpcode() == Instruction::Shl &&
2729 isa<ConstantInt>(RHSI->getOperand(0))) {
2730 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2731 if (C1.isPowerOf2()) {
2732 Value *N = RHSI->getOperand(1);
2733 const Type *NTy = N->getType();
2734 if (uint32_t C2 = C1.logBase2()) {
2735 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002736 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002738 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 }
2740 }
2741 }
2742
2743 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2744 // where C1&C2 are powers of two.
2745 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2746 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2747 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2748 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2749 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2750 // Compute the shift amounts
2751 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2752 // Construct the "on true" case of the select
2753 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002754 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755 Op0, TC, SI->getName()+".t");
2756 TSI = InsertNewInstBefore(TSI, I);
2757
2758 // Construct the "on false" case of the select
2759 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002760 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 Op0, FC, SI->getName()+".f");
2762 FSI = InsertNewInstBefore(FSI, I);
2763
2764 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002765 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002766 }
2767 }
2768 return 0;
2769}
2770
2771Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2772 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2773
2774 // Handle the integer div common cases
2775 if (Instruction *Common = commonIDivTransforms(I))
2776 return Common;
2777
2778 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2779 // sdiv X, -1 == -X
2780 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782
2783 // -X/C -> X/-C
2784 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 }
2787
2788 // If the sign bits of both operands are zero (i.e. we can prove they are
2789 // unsigned inputs), turn this into a udiv.
2790 if (I.getType()->isInteger()) {
2791 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2792 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002793 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002794 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795 }
2796 }
2797
2798 return 0;
2799}
2800
2801Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2802 return commonDivTransforms(I);
2803}
2804
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805/// This function implements the transforms on rem instructions that work
2806/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2807/// is used by the visitors to those instructions.
2808/// @brief Transforms common to all three rem instructions
2809Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2810 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2811
Chris Lattner653ef3c2008-02-19 06:12:18 +00002812 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 if (Constant *LHS = dyn_cast<Constant>(Op0))
2814 if (LHS->isNullValue())
2815 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2816
Chris Lattner653ef3c2008-02-19 06:12:18 +00002817 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2818 if (I.getType()->isFPOrFPVector())
2819 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002820 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002821 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 if (isa<UndefValue>(Op1))
2823 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2824
2825 // Handle cases involving: rem X, (select Cond, Y, Z)
2826 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2827 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2828 // the same basic block, then we replace the select with Y, and the
2829 // condition of the select with false (if the cond value is in the same
2830 // BB). If the select has uses other than the div, this allows them to be
2831 // simplified also.
2832 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2833 if (ST->isNullValue()) {
2834 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2835 if (CondI && CondI->getParent() == I.getParent())
2836 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2837 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2838 I.setOperand(1, SI->getOperand(2));
2839 else
2840 UpdateValueUsesWith(SI, SI->getOperand(2));
2841 return &I;
2842 }
2843 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2844 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2845 if (ST->isNullValue()) {
2846 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2847 if (CondI && CondI->getParent() == I.getParent())
2848 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2849 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2850 I.setOperand(1, SI->getOperand(1));
2851 else
2852 UpdateValueUsesWith(SI, SI->getOperand(1));
2853 return &I;
2854 }
2855 }
2856
2857 return 0;
2858}
2859
2860/// This function implements the transforms common to both integer remainder
2861/// instructions (urem and srem). It is called by the visitors to those integer
2862/// remainder instructions.
2863/// @brief Common integer remainder transforms
2864Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2865 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2866
2867 if (Instruction *common = commonRemTransforms(I))
2868 return common;
2869
2870 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2871 // X % 0 == undef, we don't need to preserve faults!
2872 if (RHS->equalsInt(0))
2873 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2874
2875 if (RHS->equalsInt(1)) // X % 1 == 0
2876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2877
2878 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2879 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2880 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2881 return R;
2882 } else if (isa<PHINode>(Op0I)) {
2883 if (Instruction *NV = FoldOpIntoPhi(I))
2884 return NV;
2885 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002886
2887 // See if we can fold away this rem instruction.
2888 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2889 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2890 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2891 KnownZero, KnownOne))
2892 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 }
2894 }
2895
2896 return 0;
2897}
2898
2899Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2900 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
2902 if (Instruction *common = commonIRemTransforms(I))
2903 return common;
2904
2905 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2906 // X urem C^2 -> X and C
2907 // Check to see if this is an unsigned remainder with an exact power of 2,
2908 // if so, convert to a bitwise and.
2909 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2910 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00002911 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 }
2913
2914 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2915 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2916 if (RHSI->getOpcode() == Instruction::Shl &&
2917 isa<ConstantInt>(RHSI->getOperand(0))) {
2918 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2919 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00002920 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002922 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923 }
2924 }
2925 }
2926
2927 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2928 // where C1&C2 are powers of two.
2929 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2930 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2931 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2932 // STO == 0 and SFO == 0 handled above.
2933 if ((STO->getValue().isPowerOf2()) &&
2934 (SFO->getValue().isPowerOf2())) {
2935 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002936 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002938 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002939 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 }
2941 }
2942 }
2943
2944 return 0;
2945}
2946
2947Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2948 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2949
Dan Gohmandb3dd962007-11-05 23:16:33 +00002950 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951 if (Instruction *common = commonIRemTransforms(I))
2952 return common;
2953
2954 if (Value *RHSNeg = dyn_castNegVal(Op1))
2955 if (!isa<ConstantInt>(RHSNeg) ||
2956 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2957 // X % -Y -> X % Y
2958 AddUsesToWorkList(I);
2959 I.setOperand(1, RHSNeg);
2960 return &I;
2961 }
2962
Dan Gohmandb3dd962007-11-05 23:16:33 +00002963 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002964 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002965 if (I.getType()->isInteger()) {
2966 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2967 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2968 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002969 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00002970 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971 }
2972
2973 return 0;
2974}
2975
2976Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2977 return commonRemTransforms(I);
2978}
2979
2980// isMaxValueMinusOne - return true if this is Max-1
2981static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2982 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2983 if (!isSigned)
2984 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2985 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2986}
2987
2988// isMinValuePlusOne - return true if this is Min+1
2989static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2990 if (!isSigned)
2991 return C->getValue() == 1; // unsigned
2992
2993 // Calculate 1111111111000000000000
2994 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2995 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2996}
2997
2998// isOneBitSet - Return true if there is exactly one bit set in the specified
2999// constant.
3000static bool isOneBitSet(const ConstantInt *CI) {
3001 return CI->getValue().isPowerOf2();
3002}
3003
3004// isHighOnes - Return true if the constant is of the form 1+0+.
3005// This is the same as lowones(~X).
3006static bool isHighOnes(const ConstantInt *CI) {
3007 return (~CI->getValue() + 1).isPowerOf2();
3008}
3009
3010/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3011/// are carefully arranged to allow folding of expressions such as:
3012///
3013/// (A < B) | (A > B) --> (A != B)
3014///
3015/// Note that this is only valid if the first and second predicates have the
3016/// same sign. Is illegal to do: (A u< B) | (A s> B)
3017///
3018/// Three bits are used to represent the condition, as follows:
3019/// 0 A > B
3020/// 1 A == B
3021/// 2 A < B
3022///
3023/// <=> Value Definition
3024/// 000 0 Always false
3025/// 001 1 A > B
3026/// 010 2 A == B
3027/// 011 3 A >= B
3028/// 100 4 A < B
3029/// 101 5 A != B
3030/// 110 6 A <= B
3031/// 111 7 Always true
3032///
3033static unsigned getICmpCode(const ICmpInst *ICI) {
3034 switch (ICI->getPredicate()) {
3035 // False -> 0
3036 case ICmpInst::ICMP_UGT: return 1; // 001
3037 case ICmpInst::ICMP_SGT: return 1; // 001
3038 case ICmpInst::ICMP_EQ: return 2; // 010
3039 case ICmpInst::ICMP_UGE: return 3; // 011
3040 case ICmpInst::ICMP_SGE: return 3; // 011
3041 case ICmpInst::ICMP_ULT: return 4; // 100
3042 case ICmpInst::ICMP_SLT: return 4; // 100
3043 case ICmpInst::ICMP_NE: return 5; // 101
3044 case ICmpInst::ICMP_ULE: return 6; // 110
3045 case ICmpInst::ICMP_SLE: return 6; // 110
3046 // True -> 7
3047 default:
3048 assert(0 && "Invalid ICmp predicate!");
3049 return 0;
3050 }
3051}
3052
3053/// getICmpValue - This is the complement of getICmpCode, which turns an
3054/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003055/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056/// of predicate to use in new icmp instructions.
3057static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3058 switch (code) {
3059 default: assert(0 && "Illegal ICmp code!");
3060 case 0: return ConstantInt::getFalse();
3061 case 1:
3062 if (sign)
3063 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3064 else
3065 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3066 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3067 case 3:
3068 if (sign)
3069 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3070 else
3071 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3072 case 4:
3073 if (sign)
3074 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3075 else
3076 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3077 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3078 case 6:
3079 if (sign)
3080 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3081 else
3082 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3083 case 7: return ConstantInt::getTrue();
3084 }
3085}
3086
3087static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3088 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3089 (ICmpInst::isSignedPredicate(p1) &&
3090 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3091 (ICmpInst::isSignedPredicate(p2) &&
3092 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3093}
3094
3095namespace {
3096// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3097struct FoldICmpLogical {
3098 InstCombiner &IC;
3099 Value *LHS, *RHS;
3100 ICmpInst::Predicate pred;
3101 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3102 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3103 pred(ICI->getPredicate()) {}
3104 bool shouldApply(Value *V) const {
3105 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3106 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003107 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3108 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 return false;
3110 }
3111 Instruction *apply(Instruction &Log) const {
3112 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3113 if (ICI->getOperand(0) != LHS) {
3114 assert(ICI->getOperand(1) == LHS);
3115 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3116 }
3117
3118 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3119 unsigned LHSCode = getICmpCode(ICI);
3120 unsigned RHSCode = getICmpCode(RHSICI);
3121 unsigned Code;
3122 switch (Log.getOpcode()) {
3123 case Instruction::And: Code = LHSCode & RHSCode; break;
3124 case Instruction::Or: Code = LHSCode | RHSCode; break;
3125 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3126 default: assert(0 && "Illegal logical opcode!"); return 0;
3127 }
3128
3129 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3130 ICmpInst::isSignedPredicate(ICI->getPredicate());
3131
3132 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3133 if (Instruction *I = dyn_cast<Instruction>(RV))
3134 return I;
3135 // Otherwise, it's a constant boolean value...
3136 return IC.ReplaceInstUsesWith(Log, RV);
3137 }
3138};
3139} // end anonymous namespace
3140
3141// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3142// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3143// guaranteed to be a binary operator.
3144Instruction *InstCombiner::OptAndOp(Instruction *Op,
3145 ConstantInt *OpRHS,
3146 ConstantInt *AndRHS,
3147 BinaryOperator &TheAnd) {
3148 Value *X = Op->getOperand(0);
3149 Constant *Together = 0;
3150 if (!Op->isShift())
3151 Together = And(AndRHS, OpRHS);
3152
3153 switch (Op->getOpcode()) {
3154 case Instruction::Xor:
3155 if (Op->hasOneUse()) {
3156 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003157 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158 InsertNewInstBefore(And, TheAnd);
3159 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003160 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161 }
3162 break;
3163 case Instruction::Or:
3164 if (Together == AndRHS) // (X | C) & C --> C
3165 return ReplaceInstUsesWith(TheAnd, AndRHS);
3166
3167 if (Op->hasOneUse() && Together != OpRHS) {
3168 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003169 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003170 InsertNewInstBefore(Or, TheAnd);
3171 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003172 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 }
3174 break;
3175 case Instruction::Add:
3176 if (Op->hasOneUse()) {
3177 // Adding a one to a single bit bit-field should be turned into an XOR
3178 // of the bit. First thing to check is to see if this AND is with a
3179 // single bit constant.
3180 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3181
3182 // If there is only one bit set...
3183 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3184 // Ok, at this point, we know that we are masking the result of the
3185 // ADD down to exactly one bit. If the constant we are adding has
3186 // no bits set below this bit, then we can eliminate the ADD.
3187 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3188
3189 // Check to see if any bits below the one bit set in AndRHSV are set.
3190 if ((AddRHS & (AndRHSV-1)) == 0) {
3191 // If not, the only thing that can effect the output of the AND is
3192 // the bit specified by AndRHSV. If that bit is set, the effect of
3193 // the XOR is to toggle the bit. If it is clear, then the ADD has
3194 // no effect.
3195 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3196 TheAnd.setOperand(0, X);
3197 return &TheAnd;
3198 } else {
3199 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003200 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 InsertNewInstBefore(NewAnd, TheAnd);
3202 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003203 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 }
3205 }
3206 }
3207 }
3208 break;
3209
3210 case Instruction::Shl: {
3211 // We know that the AND will not produce any of the bits shifted in, so if
3212 // the anded constant includes them, clear them now!
3213 //
3214 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3215 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3216 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3217 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3218
3219 if (CI->getValue() == ShlMask) {
3220 // Masking out bits that the shift already masks
3221 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3222 } else if (CI != AndRHS) { // Reducing bits set in and.
3223 TheAnd.setOperand(1, CI);
3224 return &TheAnd;
3225 }
3226 break;
3227 }
3228 case Instruction::LShr:
3229 {
3230 // We know that the AND will not produce any of the bits shifted in, so if
3231 // the anded constant includes them, clear them now! This only applies to
3232 // unsigned shifts, because a signed shr may bring in set bits!
3233 //
3234 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3235 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3236 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3237 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3238
3239 if (CI->getValue() == ShrMask) {
3240 // Masking out bits that the shift already masks.
3241 return ReplaceInstUsesWith(TheAnd, Op);
3242 } else if (CI != AndRHS) {
3243 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3244 return &TheAnd;
3245 }
3246 break;
3247 }
3248 case Instruction::AShr:
3249 // Signed shr.
3250 // See if this is shifting in some sign extension, then masking it out
3251 // with an and.
3252 if (Op->hasOneUse()) {
3253 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3254 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3255 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3256 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3257 if (C == AndRHS) { // Masking out bits shifted in.
3258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3259 // Make the argument unsigned.
3260 Value *ShVal = Op->getOperand(0);
3261 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003262 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003264 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 }
3266 }
3267 break;
3268 }
3269 return 0;
3270}
3271
3272
3273/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3274/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3275/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3276/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3277/// insert new instructions.
3278Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3279 bool isSigned, bool Inside,
3280 Instruction &IB) {
3281 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3282 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3283 "Lo is not <= Hi in range emission code!");
3284
3285 if (Inside) {
3286 if (Lo == Hi) // Trivially false.
3287 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3288
3289 // V >= Min && V < Hi --> V < Hi
3290 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3291 ICmpInst::Predicate pred = (isSigned ?
3292 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3293 return new ICmpInst(pred, V, Hi);
3294 }
3295
3296 // Emit V-Lo <u Hi-Lo
3297 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003298 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003299 InsertNewInstBefore(Add, IB);
3300 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3301 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3302 }
3303
3304 if (Lo == Hi) // Trivially true.
3305 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3306
3307 // V < Min || V >= Hi -> V > Hi-1
3308 Hi = SubOne(cast<ConstantInt>(Hi));
3309 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3310 ICmpInst::Predicate pred = (isSigned ?
3311 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3312 return new ICmpInst(pred, V, Hi);
3313 }
3314
3315 // Emit V-Lo >u Hi-1-Lo
3316 // Note that Hi has already had one subtracted from it, above.
3317 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003318 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003319 InsertNewInstBefore(Add, IB);
3320 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3321 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3322}
3323
3324// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3325// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3326// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3327// not, since all 1s are not contiguous.
3328static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3329 const APInt& V = Val->getValue();
3330 uint32_t BitWidth = Val->getType()->getBitWidth();
3331 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3332
3333 // look for the first zero bit after the run of ones
3334 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3335 // look for the first non-zero bit
3336 ME = V.getActiveBits();
3337 return true;
3338}
3339
3340/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3341/// where isSub determines whether the operator is a sub. If we can fold one of
3342/// the following xforms:
3343///
3344/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3345/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3346/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3347///
3348/// return (A +/- B).
3349///
3350Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3351 ConstantInt *Mask, bool isSub,
3352 Instruction &I) {
3353 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3354 if (!LHSI || LHSI->getNumOperands() != 2 ||
3355 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3356
3357 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3358
3359 switch (LHSI->getOpcode()) {
3360 default: return 0;
3361 case Instruction::And:
3362 if (And(N, Mask) == Mask) {
3363 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3364 if ((Mask->getValue().countLeadingZeros() +
3365 Mask->getValue().countPopulation()) ==
3366 Mask->getValue().getBitWidth())
3367 break;
3368
3369 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3370 // part, we don't need any explicit masks to take them out of A. If that
3371 // is all N is, ignore it.
3372 uint32_t MB = 0, ME = 0;
3373 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3374 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3375 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3376 if (MaskedValueIsZero(RHS, Mask))
3377 break;
3378 }
3379 }
3380 return 0;
3381 case Instruction::Or:
3382 case Instruction::Xor:
3383 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3384 if ((Mask->getValue().countLeadingZeros() +
3385 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3386 && And(N, Mask)->isZero())
3387 break;
3388 return 0;
3389 }
3390
3391 Instruction *New;
3392 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003393 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003394 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003395 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396 return InsertNewInstBefore(New, I);
3397}
3398
3399Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3400 bool Changed = SimplifyCommutative(I);
3401 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3402
3403 if (isa<UndefValue>(Op1)) // X & undef -> 0
3404 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3405
3406 // and X, X = X
3407 if (Op0 == Op1)
3408 return ReplaceInstUsesWith(I, Op1);
3409
3410 // See if we can simplify any instructions used by the instruction whose sole
3411 // purpose is to compute bits we don't care about.
3412 if (!isa<VectorType>(I.getType())) {
3413 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3414 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3415 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3416 KnownZero, KnownOne))
3417 return &I;
3418 } else {
3419 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3420 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3421 return ReplaceInstUsesWith(I, I.getOperand(0));
3422 } else if (isa<ConstantAggregateZero>(Op1)) {
3423 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3424 }
3425 }
3426
3427 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3428 const APInt& AndRHSMask = AndRHS->getValue();
3429 APInt NotAndRHS(~AndRHSMask);
3430
3431 // Optimize a variety of ((val OP C1) & C2) combinations...
3432 if (isa<BinaryOperator>(Op0)) {
3433 Instruction *Op0I = cast<Instruction>(Op0);
3434 Value *Op0LHS = Op0I->getOperand(0);
3435 Value *Op0RHS = Op0I->getOperand(1);
3436 switch (Op0I->getOpcode()) {
3437 case Instruction::Xor:
3438 case Instruction::Or:
3439 // If the mask is only needed on one incoming arm, push it up.
3440 if (Op0I->hasOneUse()) {
3441 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3442 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003443 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 Op0RHS->getName()+".masked");
3445 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003446 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3448 }
3449 if (!isa<Constant>(Op0RHS) &&
3450 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3451 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003452 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003453 Op0LHS->getName()+".masked");
3454 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003455 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3457 }
3458 }
3459
3460 break;
3461 case Instruction::Add:
3462 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3463 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3464 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3465 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003466 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003468 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469 break;
3470
3471 case Instruction::Sub:
3472 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3473 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3474 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3475 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003476 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003477 break;
3478 }
3479
3480 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3481 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3482 return Res;
3483 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3484 // If this is an integer truncation or change from signed-to-unsigned, and
3485 // if the source is an and/or with immediate, transform it. This
3486 // frequently occurs for bitfield accesses.
3487 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3488 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3489 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003490 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003491 if (CastOp->getOpcode() == Instruction::And) {
3492 // Change: and (cast (and X, C1) to T), C2
3493 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3494 // This will fold the two constants together, which may allow
3495 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003496 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497 CastOp->getOperand(0), I.getType(),
3498 CastOp->getName()+".shrunk");
3499 NewCast = InsertNewInstBefore(NewCast, I);
3500 // trunc_or_bitcast(C1)&C2
3501 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3502 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003503 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003504 } else if (CastOp->getOpcode() == Instruction::Or) {
3505 // Change: and (cast (or X, C1) to T), C2
3506 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3507 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3508 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3509 return ReplaceInstUsesWith(I, AndRHS);
3510 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 }
3513 }
3514
3515 // Try to fold constant and into select arguments.
3516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3518 return R;
3519 if (isa<PHINode>(Op0))
3520 if (Instruction *NV = FoldOpIntoPhi(I))
3521 return NV;
3522 }
3523
3524 Value *Op0NotVal = dyn_castNotVal(Op0);
3525 Value *Op1NotVal = dyn_castNotVal(Op1);
3526
3527 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3528 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3529
3530 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3531 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003532 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 I.getName()+".demorgan");
3534 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003535 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 }
3537
3538 {
3539 Value *A = 0, *B = 0, *C = 0, *D = 0;
3540 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3541 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3542 return ReplaceInstUsesWith(I, Op1);
3543
3544 // (A|B) & ~(A&B) -> A^B
3545 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3546 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003547 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548 }
3549 }
3550
3551 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3552 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3553 return ReplaceInstUsesWith(I, Op0);
3554
3555 // ~(A&B) & (A|B) -> A^B
3556 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3557 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003558 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003559 }
3560 }
3561
3562 if (Op0->hasOneUse() &&
3563 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3564 if (A == Op1) { // (A^B)&A -> A&(A^B)
3565 I.swapOperands(); // Simplify below
3566 std::swap(Op0, Op1);
3567 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3568 cast<BinaryOperator>(Op0)->swapOperands();
3569 I.swapOperands(); // Simplify below
3570 std::swap(Op0, Op1);
3571 }
3572 }
3573 if (Op1->hasOneUse() &&
3574 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3575 if (B == Op0) { // B&(A^B) -> B&(B^A)
3576 cast<BinaryOperator>(Op1)->swapOperands();
3577 std::swap(A, B);
3578 }
3579 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003580 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003582 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003583 }
3584 }
3585 }
3586
3587 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3588 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3589 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3590 return R;
3591
3592 Value *LHSVal, *RHSVal;
3593 ConstantInt *LHSCst, *RHSCst;
3594 ICmpInst::Predicate LHSCC, RHSCC;
3595 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3596 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3597 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3598 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3599 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3600 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3601 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003602 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3603
3604 // Don't try to fold ICMP_SLT + ICMP_ULT.
3605 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3606 ICmpInst::isSignedPredicate(LHSCC) ==
3607 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003609 ICmpInst::Predicate GT;
3610 if (ICmpInst::isSignedPredicate(LHSCC) ||
3611 (ICmpInst::isEquality(LHSCC) &&
3612 ICmpInst::isSignedPredicate(RHSCC)))
3613 GT = ICmpInst::ICMP_SGT;
3614 else
3615 GT = ICmpInst::ICMP_UGT;
3616
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003617 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3618 ICmpInst *LHS = cast<ICmpInst>(Op0);
3619 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3620 std::swap(LHS, RHS);
3621 std::swap(LHSCst, RHSCst);
3622 std::swap(LHSCC, RHSCC);
3623 }
3624
3625 // At this point, we know we have have two icmp instructions
3626 // comparing a value against two constants and and'ing the result
3627 // together. Because of the above check, we know that we only have
3628 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3629 // (from the FoldICmpLogical check above), that the two constants
3630 // are not equal and that the larger constant is on the RHS
3631 assert(LHSCst != RHSCst && "Compares not folded above?");
3632
3633 switch (LHSCC) {
3634 default: assert(0 && "Unknown integer condition code!");
3635 case ICmpInst::ICMP_EQ:
3636 switch (RHSCC) {
3637 default: assert(0 && "Unknown integer condition code!");
3638 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3639 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3640 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3641 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3642 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3643 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3644 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3645 return ReplaceInstUsesWith(I, LHS);
3646 }
3647 case ICmpInst::ICMP_NE:
3648 switch (RHSCC) {
3649 default: assert(0 && "Unknown integer condition code!");
3650 case ICmpInst::ICMP_ULT:
3651 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3652 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3653 break; // (X != 13 & X u< 15) -> no change
3654 case ICmpInst::ICMP_SLT:
3655 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3656 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3657 break; // (X != 13 & X s< 15) -> no change
3658 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3659 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3660 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3661 return ReplaceInstUsesWith(I, RHS);
3662 case ICmpInst::ICMP_NE:
3663 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3664 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00003665 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003666 LHSVal->getName()+".off");
3667 InsertNewInstBefore(Add, I);
3668 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3669 ConstantInt::get(Add->getType(), 1));
3670 }
3671 break; // (X != 13 & X != 15) -> no change
3672 }
3673 break;
3674 case ICmpInst::ICMP_ULT:
3675 switch (RHSCC) {
3676 default: assert(0 && "Unknown integer condition code!");
3677 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3678 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3679 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3680 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3681 break;
3682 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3683 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3684 return ReplaceInstUsesWith(I, LHS);
3685 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3686 break;
3687 }
3688 break;
3689 case ICmpInst::ICMP_SLT:
3690 switch (RHSCC) {
3691 default: assert(0 && "Unknown integer condition code!");
3692 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3693 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3694 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3695 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3696 break;
3697 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3698 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3699 return ReplaceInstUsesWith(I, LHS);
3700 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3701 break;
3702 }
3703 break;
3704 case ICmpInst::ICMP_UGT:
3705 switch (RHSCC) {
3706 default: assert(0 && "Unknown integer condition code!");
3707 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3708 return ReplaceInstUsesWith(I, LHS);
3709 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3710 return ReplaceInstUsesWith(I, RHS);
3711 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3712 break;
3713 case ICmpInst::ICMP_NE:
3714 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3715 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3716 break; // (X u> 13 & X != 15) -> no change
3717 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3718 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3719 true, I);
3720 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3721 break;
3722 }
3723 break;
3724 case ICmpInst::ICMP_SGT:
3725 switch (RHSCC) {
3726 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003727 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3729 return ReplaceInstUsesWith(I, RHS);
3730 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3731 break;
3732 case ICmpInst::ICMP_NE:
3733 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3734 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3735 break; // (X s> 13 & X != 15) -> no change
3736 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3737 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3738 true, I);
3739 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3740 break;
3741 }
3742 break;
3743 }
3744 }
3745 }
3746
3747 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3748 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3749 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3750 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3751 const Type *SrcTy = Op0C->getOperand(0)->getType();
3752 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3753 // Only do this if the casts both really cause code to be generated.
3754 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3755 I.getType(), TD) &&
3756 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3757 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003758 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759 Op1C->getOperand(0),
3760 I.getName());
3761 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003762 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763 }
3764 }
3765
3766 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3767 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3768 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3769 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3770 SI0->getOperand(1) == SI1->getOperand(1) &&
3771 (SI0->hasOneUse() || SI1->hasOneUse())) {
3772 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00003773 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003774 SI1->getOperand(0),
3775 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003776 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003777 SI1->getOperand(1));
3778 }
3779 }
3780
Chris Lattner91882432007-10-24 05:38:08 +00003781 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3782 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3783 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3784 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3785 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3786 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3787 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3788 // If either of the constants are nans, then the whole thing returns
3789 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003790 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003791 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3792 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3793 RHS->getOperand(0));
3794 }
3795 }
3796 }
3797
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 return Changed ? &I : 0;
3799}
3800
3801/// CollectBSwapParts - Look to see if the specified value defines a single byte
3802/// in the result. If it does, and if the specified byte hasn't been filled in
3803/// yet, fill it in and return false.
3804static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3805 Instruction *I = dyn_cast<Instruction>(V);
3806 if (I == 0) return true;
3807
3808 // If this is an or instruction, it is an inner node of the bswap.
3809 if (I->getOpcode() == Instruction::Or)
3810 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3811 CollectBSwapParts(I->getOperand(1), ByteValues);
3812
3813 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3814 // If this is a shift by a constant int, and it is "24", then its operand
3815 // defines a byte. We only handle unsigned types here.
3816 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3817 // Not shifting the entire input by N-1 bytes?
3818 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3819 8*(ByteValues.size()-1))
3820 return true;
3821
3822 unsigned DestNo;
3823 if (I->getOpcode() == Instruction::Shl) {
3824 // X << 24 defines the top byte with the lowest of the input bytes.
3825 DestNo = ByteValues.size()-1;
3826 } else {
3827 // X >>u 24 defines the low byte with the highest of the input bytes.
3828 DestNo = 0;
3829 }
3830
3831 // If the destination byte value is already defined, the values are or'd
3832 // together, which isn't a bswap (unless it's an or of the same bits).
3833 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3834 return true;
3835 ByteValues[DestNo] = I->getOperand(0);
3836 return false;
3837 }
3838
3839 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3840 // don't have this.
3841 Value *Shift = 0, *ShiftLHS = 0;
3842 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3843 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3844 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3845 return true;
3846 Instruction *SI = cast<Instruction>(Shift);
3847
3848 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3849 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3850 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3851 return true;
3852
3853 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3854 unsigned DestByte;
3855 if (AndAmt->getValue().getActiveBits() > 64)
3856 return true;
3857 uint64_t AndAmtVal = AndAmt->getZExtValue();
3858 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3859 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3860 break;
3861 // Unknown mask for bswap.
3862 if (DestByte == ByteValues.size()) return true;
3863
3864 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3865 unsigned SrcByte;
3866 if (SI->getOpcode() == Instruction::Shl)
3867 SrcByte = DestByte - ShiftBytes;
3868 else
3869 SrcByte = DestByte + ShiftBytes;
3870
3871 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3872 if (SrcByte != ByteValues.size()-DestByte-1)
3873 return true;
3874
3875 // If the destination byte value is already defined, the values are or'd
3876 // together, which isn't a bswap (unless it's an or of the same bits).
3877 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3878 return true;
3879 ByteValues[DestByte] = SI->getOperand(0);
3880 return false;
3881}
3882
3883/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3884/// If so, insert the new bswap intrinsic and return it.
3885Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3886 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3887 if (!ITy || ITy->getBitWidth() % 16)
3888 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3889
3890 /// ByteValues - For each byte of the result, we keep track of which value
3891 /// defines each byte.
3892 SmallVector<Value*, 8> ByteValues;
3893 ByteValues.resize(ITy->getBitWidth()/8);
3894
3895 // Try to find all the pieces corresponding to the bswap.
3896 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3897 CollectBSwapParts(I.getOperand(1), ByteValues))
3898 return 0;
3899
3900 // Check to see if all of the bytes come from the same value.
3901 Value *V = ByteValues[0];
3902 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3903
3904 // Check to make sure that all of the bytes come from the same value.
3905 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3906 if (ByteValues[i] != V)
3907 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003908 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003910 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003911 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003912}
3913
3914
3915Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3916 bool Changed = SimplifyCommutative(I);
3917 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3918
3919 if (isa<UndefValue>(Op1)) // X | undef -> -1
3920 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3921
3922 // or X, X = X
3923 if (Op0 == Op1)
3924 return ReplaceInstUsesWith(I, Op0);
3925
3926 // See if we can simplify any instructions used by the instruction whose sole
3927 // purpose is to compute bits we don't care about.
3928 if (!isa<VectorType>(I.getType())) {
3929 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3930 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3931 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3932 KnownZero, KnownOne))
3933 return &I;
3934 } else if (isa<ConstantAggregateZero>(Op1)) {
3935 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3936 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3937 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3938 return ReplaceInstUsesWith(I, I.getOperand(1));
3939 }
3940
3941
3942
3943 // or X, -1 == -1
3944 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3945 ConstantInt *C1 = 0; Value *X = 0;
3946 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3947 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003948 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949 InsertNewInstBefore(Or, I);
3950 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003951 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952 ConstantInt::get(RHS->getValue() | C1->getValue()));
3953 }
3954
3955 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3956 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003957 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003958 InsertNewInstBefore(Or, I);
3959 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003960 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003961 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3962 }
3963
3964 // Try to fold constant and into select arguments.
3965 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3967 return R;
3968 if (isa<PHINode>(Op0))
3969 if (Instruction *NV = FoldOpIntoPhi(I))
3970 return NV;
3971 }
3972
3973 Value *A = 0, *B = 0;
3974 ConstantInt *C1 = 0, *C2 = 0;
3975
3976 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3977 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3978 return ReplaceInstUsesWith(I, Op1);
3979 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3980 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3981 return ReplaceInstUsesWith(I, Op0);
3982
3983 // (A | B) | C and A | (B | C) -> bswap if possible.
3984 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3985 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3986 match(Op1, m_Or(m_Value(), m_Value())) ||
3987 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3988 match(Op1, m_Shift(m_Value(), m_Value())))) {
3989 if (Instruction *BSwap = MatchBSwap(I))
3990 return BSwap;
3991 }
3992
3993 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3994 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3995 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003996 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 InsertNewInstBefore(NOr, I);
3998 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003999 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004000 }
4001
4002 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4003 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4004 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004005 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004006 InsertNewInstBefore(NOr, I);
4007 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004008 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 }
4010
4011 // (A & C)|(B & D)
4012 Value *C = 0, *D = 0;
4013 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4014 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4015 Value *V1 = 0, *V2 = 0, *V3 = 0;
4016 C1 = dyn_cast<ConstantInt>(C);
4017 C2 = dyn_cast<ConstantInt>(D);
4018 if (C1 && C2) { // (A & C1)|(B & C2)
4019 // If we have: ((V + N) & C1) | (V & C2)
4020 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4021 // replace with V+N.
4022 if (C1->getValue() == ~C2->getValue()) {
4023 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4024 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4025 // Add commutes, try both ways.
4026 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4027 return ReplaceInstUsesWith(I, A);
4028 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4029 return ReplaceInstUsesWith(I, A);
4030 }
4031 // Or commutes, try both ways.
4032 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4033 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4034 // Add commutes, try both ways.
4035 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4036 return ReplaceInstUsesWith(I, B);
4037 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4038 return ReplaceInstUsesWith(I, B);
4039 }
4040 }
4041 V1 = 0; V2 = 0; V3 = 0;
4042 }
4043
4044 // Check to see if we have any common things being and'ed. If so, find the
4045 // terms for V1 & (V2|V3).
4046 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4047 if (A == B) // (A & C)|(A & D) == A & (C|D)
4048 V1 = A, V2 = C, V3 = D;
4049 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4050 V1 = A, V2 = B, V3 = C;
4051 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4052 V1 = C, V2 = A, V3 = D;
4053 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4054 V1 = C, V2 = A, V3 = B;
4055
4056 if (V1) {
4057 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004058 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4059 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004060 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004061 }
4062 }
4063
4064 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4065 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4066 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4067 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4068 SI0->getOperand(1) == SI1->getOperand(1) &&
4069 (SI0->hasOneUse() || SI1->hasOneUse())) {
4070 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004071 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072 SI1->getOperand(0),
4073 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004074 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004075 SI1->getOperand(1));
4076 }
4077 }
4078
4079 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4080 if (A == Op1) // ~A | A == -1
4081 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4082 } else {
4083 A = 0;
4084 }
4085 // Note, A is still live here!
4086 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4087 if (Op0 == B)
4088 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4089
4090 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4091 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004092 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004094 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095 }
4096 }
4097
4098 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4099 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4100 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4101 return R;
4102
4103 Value *LHSVal, *RHSVal;
4104 ConstantInt *LHSCst, *RHSCst;
4105 ICmpInst::Predicate LHSCC, RHSCC;
4106 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4107 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4108 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4109 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4110 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4111 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4112 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4113 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4114 // We can't fold (ugt x, C) | (sgt x, C2).
4115 PredicatesFoldable(LHSCC, RHSCC)) {
4116 // Ensure that the larger constant is on the RHS.
4117 ICmpInst *LHS = cast<ICmpInst>(Op0);
4118 bool NeedsSwap;
4119 if (ICmpInst::isSignedPredicate(LHSCC))
4120 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4121 else
4122 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4123
4124 if (NeedsSwap) {
4125 std::swap(LHS, RHS);
4126 std::swap(LHSCst, RHSCst);
4127 std::swap(LHSCC, RHSCC);
4128 }
4129
4130 // At this point, we know we have have two icmp instructions
4131 // comparing a value against two constants and or'ing the result
4132 // together. Because of the above check, we know that we only have
4133 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4134 // FoldICmpLogical check above), that the two constants are not
4135 // equal.
4136 assert(LHSCst != RHSCst && "Compares not folded above?");
4137
4138 switch (LHSCC) {
4139 default: assert(0 && "Unknown integer condition code!");
4140 case ICmpInst::ICMP_EQ:
4141 switch (RHSCC) {
4142 default: assert(0 && "Unknown integer condition code!");
4143 case ICmpInst::ICMP_EQ:
4144 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4145 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004146 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 LHSVal->getName()+".off");
4148 InsertNewInstBefore(Add, I);
4149 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4150 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4151 }
4152 break; // (X == 13 | X == 15) -> no change
4153 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4154 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4155 break;
4156 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4157 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4158 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4159 return ReplaceInstUsesWith(I, RHS);
4160 }
4161 break;
4162 case ICmpInst::ICMP_NE:
4163 switch (RHSCC) {
4164 default: assert(0 && "Unknown integer condition code!");
4165 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4166 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4167 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4168 return ReplaceInstUsesWith(I, LHS);
4169 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4170 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4171 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4172 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4173 }
4174 break;
4175 case ICmpInst::ICMP_ULT:
4176 switch (RHSCC) {
4177 default: assert(0 && "Unknown integer condition code!");
4178 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4179 break;
4180 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004181 // If RHSCst is [us]MAXINT, it is always false. Not handling
4182 // this can cause overflow.
4183 if (RHSCst->isMaxValue(false))
4184 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4186 false, I);
4187 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4188 break;
4189 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4190 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4191 return ReplaceInstUsesWith(I, RHS);
4192 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4193 break;
4194 }
4195 break;
4196 case ICmpInst::ICMP_SLT:
4197 switch (RHSCC) {
4198 default: assert(0 && "Unknown integer condition code!");
4199 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4200 break;
4201 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004202 // If RHSCst is [us]MAXINT, it is always false. Not handling
4203 // this can cause overflow.
4204 if (RHSCst->isMaxValue(true))
4205 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4207 false, I);
4208 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4209 break;
4210 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4211 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4212 return ReplaceInstUsesWith(I, RHS);
4213 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4214 break;
4215 }
4216 break;
4217 case ICmpInst::ICMP_UGT:
4218 switch (RHSCC) {
4219 default: assert(0 && "Unknown integer condition code!");
4220 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4221 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4222 return ReplaceInstUsesWith(I, LHS);
4223 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4224 break;
4225 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4226 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4227 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4228 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4229 break;
4230 }
4231 break;
4232 case ICmpInst::ICMP_SGT:
4233 switch (RHSCC) {
4234 default: assert(0 && "Unknown integer condition code!");
4235 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4236 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4237 return ReplaceInstUsesWith(I, LHS);
4238 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4239 break;
4240 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4241 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4242 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4243 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4244 break;
4245 }
4246 break;
4247 }
4248 }
4249 }
4250
4251 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004252 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4254 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004255 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4256 !isa<ICmpInst>(Op1C->getOperand(0))) {
4257 const Type *SrcTy = Op0C->getOperand(0)->getType();
4258 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4259 // Only do this if the casts both really cause code to be
4260 // generated.
4261 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4262 I.getType(), TD) &&
4263 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4264 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004265 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004266 Op1C->getOperand(0),
4267 I.getName());
4268 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004269 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004270 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004271 }
4272 }
Chris Lattner91882432007-10-24 05:38:08 +00004273 }
4274
4275
4276 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4277 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4278 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4279 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004280 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4281 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004282 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4283 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4284 // If either of the constants are nans, then the whole thing returns
4285 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004286 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004287 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4288
4289 // Otherwise, no need to compare the two constants, compare the
4290 // rest.
4291 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4292 RHS->getOperand(0));
4293 }
4294 }
4295 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004296
4297 return Changed ? &I : 0;
4298}
4299
Dan Gohman089efff2008-05-13 00:00:25 +00004300namespace {
4301
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004302// XorSelf - Implements: X ^ X --> 0
4303struct XorSelf {
4304 Value *RHS;
4305 XorSelf(Value *rhs) : RHS(rhs) {}
4306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4307 Instruction *apply(BinaryOperator &Xor) const {
4308 return &Xor;
4309 }
4310};
4311
Dan Gohman089efff2008-05-13 00:00:25 +00004312}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313
4314Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4315 bool Changed = SimplifyCommutative(I);
4316 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4317
Evan Chenge5cd8032008-03-25 20:07:13 +00004318 if (isa<UndefValue>(Op1)) {
4319 if (isa<UndefValue>(Op0))
4320 // Handle undef ^ undef -> 0 special case. This is a common
4321 // idiom (misuse).
4322 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004323 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004324 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004325
4326 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4327 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004328 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4330 }
4331
4332 // See if we can simplify any instructions used by the instruction whose sole
4333 // purpose is to compute bits we don't care about.
4334 if (!isa<VectorType>(I.getType())) {
4335 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4336 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4337 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4338 KnownZero, KnownOne))
4339 return &I;
4340 } else if (isa<ConstantAggregateZero>(Op1)) {
4341 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4342 }
4343
4344 // Is this a ~ operation?
4345 if (Value *NotOp = dyn_castNotVal(&I)) {
4346 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4347 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4348 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4349 if (Op0I->getOpcode() == Instruction::And ||
4350 Op0I->getOpcode() == Instruction::Or) {
4351 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4352 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4353 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004354 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004355 Op0I->getOperand(1)->getName()+".not");
4356 InsertNewInstBefore(NotY, I);
4357 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004358 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004360 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004361 }
4362 }
4363 }
4364 }
4365
4366
4367 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004368 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4369 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4370 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371 return new ICmpInst(ICI->getInversePredicate(),
4372 ICI->getOperand(0), ICI->getOperand(1));
4373
Nick Lewycky1405e922007-08-06 20:04:16 +00004374 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4375 return new FCmpInst(FCI->getInversePredicate(),
4376 FCI->getOperand(0), FCI->getOperand(1));
4377 }
4378
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004379 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4380 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4381 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4382 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4383 Instruction::CastOps Opcode = Op0C->getOpcode();
4384 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4385 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4386 Op0C->getDestTy())) {
4387 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4388 CI->getOpcode(), CI->getInversePredicate(),
4389 CI->getOperand(0), CI->getOperand(1)), I);
4390 NewCI->takeName(CI);
4391 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4392 }
4393 }
4394 }
4395 }
4396 }
4397
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004398 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4399 // ~(c-X) == X-c-1 == X+(-c-1)
4400 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4401 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4402 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4403 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4404 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004405 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406 }
4407
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004408 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 if (Op0I->getOpcode() == Instruction::Add) {
4410 // ~(X-c) --> (-c-1)-X
4411 if (RHS->isAllOnesValue()) {
4412 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004413 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 ConstantExpr::getSub(NegOp0CI,
4415 ConstantInt::get(I.getType(), 1)),
4416 Op0I->getOperand(0));
4417 } else if (RHS->getValue().isSignBit()) {
4418 // (X + C) ^ signbit -> (X + C + signbit)
4419 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004420 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421
4422 }
4423 } else if (Op0I->getOpcode() == Instruction::Or) {
4424 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4425 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4426 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4427 // Anything in both C1 and C2 is known to be zero, remove it from
4428 // NewRHS.
4429 Constant *CommonBits = And(Op0CI, RHS);
4430 NewRHS = ConstantExpr::getAnd(NewRHS,
4431 ConstantExpr::getNot(CommonBits));
4432 AddToWorkList(Op0I);
4433 I.setOperand(0, Op0I->getOperand(0));
4434 I.setOperand(1, NewRHS);
4435 return &I;
4436 }
4437 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004438 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004439 }
4440
4441 // Try to fold constant and into select arguments.
4442 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4443 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4444 return R;
4445 if (isa<PHINode>(Op0))
4446 if (Instruction *NV = FoldOpIntoPhi(I))
4447 return NV;
4448 }
4449
4450 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4451 if (X == Op1)
4452 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4453
4454 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4455 if (X == Op0)
4456 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4457
4458
4459 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4460 if (Op1I) {
4461 Value *A, *B;
4462 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4463 if (A == Op0) { // B^(B|A) == (A|B)^B
4464 Op1I->swapOperands();
4465 I.swapOperands();
4466 std::swap(Op0, Op1);
4467 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4468 I.swapOperands(); // Simplified below.
4469 std::swap(Op0, Op1);
4470 }
4471 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4472 if (Op0 == A) // A^(A^B) == B
4473 return ReplaceInstUsesWith(I, B);
4474 else if (Op0 == B) // A^(B^A) == B
4475 return ReplaceInstUsesWith(I, A);
4476 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4477 if (A == Op0) { // A^(A&B) -> A^(B&A)
4478 Op1I->swapOperands();
4479 std::swap(A, B);
4480 }
4481 if (B == Op0) { // A^(B&A) -> (B&A)^A
4482 I.swapOperands(); // Simplified below.
4483 std::swap(Op0, Op1);
4484 }
4485 }
4486 }
4487
4488 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4489 if (Op0I) {
4490 Value *A, *B;
4491 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4492 if (A == Op1) // (B|A)^B == (A|B)^B
4493 std::swap(A, B);
4494 if (B == Op1) { // (A|B)^B == A & ~B
4495 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004496 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4497 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004498 }
4499 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4500 if (Op1 == A) // (A^B)^A == B
4501 return ReplaceInstUsesWith(I, B);
4502 else if (Op1 == B) // (B^A)^A == B
4503 return ReplaceInstUsesWith(I, A);
4504 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4505 if (A == Op1) // (A&B)^A -> (B&A)^A
4506 std::swap(A, B);
4507 if (B == Op1 && // (B&A)^A == ~B & A
4508 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4509 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004510 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4511 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512 }
4513 }
4514 }
4515
4516 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4517 if (Op0I && Op1I && Op0I->isShift() &&
4518 Op0I->getOpcode() == Op1I->getOpcode() &&
4519 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4520 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4521 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004522 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 Op1I->getOperand(0),
4524 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004525 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004526 Op1I->getOperand(1));
4527 }
4528
4529 if (Op0I && Op1I) {
4530 Value *A, *B, *C, *D;
4531 // (A & B)^(A | B) -> A ^ B
4532 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4533 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4534 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004535 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004536 }
4537 // (A | B)^(A & B) -> A ^ B
4538 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4539 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4540 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004541 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004542 }
4543
4544 // (A & B)^(C & D)
4545 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4546 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4547 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4548 // (X & Y)^(X & Y) -> (Y^Z) & X
4549 Value *X = 0, *Y = 0, *Z = 0;
4550 if (A == C)
4551 X = A, Y = B, Z = D;
4552 else if (A == D)
4553 X = A, Y = B, Z = C;
4554 else if (B == C)
4555 X = B, Y = A, Z = D;
4556 else if (B == D)
4557 X = B, Y = A, Z = C;
4558
4559 if (X) {
4560 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004561 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4562 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004563 }
4564 }
4565 }
4566
4567 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4568 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4569 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4570 return R;
4571
4572 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004573 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004574 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4575 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4576 const Type *SrcTy = Op0C->getOperand(0)->getType();
4577 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4578 // Only do this if the casts both really cause code to be generated.
4579 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4580 I.getType(), TD) &&
4581 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4582 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004583 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004584 Op1C->getOperand(0),
4585 I.getName());
4586 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004587 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004588 }
4589 }
Chris Lattner91882432007-10-24 05:38:08 +00004590 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004591
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004592 return Changed ? &I : 0;
4593}
4594
4595/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4596/// overflowed for this type.
4597static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4598 ConstantInt *In2, bool IsSigned = false) {
4599 Result = cast<ConstantInt>(Add(In1, In2));
4600
4601 if (IsSigned)
4602 if (In2->getValue().isNegative())
4603 return Result->getValue().sgt(In1->getValue());
4604 else
4605 return Result->getValue().slt(In1->getValue());
4606 else
4607 return Result->getValue().ult(In1->getValue());
4608}
4609
4610/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4611/// code necessary to compute the offset from the base pointer (without adding
4612/// in the base pointer). Return the result as a signed integer of intptr size.
4613static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4614 TargetData &TD = IC.getTargetData();
4615 gep_type_iterator GTI = gep_type_begin(GEP);
4616 const Type *IntPtrTy = TD.getIntPtrType();
4617 Value *Result = Constant::getNullValue(IntPtrTy);
4618
4619 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004620 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004621 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4622
4623 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4624 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004625 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004626 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4627 if (OpC->isZero()) continue;
4628
4629 // Handle a struct index, which adds its field offset to the pointer.
4630 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4631 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4632
4633 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4634 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4635 else
4636 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004637 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004638 ConstantInt::get(IntPtrTy, Size),
4639 GEP->getName()+".offs"), I);
4640 continue;
4641 }
4642
4643 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4644 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4645 Scale = ConstantExpr::getMul(OC, Scale);
4646 if (Constant *RC = dyn_cast<Constant>(Result))
4647 Result = ConstantExpr::getAdd(RC, Scale);
4648 else {
4649 // Emit an add instruction.
4650 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004651 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004652 GEP->getName()+".offs"), I);
4653 }
4654 continue;
4655 }
4656 // Convert to correct type.
4657 if (Op->getType() != IntPtrTy) {
4658 if (Constant *OpC = dyn_cast<Constant>(Op))
4659 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4660 else
4661 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4662 Op->getName()+".c"), I);
4663 }
4664 if (Size != 1) {
4665 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4666 if (Constant *OpC = dyn_cast<Constant>(Op))
4667 Op = ConstantExpr::getMul(OpC, Scale);
4668 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004669 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004670 GEP->getName()+".idx"), I);
4671 }
4672
4673 // Emit an add instruction.
4674 if (isa<Constant>(Op) && isa<Constant>(Result))
4675 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4676 cast<Constant>(Result));
4677 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004678 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004679 GEP->getName()+".offs"), I);
4680 }
4681 return Result;
4682}
4683
Chris Lattnereba75862008-04-22 02:53:33 +00004684
4685/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4686/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4687/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4688/// complex, and scales are involved. The above expression would also be legal
4689/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4690/// later form is less amenable to optimization though, and we are allowed to
4691/// generate the first by knowing that pointer arithmetic doesn't overflow.
4692///
4693/// If we can't emit an optimized form for this expression, this returns null.
4694///
4695static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4696 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00004697 TargetData &TD = IC.getTargetData();
4698 gep_type_iterator GTI = gep_type_begin(GEP);
4699
4700 // Check to see if this gep only has a single variable index. If so, and if
4701 // any constant indices are a multiple of its scale, then we can compute this
4702 // in terms of the scale of the variable index. For example, if the GEP
4703 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4704 // because the expression will cross zero at the same point.
4705 unsigned i, e = GEP->getNumOperands();
4706 int64_t Offset = 0;
4707 for (i = 1; i != e; ++i, ++GTI) {
4708 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4709 // Compute the aggregate offset of constant indices.
4710 if (CI->isZero()) continue;
4711
4712 // Handle a struct index, which adds its field offset to the pointer.
4713 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4714 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4715 } else {
4716 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4717 Offset += Size*CI->getSExtValue();
4718 }
4719 } else {
4720 // Found our variable index.
4721 break;
4722 }
4723 }
4724
4725 // If there are no variable indices, we must have a constant offset, just
4726 // evaluate it the general way.
4727 if (i == e) return 0;
4728
4729 Value *VariableIdx = GEP->getOperand(i);
4730 // Determine the scale factor of the variable element. For example, this is
4731 // 4 if the variable index is into an array of i32.
4732 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4733
4734 // Verify that there are no other variable indices. If so, emit the hard way.
4735 for (++i, ++GTI; i != e; ++i, ++GTI) {
4736 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4737 if (!CI) return 0;
4738
4739 // Compute the aggregate offset of constant indices.
4740 if (CI->isZero()) continue;
4741
4742 // Handle a struct index, which adds its field offset to the pointer.
4743 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4744 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4745 } else {
4746 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4747 Offset += Size*CI->getSExtValue();
4748 }
4749 }
4750
4751 // Okay, we know we have a single variable index, which must be a
4752 // pointer/array/vector index. If there is no offset, life is simple, return
4753 // the index.
4754 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4755 if (Offset == 0) {
4756 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4757 // we don't need to bother extending: the extension won't affect where the
4758 // computation crosses zero.
4759 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4760 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4761 VariableIdx->getNameStart(), &I);
4762 return VariableIdx;
4763 }
4764
4765 // Otherwise, there is an index. The computation we will do will be modulo
4766 // the pointer size, so get it.
4767 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4768
4769 Offset &= PtrSizeMask;
4770 VariableScale &= PtrSizeMask;
4771
4772 // To do this transformation, any constant index must be a multiple of the
4773 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4774 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4775 // multiple of the variable scale.
4776 int64_t NewOffs = Offset / (int64_t)VariableScale;
4777 if (Offset != NewOffs*(int64_t)VariableScale)
4778 return 0;
4779
4780 // Okay, we can do this evaluation. Start by converting the index to intptr.
4781 const Type *IntPtrTy = TD.getIntPtrType();
4782 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00004783 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00004784 true /*SExt*/,
4785 VariableIdx->getNameStart(), &I);
4786 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00004787 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00004788}
4789
4790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4792/// else. At this point we know that the GEP is on the LHS of the comparison.
4793Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4794 ICmpInst::Predicate Cond,
4795 Instruction &I) {
4796 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4797
Chris Lattnereba75862008-04-22 02:53:33 +00004798 // Look through bitcasts.
4799 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4800 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801
4802 Value *PtrBase = GEPLHS->getOperand(0);
4803 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004804 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00004805 // This transformation (ignoring the base and scales) is valid because we
4806 // know pointers can't overflow. See if we can output an optimized form.
4807 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4808
4809 // If not, synthesize the offset the hard way.
4810 if (Offset == 0)
4811 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00004812 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4813 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004814 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4815 // If the base pointers are different, but the indices are the same, just
4816 // compare the base pointer.
4817 if (PtrBase != GEPRHS->getOperand(0)) {
4818 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4819 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4820 GEPRHS->getOperand(0)->getType();
4821 if (IndicesTheSame)
4822 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4823 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4824 IndicesTheSame = false;
4825 break;
4826 }
4827
4828 // If all indices are the same, just compare the base pointers.
4829 if (IndicesTheSame)
4830 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4831 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4832
4833 // Otherwise, the base pointers are different and the indices are
4834 // different, bail out.
4835 return 0;
4836 }
4837
4838 // If one of the GEPs has all zero indices, recurse.
4839 bool AllZeros = true;
4840 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4841 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4842 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4843 AllZeros = false;
4844 break;
4845 }
4846 if (AllZeros)
4847 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4848 ICmpInst::getSwappedPredicate(Cond), I);
4849
4850 // If the other GEP has all zero indices, recurse.
4851 AllZeros = true;
4852 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4853 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4854 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4855 AllZeros = false;
4856 break;
4857 }
4858 if (AllZeros)
4859 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4860
4861 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4862 // If the GEPs only differ by one index, compare it.
4863 unsigned NumDifferences = 0; // Keep track of # differences.
4864 unsigned DiffOperand = 0; // The operand that differs.
4865 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4866 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4867 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4868 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4869 // Irreconcilable differences.
4870 NumDifferences = 2;
4871 break;
4872 } else {
4873 if (NumDifferences++) break;
4874 DiffOperand = i;
4875 }
4876 }
4877
4878 if (NumDifferences == 0) // SAME GEP?
4879 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004880 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00004881 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00004882
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004883 else if (NumDifferences == 1) {
4884 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4885 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4886 // Make sure we do a signed comparison here.
4887 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4888 }
4889 }
4890
4891 // Only lower this if the icmp is the only user of the GEP or if we expect
4892 // the result to fold to a constant!
4893 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4894 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4895 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4896 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4897 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4898 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4899 }
4900 }
4901 return 0;
4902}
4903
Chris Lattnere6b62d92008-05-19 20:18:56 +00004904/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4905///
4906Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4907 Instruction *LHSI,
4908 Constant *RHSC) {
4909 if (!isa<ConstantFP>(RHSC)) return 0;
4910 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4911
4912 // Get the width of the mantissa. We don't want to hack on conversions that
4913 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00004914 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00004915 if (MantissaWidth == -1) return 0; // Unknown.
4916
4917 // Check to see that the input is converted from an integer type that is small
4918 // enough that preserves all bits. TODO: check here for "known" sign bits.
4919 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4920 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4921
4922 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4923 if (isa<UIToFPInst>(LHSI))
4924 ++InputSize;
4925
4926 // If the conversion would lose info, don't hack on this.
4927 if ((int)InputSize > MantissaWidth)
4928 return 0;
4929
4930 // Otherwise, we can potentially simplify the comparison. We know that it
4931 // will always come through as an integer value and we know the constant is
4932 // not a NAN (it would have been previously simplified).
4933 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4934
4935 ICmpInst::Predicate Pred;
4936 switch (I.getPredicate()) {
4937 default: assert(0 && "Unexpected predicate!");
4938 case FCmpInst::FCMP_UEQ:
4939 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4940 case FCmpInst::FCMP_UGT:
4941 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4942 case FCmpInst::FCMP_UGE:
4943 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4944 case FCmpInst::FCMP_ULT:
4945 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4946 case FCmpInst::FCMP_ULE:
4947 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4948 case FCmpInst::FCMP_UNE:
4949 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4950 case FCmpInst::FCMP_ORD:
4951 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4952 case FCmpInst::FCMP_UNO:
4953 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4954 }
4955
4956 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4957
4958 // Now we know that the APFloat is a normal number, zero or inf.
4959
Chris Lattnerf13ff492008-05-20 03:50:52 +00004960 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00004961 // comparing an i8 to 300.0.
4962 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4963
4964 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4965 // and large values.
4966 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4967 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4968 APFloat::rmNearestTiesToEven);
4969 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00004970 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4971 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004972 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4973 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4974 }
4975
4976 // See if the RHS value is < SignedMin.
4977 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4978 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4979 APFloat::rmNearestTiesToEven);
4980 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00004981 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4982 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004983 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4984 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4985 }
4986
4987 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4988 // it may still be fractional. See if it is fractional by casting the FP
4989 // value to the integer value and back, checking for equality. Don't do this
4990 // for zero, because -0.0 is not fractional.
4991 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4992 if (!RHS.isZero() &&
4993 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4994 // If we had a comparison against a fractional value, we have to adjust
4995 // the compare predicate and sometimes the value. RHSC is rounded towards
4996 // zero at this point.
4997 switch (Pred) {
4998 default: assert(0 && "Unexpected integer comparison!");
4999 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5000 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5001 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5002 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5003 case ICmpInst::ICMP_SLE:
5004 // (float)int <= 4.4 --> int <= 4
5005 // (float)int <= -4.4 --> int < -4
5006 if (RHS.isNegative())
5007 Pred = ICmpInst::ICMP_SLT;
5008 break;
5009 case ICmpInst::ICMP_SLT:
5010 // (float)int < -4.4 --> int < -4
5011 // (float)int < 4.4 --> int <= 4
5012 if (!RHS.isNegative())
5013 Pred = ICmpInst::ICMP_SLE;
5014 break;
5015 case ICmpInst::ICMP_SGT:
5016 // (float)int > 4.4 --> int > 4
5017 // (float)int > -4.4 --> int >= -4
5018 if (RHS.isNegative())
5019 Pred = ICmpInst::ICMP_SGE;
5020 break;
5021 case ICmpInst::ICMP_SGE:
5022 // (float)int >= -4.4 --> int >= -4
5023 // (float)int >= 4.4 --> int > 4
5024 if (!RHS.isNegative())
5025 Pred = ICmpInst::ICMP_SGT;
5026 break;
5027 }
5028 }
5029
5030 // Lower this FP comparison into an appropriate integer version of the
5031 // comparison.
5032 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5033}
5034
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5036 bool Changed = SimplifyCompare(I);
5037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5038
5039 // Fold trivial predicates.
5040 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5041 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5042 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5043 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5044
5045 // Simplify 'fcmp pred X, X'
5046 if (Op0 == Op1) {
5047 switch (I.getPredicate()) {
5048 default: assert(0 && "Unknown predicate!");
5049 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5050 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5051 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5052 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5053 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5054 case FCmpInst::FCMP_OLT: // True if ordered and less than
5055 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5056 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5057
5058 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5059 case FCmpInst::FCMP_ULT: // True if unordered or less than
5060 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5061 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5062 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5063 I.setPredicate(FCmpInst::FCMP_UNO);
5064 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5065 return &I;
5066
5067 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5068 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5069 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5070 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5071 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5072 I.setPredicate(FCmpInst::FCMP_ORD);
5073 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5074 return &I;
5075 }
5076 }
5077
5078 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5079 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5080
5081 // Handle fcmp with constant RHS
5082 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005083 // If the constant is a nan, see if we can fold the comparison based on it.
5084 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5085 if (CFP->getValueAPF().isNaN()) {
5086 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5087 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005088 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5089 "Comparison must be either ordered or unordered!");
5090 // True if unordered.
5091 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005092 }
5093 }
5094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005095 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5096 switch (LHSI->getOpcode()) {
5097 case Instruction::PHI:
5098 if (Instruction *NV = FoldOpIntoPhi(I))
5099 return NV;
5100 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005101 case Instruction::SIToFP:
5102 case Instruction::UIToFP:
5103 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5104 return NV;
5105 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005106 case Instruction::Select:
5107 // If either operand of the select is a constant, we can fold the
5108 // comparison into the select arms, which will cause one to be
5109 // constant folded and the select turned into a bitwise or.
5110 Value *Op1 = 0, *Op2 = 0;
5111 if (LHSI->hasOneUse()) {
5112 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5113 // Fold the known value into the constant operand.
5114 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5115 // Insert a new FCmp of the other select operand.
5116 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5117 LHSI->getOperand(2), RHSC,
5118 I.getName()), I);
5119 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5120 // Fold the known value into the constant operand.
5121 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5122 // Insert a new FCmp of the other select operand.
5123 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5124 LHSI->getOperand(1), RHSC,
5125 I.getName()), I);
5126 }
5127 }
5128
5129 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005130 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005131 break;
5132 }
5133 }
5134
5135 return Changed ? &I : 0;
5136}
5137
5138Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5139 bool Changed = SimplifyCompare(I);
5140 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5141 const Type *Ty = Op0->getType();
5142
5143 // icmp X, X
5144 if (Op0 == Op1)
5145 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005146 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005147
5148 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5149 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005151 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5152 // addresses never equal each other! We already know that Op0 != Op1.
5153 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5154 isa<ConstantPointerNull>(Op0)) &&
5155 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5156 isa<ConstantPointerNull>(Op1)))
5157 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005158 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005159
5160 // icmp's with boolean values can always be turned into bitwise operations
5161 if (Ty == Type::Int1Ty) {
5162 switch (I.getPredicate()) {
5163 default: assert(0 && "Invalid icmp instruction!");
5164 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005165 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005166 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005167 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005168 }
5169 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171
5172 case ICmpInst::ICMP_UGT:
5173 case ICmpInst::ICMP_SGT:
5174 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5175 // FALL THROUGH
5176 case ICmpInst::ICMP_ULT:
5177 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005178 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005179 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005180 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 }
5182 case ICmpInst::ICMP_UGE:
5183 case ICmpInst::ICMP_SGE:
5184 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5185 // FALL THROUGH
5186 case ICmpInst::ICMP_ULE:
5187 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005188 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005189 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005190 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 }
5192 }
5193 }
5194
5195 // See if we are doing a comparison between a constant and an instruction that
5196 // can be folded into the comparison.
5197 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005198 Value *A, *B;
5199
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005200 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5201 if (I.isEquality() && CI->isNullValue() &&
5202 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5203 // (icmp cond A B) if cond is equality
5204 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005205 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005206
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005207 switch (I.getPredicate()) {
5208 default: break;
5209 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5210 if (CI->isMinValue(false))
5211 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5212 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5213 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5214 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5215 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5216 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5217 if (CI->isMinValue(true))
5218 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5219 ConstantInt::getAllOnesValue(Op0->getType()));
5220
5221 break;
5222
5223 case ICmpInst::ICMP_SLT:
5224 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5225 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5226 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5227 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5228 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5230 break;
5231
5232 case ICmpInst::ICMP_UGT:
5233 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5234 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5235 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5236 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5237 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5238 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5239
5240 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5241 if (CI->isMaxValue(true))
5242 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5243 ConstantInt::getNullValue(Op0->getType()));
5244 break;
5245
5246 case ICmpInst::ICMP_SGT:
5247 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5248 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5249 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5250 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5251 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5252 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5253 break;
5254
5255 case ICmpInst::ICMP_ULE:
5256 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5257 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5258 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5259 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5260 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5261 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5262 break;
5263
5264 case ICmpInst::ICMP_SLE:
5265 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5266 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5267 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5268 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5269 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5270 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5271 break;
5272
5273 case ICmpInst::ICMP_UGE:
5274 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5275 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5276 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5277 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5278 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5279 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5280 break;
5281
5282 case ICmpInst::ICMP_SGE:
5283 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5284 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5285 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5286 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5287 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5288 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5289 break;
5290 }
5291
5292 // If we still have a icmp le or icmp ge instruction, turn it into the
5293 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5294 // already been handled above, this requires little checking.
5295 //
5296 switch (I.getPredicate()) {
5297 default: break;
5298 case ICmpInst::ICMP_ULE:
5299 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5300 case ICmpInst::ICMP_SLE:
5301 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5302 case ICmpInst::ICMP_UGE:
5303 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5304 case ICmpInst::ICMP_SGE:
5305 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5306 }
5307
5308 // See if we can fold the comparison based on bits known to be zero or one
5309 // in the input. If this comparison is a normal comparison, it demands all
5310 // bits, if it is a sign bit comparison, it only demands the sign bit.
5311
5312 bool UnusedBit;
5313 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5314
5315 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5316 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5317 if (SimplifyDemandedBits(Op0,
5318 isSignBit ? APInt::getSignBit(BitWidth)
5319 : APInt::getAllOnesValue(BitWidth),
5320 KnownZero, KnownOne, 0))
5321 return &I;
5322
5323 // Given the known and unknown bits, compute a range that the LHS could be
5324 // in.
5325 if ((KnownOne | KnownZero) != 0) {
5326 // Compute the Min, Max and RHS values based on the known bits. For the
5327 // EQ and NE we use unsigned values.
5328 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5329 const APInt& RHSVal = CI->getValue();
5330 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5331 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5332 Max);
5333 } else {
5334 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5335 Max);
5336 }
5337 switch (I.getPredicate()) { // LE/GE have been folded already.
5338 default: assert(0 && "Unknown icmp opcode!");
5339 case ICmpInst::ICMP_EQ:
5340 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5341 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5342 break;
5343 case ICmpInst::ICMP_NE:
5344 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5345 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5346 break;
5347 case ICmpInst::ICMP_ULT:
5348 if (Max.ult(RHSVal))
5349 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5350 if (Min.uge(RHSVal))
5351 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5352 break;
5353 case ICmpInst::ICMP_UGT:
5354 if (Min.ugt(RHSVal))
5355 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5356 if (Max.ule(RHSVal))
5357 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5358 break;
5359 case ICmpInst::ICMP_SLT:
5360 if (Max.slt(RHSVal))
5361 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5362 if (Min.sgt(RHSVal))
5363 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5364 break;
5365 case ICmpInst::ICMP_SGT:
5366 if (Min.sgt(RHSVal))
5367 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5368 if (Max.sle(RHSVal))
5369 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5370 break;
5371 }
5372 }
5373
5374 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5375 // instruction, see if that instruction also has constants so that the
5376 // instruction can be folded into the icmp
5377 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5378 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5379 return Res;
5380 }
5381
5382 // Handle icmp with constant (but not simple integer constant) RHS
5383 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5384 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5385 switch (LHSI->getOpcode()) {
5386 case Instruction::GetElementPtr:
5387 if (RHSC->isNullValue()) {
5388 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5389 bool isAllZeros = true;
5390 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5391 if (!isa<Constant>(LHSI->getOperand(i)) ||
5392 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5393 isAllZeros = false;
5394 break;
5395 }
5396 if (isAllZeros)
5397 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5398 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5399 }
5400 break;
5401
5402 case Instruction::PHI:
5403 if (Instruction *NV = FoldOpIntoPhi(I))
5404 return NV;
5405 break;
5406 case Instruction::Select: {
5407 // If either operand of the select is a constant, we can fold the
5408 // comparison into the select arms, which will cause one to be
5409 // constant folded and the select turned into a bitwise or.
5410 Value *Op1 = 0, *Op2 = 0;
5411 if (LHSI->hasOneUse()) {
5412 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5413 // Fold the known value into the constant operand.
5414 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5415 // Insert a new ICmp of the other select operand.
5416 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5417 LHSI->getOperand(2), RHSC,
5418 I.getName()), I);
5419 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5420 // Fold the known value into the constant operand.
5421 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5422 // Insert a new ICmp of the other select operand.
5423 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5424 LHSI->getOperand(1), RHSC,
5425 I.getName()), I);
5426 }
5427 }
5428
5429 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005430 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 break;
5432 }
5433 case Instruction::Malloc:
5434 // If we have (malloc != null), and if the malloc has a single use, we
5435 // can assume it is successful and remove the malloc.
5436 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5437 AddToWorkList(LHSI);
5438 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005439 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005440 }
5441 break;
5442 }
5443 }
5444
5445 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5446 if (User *GEP = dyn_castGetElementPtr(Op0))
5447 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5448 return NI;
5449 if (User *GEP = dyn_castGetElementPtr(Op1))
5450 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5451 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5452 return NI;
5453
5454 // Test to see if the operands of the icmp are casted versions of other
5455 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5456 // now.
5457 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5458 if (isa<PointerType>(Op0->getType()) &&
5459 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5460 // We keep moving the cast from the left operand over to the right
5461 // operand, where it can often be eliminated completely.
5462 Op0 = CI->getOperand(0);
5463
5464 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5465 // so eliminate it as well.
5466 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5467 Op1 = CI2->getOperand(0);
5468
5469 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005470 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005471 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5472 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5473 } else {
5474 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005475 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005476 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005477 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005478 return new ICmpInst(I.getPredicate(), Op0, Op1);
5479 }
5480 }
5481
5482 if (isa<CastInst>(Op0)) {
5483 // Handle the special case of: icmp (cast bool to X), <cst>
5484 // This comes up when you have code like
5485 // int X = A < B;
5486 // if (X) ...
5487 // For generality, we handle any zero-extension of any operand comparison
5488 // with a constant or another cast from the same type.
5489 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5490 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5491 return R;
5492 }
5493
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005494 // ~x < ~y --> y < x
5495 { Value *A, *B;
5496 if (match(Op0, m_Not(m_Value(A))) &&
5497 match(Op1, m_Not(m_Value(B))))
5498 return new ICmpInst(I.getPredicate(), B, A);
5499 }
5500
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005501 if (I.isEquality()) {
5502 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005503
5504 // -x == -y --> x == y
5505 if (match(Op0, m_Neg(m_Value(A))) &&
5506 match(Op1, m_Neg(m_Value(B))))
5507 return new ICmpInst(I.getPredicate(), A, B);
5508
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005509 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5510 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5511 Value *OtherVal = A == Op1 ? B : A;
5512 return new ICmpInst(I.getPredicate(), OtherVal,
5513 Constant::getNullValue(A->getType()));
5514 }
5515
5516 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5517 // A^c1 == C^c2 --> A == C^(c1^c2)
5518 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5519 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5520 if (Op1->hasOneUse()) {
5521 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005522 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005523 return new ICmpInst(I.getPredicate(), A,
5524 InsertNewInstBefore(Xor, I));
5525 }
5526
5527 // A^B == A^D -> B == D
5528 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5529 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5530 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5531 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5532 }
5533 }
5534
5535 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5536 (A == Op0 || B == Op0)) {
5537 // A == (A^B) -> B == 0
5538 Value *OtherVal = A == Op0 ? B : A;
5539 return new ICmpInst(I.getPredicate(), OtherVal,
5540 Constant::getNullValue(A->getType()));
5541 }
5542 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5543 // (A-B) == A -> B == 0
5544 return new ICmpInst(I.getPredicate(), B,
5545 Constant::getNullValue(B->getType()));
5546 }
5547 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5548 // A == (A-B) -> B == 0
5549 return new ICmpInst(I.getPredicate(), B,
5550 Constant::getNullValue(B->getType()));
5551 }
5552
5553 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5554 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5555 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5556 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5557 Value *X = 0, *Y = 0, *Z = 0;
5558
5559 if (A == C) {
5560 X = B; Y = D; Z = A;
5561 } else if (A == D) {
5562 X = B; Y = C; Z = A;
5563 } else if (B == C) {
5564 X = A; Y = D; Z = B;
5565 } else if (B == D) {
5566 X = A; Y = C; Z = B;
5567 }
5568
5569 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005570 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5571 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005572 I.setOperand(0, Op1);
5573 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5574 return &I;
5575 }
5576 }
5577 }
5578 return Changed ? &I : 0;
5579}
5580
5581
5582/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5583/// and CmpRHS are both known to be integer constants.
5584Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5585 ConstantInt *DivRHS) {
5586 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5587 const APInt &CmpRHSV = CmpRHS->getValue();
5588
5589 // FIXME: If the operand types don't match the type of the divide
5590 // then don't attempt this transform. The code below doesn't have the
5591 // logic to deal with a signed divide and an unsigned compare (and
5592 // vice versa). This is because (x /s C1) <s C2 produces different
5593 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5594 // (x /u C1) <u C2. Simply casting the operands and result won't
5595 // work. :( The if statement below tests that condition and bails
5596 // if it finds it.
5597 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5598 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5599 return 0;
5600 if (DivRHS->isZero())
5601 return 0; // The ProdOV computation fails on divide by zero.
5602
5603 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5604 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5605 // C2 (CI). By solving for X we can turn this into a range check
5606 // instead of computing a divide.
5607 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5608
5609 // Determine if the product overflows by seeing if the product is
5610 // not equal to the divide. Make sure we do the same kind of divide
5611 // as in the LHS instruction that we're folding.
5612 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5613 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5614
5615 // Get the ICmp opcode
5616 ICmpInst::Predicate Pred = ICI.getPredicate();
5617
5618 // Figure out the interval that is being checked. For example, a comparison
5619 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5620 // Compute this interval based on the constants involved and the signedness of
5621 // the compare/divide. This computes a half-open interval, keeping track of
5622 // whether either value in the interval overflows. After analysis each
5623 // overflow variable is set to 0 if it's corresponding bound variable is valid
5624 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5625 int LoOverflow = 0, HiOverflow = 0;
5626 ConstantInt *LoBound = 0, *HiBound = 0;
5627
5628
5629 if (!DivIsSigned) { // udiv
5630 // e.g. X/5 op 3 --> [15, 20)
5631 LoBound = Prod;
5632 HiOverflow = LoOverflow = ProdOV;
5633 if (!HiOverflow)
5634 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005635 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005636 if (CmpRHSV == 0) { // (X / pos) op 0
5637 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5638 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5639 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005640 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005641 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5642 HiOverflow = LoOverflow = ProdOV;
5643 if (!HiOverflow)
5644 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5645 } else { // (X / pos) op neg
5646 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5647 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5648 LoOverflow = AddWithOverflow(LoBound, Prod,
5649 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5650 HiBound = AddOne(Prod);
5651 HiOverflow = ProdOV ? -1 : 0;
5652 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005653 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005654 if (CmpRHSV == 0) { // (X / neg) op 0
5655 // e.g. X/-5 op 0 --> [-4, 5)
5656 LoBound = AddOne(DivRHS);
5657 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5658 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5659 HiOverflow = 1; // [INTMIN+1, overflow)
5660 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5661 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005662 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005663 // e.g. X/-5 op 3 --> [-19, -14)
5664 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5665 if (!LoOverflow)
5666 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5667 HiBound = AddOne(Prod);
5668 } else { // (X / neg) op neg
5669 // e.g. X/-5 op -3 --> [15, 20)
5670 LoBound = Prod;
5671 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5672 HiBound = Subtract(Prod, DivRHS);
5673 }
5674
5675 // Dividing by a negative swaps the condition. LT <-> GT
5676 Pred = ICmpInst::getSwappedPredicate(Pred);
5677 }
5678
5679 Value *X = DivI->getOperand(0);
5680 switch (Pred) {
5681 default: assert(0 && "Unhandled icmp opcode!");
5682 case ICmpInst::ICMP_EQ:
5683 if (LoOverflow && HiOverflow)
5684 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5685 else if (HiOverflow)
5686 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5687 ICmpInst::ICMP_UGE, X, LoBound);
5688 else if (LoOverflow)
5689 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5690 ICmpInst::ICMP_ULT, X, HiBound);
5691 else
5692 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5693 case ICmpInst::ICMP_NE:
5694 if (LoOverflow && HiOverflow)
5695 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5696 else if (HiOverflow)
5697 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5698 ICmpInst::ICMP_ULT, X, LoBound);
5699 else if (LoOverflow)
5700 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5701 ICmpInst::ICMP_UGE, X, HiBound);
5702 else
5703 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5704 case ICmpInst::ICMP_ULT:
5705 case ICmpInst::ICMP_SLT:
5706 if (LoOverflow == +1) // Low bound is greater than input range.
5707 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5708 if (LoOverflow == -1) // Low bound is less than input range.
5709 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5710 return new ICmpInst(Pred, X, LoBound);
5711 case ICmpInst::ICMP_UGT:
5712 case ICmpInst::ICMP_SGT:
5713 if (HiOverflow == +1) // High bound greater than input range.
5714 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5715 else if (HiOverflow == -1) // High bound less than input range.
5716 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5717 if (Pred == ICmpInst::ICMP_UGT)
5718 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5719 else
5720 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5721 }
5722}
5723
5724
5725/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5726///
5727Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5728 Instruction *LHSI,
5729 ConstantInt *RHS) {
5730 const APInt &RHSV = RHS->getValue();
5731
5732 switch (LHSI->getOpcode()) {
5733 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5734 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5735 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5736 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005737 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5738 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005739 Value *CompareVal = LHSI->getOperand(0);
5740
5741 // If the sign bit of the XorCST is not set, there is no change to
5742 // the operation, just stop using the Xor.
5743 if (!XorCST->getValue().isNegative()) {
5744 ICI.setOperand(0, CompareVal);
5745 AddToWorkList(LHSI);
5746 return &ICI;
5747 }
5748
5749 // Was the old condition true if the operand is positive?
5750 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5751
5752 // If so, the new one isn't.
5753 isTrueIfPositive ^= true;
5754
5755 if (isTrueIfPositive)
5756 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5757 else
5758 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5759 }
5760 }
5761 break;
5762 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5763 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5764 LHSI->getOperand(0)->hasOneUse()) {
5765 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5766
5767 // If the LHS is an AND of a truncating cast, we can widen the
5768 // and/compare to be the input width without changing the value
5769 // produced, eliminating a cast.
5770 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5771 // We can do this transformation if either the AND constant does not
5772 // have its sign bit set or if it is an equality comparison.
5773 // Extending a relational comparison when we're checking the sign
5774 // bit would not work.
5775 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005776 (ICI.isEquality() ||
5777 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005778 uint32_t BitWidth =
5779 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5780 APInt NewCST = AndCST->getValue();
5781 NewCST.zext(BitWidth);
5782 APInt NewCI = RHSV;
5783 NewCI.zext(BitWidth);
5784 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005785 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005786 ConstantInt::get(NewCST),LHSI->getName());
5787 InsertNewInstBefore(NewAnd, ICI);
5788 return new ICmpInst(ICI.getPredicate(), NewAnd,
5789 ConstantInt::get(NewCI));
5790 }
5791 }
5792
5793 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5794 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5795 // happens a LOT in code produced by the C front-end, for bitfield
5796 // access.
5797 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5798 if (Shift && !Shift->isShift())
5799 Shift = 0;
5800
5801 ConstantInt *ShAmt;
5802 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5803 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5804 const Type *AndTy = AndCST->getType(); // Type of the and.
5805
5806 // We can fold this as long as we can't shift unknown bits
5807 // into the mask. This can only happen with signed shift
5808 // rights, as they sign-extend.
5809 if (ShAmt) {
5810 bool CanFold = Shift->isLogicalShift();
5811 if (!CanFold) {
5812 // To test for the bad case of the signed shr, see if any
5813 // of the bits shifted in could be tested after the mask.
5814 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5815 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5816
5817 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5818 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5819 AndCST->getValue()) == 0)
5820 CanFold = true;
5821 }
5822
5823 if (CanFold) {
5824 Constant *NewCst;
5825 if (Shift->getOpcode() == Instruction::Shl)
5826 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5827 else
5828 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5829
5830 // Check to see if we are shifting out any of the bits being
5831 // compared.
5832 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5833 // If we shifted bits out, the fold is not going to work out.
5834 // As a special case, check to see if this means that the
5835 // result is always true or false now.
5836 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5837 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5838 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5839 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5840 } else {
5841 ICI.setOperand(1, NewCst);
5842 Constant *NewAndCST;
5843 if (Shift->getOpcode() == Instruction::Shl)
5844 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5845 else
5846 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5847 LHSI->setOperand(1, NewAndCST);
5848 LHSI->setOperand(0, Shift->getOperand(0));
5849 AddToWorkList(Shift); // Shift is dead.
5850 AddUsesToWorkList(ICI);
5851 return &ICI;
5852 }
5853 }
5854 }
5855
5856 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5857 // preferable because it allows the C<<Y expression to be hoisted out
5858 // of a loop if Y is invariant and X is not.
5859 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5860 ICI.isEquality() && !Shift->isArithmeticShift() &&
5861 isa<Instruction>(Shift->getOperand(0))) {
5862 // Compute C << Y.
5863 Value *NS;
5864 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005865 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005866 Shift->getOperand(1), "tmp");
5867 } else {
5868 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00005869 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005870 Shift->getOperand(1), "tmp");
5871 }
5872 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5873
5874 // Compute X & (C << Y).
5875 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005876 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005877 InsertNewInstBefore(NewAnd, ICI);
5878
5879 ICI.setOperand(0, NewAnd);
5880 return &ICI;
5881 }
5882 }
5883 break;
5884
5885 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5886 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5887 if (!ShAmt) break;
5888
5889 uint32_t TypeBits = RHSV.getBitWidth();
5890
5891 // Check that the shift amount is in range. If not, don't perform
5892 // undefined shifts. When the shift is visited it will be
5893 // simplified.
5894 if (ShAmt->uge(TypeBits))
5895 break;
5896
5897 if (ICI.isEquality()) {
5898 // If we are comparing against bits always shifted out, the
5899 // comparison cannot succeed.
5900 Constant *Comp =
5901 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5902 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5903 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5904 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5905 return ReplaceInstUsesWith(ICI, Cst);
5906 }
5907
5908 if (LHSI->hasOneUse()) {
5909 // Otherwise strength reduce the shift into an and.
5910 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5911 Constant *Mask =
5912 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5913
5914 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005915 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916 Mask, LHSI->getName()+".mask");
5917 Value *And = InsertNewInstBefore(AndI, ICI);
5918 return new ICmpInst(ICI.getPredicate(), And,
5919 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5920 }
5921 }
5922
5923 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5924 bool TrueIfSigned = false;
5925 if (LHSI->hasOneUse() &&
5926 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5927 // (X << 31) <s 0 --> (X&1) != 0
5928 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5929 (TypeBits-ShAmt->getZExtValue()-1));
5930 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005931 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005932 Mask, LHSI->getName()+".mask");
5933 Value *And = InsertNewInstBefore(AndI, ICI);
5934
5935 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5936 And, Constant::getNullValue(And->getType()));
5937 }
5938 break;
5939 }
5940
5941 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5942 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005943 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005944 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00005945 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946
Chris Lattner5ee84f82008-03-21 05:19:58 +00005947 // Check that the shift amount is in range. If not, don't perform
5948 // undefined shifts. When the shift is visited it will be
5949 // simplified.
5950 uint32_t TypeBits = RHSV.getBitWidth();
5951 if (ShAmt->uge(TypeBits))
5952 break;
5953
5954 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005955
Chris Lattner5ee84f82008-03-21 05:19:58 +00005956 // If we are comparing against bits always shifted out, the
5957 // comparison cannot succeed.
5958 APInt Comp = RHSV << ShAmtVal;
5959 if (LHSI->getOpcode() == Instruction::LShr)
5960 Comp = Comp.lshr(ShAmtVal);
5961 else
5962 Comp = Comp.ashr(ShAmtVal);
5963
5964 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5965 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5966 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5967 return ReplaceInstUsesWith(ICI, Cst);
5968 }
5969
5970 // Otherwise, check to see if the bits shifted out are known to be zero.
5971 // If so, we can compare against the unshifted value:
5972 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00005973 if (LHSI->hasOneUse() &&
5974 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005975 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5976 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5977 ConstantExpr::getShl(RHS, ShAmt));
5978 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005979
Evan Chengfb9292a2008-04-23 00:38:06 +00005980 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005981 // Otherwise strength reduce the shift into an and.
5982 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5983 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005984
Chris Lattner5ee84f82008-03-21 05:19:58 +00005985 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005986 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005987 Mask, LHSI->getName()+".mask");
5988 Value *And = InsertNewInstBefore(AndI, ICI);
5989 return new ICmpInst(ICI.getPredicate(), And,
5990 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 }
5992 break;
5993 }
5994
5995 case Instruction::SDiv:
5996 case Instruction::UDiv:
5997 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5998 // Fold this div into the comparison, producing a range check.
5999 // Determine, based on the divide type, what the range is being
6000 // checked. If there is an overflow on the low or high side, remember
6001 // it, otherwise compute the range [low, hi) bounding the new value.
6002 // See: InsertRangeTest above for the kinds of replacements possible.
6003 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6004 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6005 DivRHS))
6006 return R;
6007 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006008
6009 case Instruction::Add:
6010 // Fold: icmp pred (add, X, C1), C2
6011
6012 if (!ICI.isEquality()) {
6013 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6014 if (!LHSC) break;
6015 const APInt &LHSV = LHSC->getValue();
6016
6017 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6018 .subtract(LHSV);
6019
6020 if (ICI.isSignedPredicate()) {
6021 if (CR.getLower().isSignBit()) {
6022 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6023 ConstantInt::get(CR.getUpper()));
6024 } else if (CR.getUpper().isSignBit()) {
6025 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6026 ConstantInt::get(CR.getLower()));
6027 }
6028 } else {
6029 if (CR.getLower().isMinValue()) {
6030 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6031 ConstantInt::get(CR.getUpper()));
6032 } else if (CR.getUpper().isMinValue()) {
6033 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6034 ConstantInt::get(CR.getLower()));
6035 }
6036 }
6037 }
6038 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006039 }
6040
6041 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6042 if (ICI.isEquality()) {
6043 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6044
6045 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6046 // the second operand is a constant, simplify a bit.
6047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6048 switch (BO->getOpcode()) {
6049 case Instruction::SRem:
6050 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6051 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6052 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6053 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6054 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006055 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006056 BO->getName());
6057 InsertNewInstBefore(NewRem, ICI);
6058 return new ICmpInst(ICI.getPredicate(), NewRem,
6059 Constant::getNullValue(BO->getType()));
6060 }
6061 }
6062 break;
6063 case Instruction::Add:
6064 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6065 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6066 if (BO->hasOneUse())
6067 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6068 Subtract(RHS, BOp1C));
6069 } else if (RHSV == 0) {
6070 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6071 // efficiently invertible, or if the add has just this one use.
6072 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6073
6074 if (Value *NegVal = dyn_castNegVal(BOp1))
6075 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6076 else if (Value *NegVal = dyn_castNegVal(BOp0))
6077 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6078 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006079 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006080 InsertNewInstBefore(Neg, ICI);
6081 Neg->takeName(BO);
6082 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6083 }
6084 }
6085 break;
6086 case Instruction::Xor:
6087 // For the xor case, we can xor two constants together, eliminating
6088 // the explicit xor.
6089 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6090 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6091 ConstantExpr::getXor(RHS, BOC));
6092
6093 // FALLTHROUGH
6094 case Instruction::Sub:
6095 // Replace (([sub|xor] A, B) != 0) with (A != B)
6096 if (RHSV == 0)
6097 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6098 BO->getOperand(1));
6099 break;
6100
6101 case Instruction::Or:
6102 // If bits are being or'd in that are not present in the constant we
6103 // are comparing against, then the comparison could never succeed!
6104 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6105 Constant *NotCI = ConstantExpr::getNot(RHS);
6106 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6107 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6108 isICMP_NE));
6109 }
6110 break;
6111
6112 case Instruction::And:
6113 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6114 // If bits are being compared against that are and'd out, then the
6115 // comparison can never succeed!
6116 if ((RHSV & ~BOC->getValue()) != 0)
6117 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6118 isICMP_NE));
6119
6120 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6121 if (RHS == BOC && RHSV.isPowerOf2())
6122 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6123 ICmpInst::ICMP_NE, LHSI,
6124 Constant::getNullValue(RHS->getType()));
6125
6126 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6127 if (isSignBit(BOC)) {
6128 Value *X = BO->getOperand(0);
6129 Constant *Zero = Constant::getNullValue(X->getType());
6130 ICmpInst::Predicate pred = isICMP_NE ?
6131 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6132 return new ICmpInst(pred, X, Zero);
6133 }
6134
6135 // ((X & ~7) == 0) --> X < 8
6136 if (RHSV == 0 && isHighOnes(BOC)) {
6137 Value *X = BO->getOperand(0);
6138 Constant *NegX = ConstantExpr::getNeg(BOC);
6139 ICmpInst::Predicate pred = isICMP_NE ?
6140 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6141 return new ICmpInst(pred, X, NegX);
6142 }
6143 }
6144 default: break;
6145 }
6146 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6147 // Handle icmp {eq|ne} <intrinsic>, intcst.
6148 if (II->getIntrinsicID() == Intrinsic::bswap) {
6149 AddToWorkList(II);
6150 ICI.setOperand(0, II->getOperand(1));
6151 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6152 return &ICI;
6153 }
6154 }
6155 } else { // Not a ICMP_EQ/ICMP_NE
6156 // If the LHS is a cast from an integral value of the same size,
6157 // then since we know the RHS is a constant, try to simlify.
6158 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6159 Value *CastOp = Cast->getOperand(0);
6160 const Type *SrcTy = CastOp->getType();
6161 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6162 if (SrcTy->isInteger() &&
6163 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6164 // If this is an unsigned comparison, try to make the comparison use
6165 // smaller constant values.
6166 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6167 // X u< 128 => X s> -1
6168 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6169 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6170 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6171 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6172 // X u> 127 => X s< 0
6173 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6174 Constant::getNullValue(SrcTy));
6175 }
6176 }
6177 }
6178 }
6179 return 0;
6180}
6181
6182/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6183/// We only handle extending casts so far.
6184///
6185Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6186 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6187 Value *LHSCIOp = LHSCI->getOperand(0);
6188 const Type *SrcTy = LHSCIOp->getType();
6189 const Type *DestTy = LHSCI->getType();
6190 Value *RHSCIOp;
6191
6192 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6193 // integer type is the same size as the pointer type.
6194 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6195 getTargetData().getPointerSizeInBits() ==
6196 cast<IntegerType>(DestTy)->getBitWidth()) {
6197 Value *RHSOp = 0;
6198 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6199 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6200 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6201 RHSOp = RHSC->getOperand(0);
6202 // If the pointer types don't match, insert a bitcast.
6203 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006204 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006205 }
6206
6207 if (RHSOp)
6208 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6209 }
6210
6211 // The code below only handles extension cast instructions, so far.
6212 // Enforce this.
6213 if (LHSCI->getOpcode() != Instruction::ZExt &&
6214 LHSCI->getOpcode() != Instruction::SExt)
6215 return 0;
6216
6217 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6218 bool isSignedCmp = ICI.isSignedPredicate();
6219
6220 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6221 // Not an extension from the same type?
6222 RHSCIOp = CI->getOperand(0);
6223 if (RHSCIOp->getType() != LHSCIOp->getType())
6224 return 0;
6225
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006226 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006227 // and the other is a zext), then we can't handle this.
6228 if (CI->getOpcode() != LHSCI->getOpcode())
6229 return 0;
6230
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006231 // Deal with equality cases early.
6232 if (ICI.isEquality())
6233 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6234
6235 // A signed comparison of sign extended values simplifies into a
6236 // signed comparison.
6237 if (isSignedCmp && isSignedExt)
6238 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6239
6240 // The other three cases all fold into an unsigned comparison.
6241 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006242 }
6243
6244 // If we aren't dealing with a constant on the RHS, exit early
6245 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6246 if (!CI)
6247 return 0;
6248
6249 // Compute the constant that would happen if we truncated to SrcTy then
6250 // reextended to DestTy.
6251 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6252 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6253
6254 // If the re-extended constant didn't change...
6255 if (Res2 == CI) {
6256 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6257 // For example, we might have:
6258 // %A = sext short %X to uint
6259 // %B = icmp ugt uint %A, 1330
6260 // It is incorrect to transform this into
6261 // %B = icmp ugt short %X, 1330
6262 // because %A may have negative value.
6263 //
6264 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6265 // OR operation is EQ/NE.
6266 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6267 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6268 else
6269 return 0;
6270 }
6271
6272 // The re-extended constant changed so the constant cannot be represented
6273 // in the shorter type. Consequently, we cannot emit a simple comparison.
6274
6275 // First, handle some easy cases. We know the result cannot be equal at this
6276 // point so handle the ICI.isEquality() cases
6277 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6278 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6279 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6280 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6281
6282 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6283 // should have been folded away previously and not enter in here.
6284 Value *Result;
6285 if (isSignedCmp) {
6286 // We're performing a signed comparison.
6287 if (cast<ConstantInt>(CI)->getValue().isNegative())
6288 Result = ConstantInt::getFalse(); // X < (small) --> false
6289 else
6290 Result = ConstantInt::getTrue(); // X < (large) --> true
6291 } else {
6292 // We're performing an unsigned comparison.
6293 if (isSignedExt) {
6294 // We're performing an unsigned comp with a sign extended value.
6295 // This is true if the input is >= 0. [aka >s -1]
6296 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6297 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6298 NegOne, ICI.getName()), ICI);
6299 } else {
6300 // Unsigned extend & unsigned compare -> always true.
6301 Result = ConstantInt::getTrue();
6302 }
6303 }
6304
6305 // Finally, return the value computed.
6306 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6307 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6308 return ReplaceInstUsesWith(ICI, Result);
6309 } else {
6310 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6311 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6312 "ICmp should be folded!");
6313 if (Constant *CI = dyn_cast<Constant>(Result))
6314 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6315 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006316 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006317 }
6318}
6319
6320Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6321 return commonShiftTransforms(I);
6322}
6323
6324Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6325 return commonShiftTransforms(I);
6326}
6327
6328Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006329 if (Instruction *R = commonShiftTransforms(I))
6330 return R;
6331
6332 Value *Op0 = I.getOperand(0);
6333
6334 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6335 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6336 if (CSI->isAllOnesValue())
6337 return ReplaceInstUsesWith(I, CSI);
6338
6339 // See if we can turn a signed shr into an unsigned shr.
6340 if (MaskedValueIsZero(Op0,
6341 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006342 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006343
6344 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006345}
6346
6347Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6348 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6350
6351 // shl X, 0 == X and shr X, 0 == X
6352 // shl 0, X == 0 and shr 0, X == 0
6353 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6354 Op0 == Constant::getNullValue(Op0->getType()))
6355 return ReplaceInstUsesWith(I, Op0);
6356
6357 if (isa<UndefValue>(Op0)) {
6358 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6359 return ReplaceInstUsesWith(I, Op0);
6360 else // undef << X -> 0, undef >>u X -> 0
6361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6362 }
6363 if (isa<UndefValue>(Op1)) {
6364 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6365 return ReplaceInstUsesWith(I, Op0);
6366 else // X << undef, X >>u undef -> 0
6367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6368 }
6369
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006370 // Try to fold constant and into select arguments.
6371 if (isa<Constant>(Op0))
6372 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6373 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6374 return R;
6375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006376 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6377 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6378 return Res;
6379 return 0;
6380}
6381
6382Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6383 BinaryOperator &I) {
6384 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6385
6386 // See if we can simplify any instructions used by the instruction whose sole
6387 // purpose is to compute bits we don't care about.
6388 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6389 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6390 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6391 KnownZero, KnownOne))
6392 return &I;
6393
6394 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6395 // of a signed value.
6396 //
6397 if (Op1->uge(TypeBits)) {
6398 if (I.getOpcode() != Instruction::AShr)
6399 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6400 else {
6401 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6402 return &I;
6403 }
6404 }
6405
6406 // ((X*C1) << C2) == (X * (C1 << C2))
6407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6408 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6409 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006410 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006411 ConstantExpr::getShl(BOOp, Op1));
6412
6413 // Try to fold constant and into select arguments.
6414 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6415 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6416 return R;
6417 if (isa<PHINode>(Op0))
6418 if (Instruction *NV = FoldOpIntoPhi(I))
6419 return NV;
6420
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006421 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6422 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6423 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6424 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6425 // place. Don't try to do this transformation in this case. Also, we
6426 // require that the input operand is a shift-by-constant so that we have
6427 // confidence that the shifts will get folded together. We could do this
6428 // xform in more cases, but it is unlikely to be profitable.
6429 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6430 isa<ConstantInt>(TrOp->getOperand(1))) {
6431 // Okay, we'll do this xform. Make the shift of shift.
6432 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006433 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006434 I.getName());
6435 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6436
6437 // For logical shifts, the truncation has the effect of making the high
6438 // part of the register be zeros. Emulate this by inserting an AND to
6439 // clear the top bits as needed. This 'and' will usually be zapped by
6440 // other xforms later if dead.
6441 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6442 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6443 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6444
6445 // The mask we constructed says what the trunc would do if occurring
6446 // between the shifts. We want to know the effect *after* the second
6447 // shift. We know that it is a logical shift by a constant, so adjust the
6448 // mask as appropriate.
6449 if (I.getOpcode() == Instruction::Shl)
6450 MaskV <<= Op1->getZExtValue();
6451 else {
6452 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6453 MaskV = MaskV.lshr(Op1->getZExtValue());
6454 }
6455
Gabor Greifa645dd32008-05-16 19:29:10 +00006456 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006457 TI->getName());
6458 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6459
6460 // Return the value truncated to the interesting size.
6461 return new TruncInst(And, I.getType());
6462 }
6463 }
6464
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006465 if (Op0->hasOneUse()) {
6466 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6467 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6468 Value *V1, *V2;
6469 ConstantInt *CC;
6470 switch (Op0BO->getOpcode()) {
6471 default: break;
6472 case Instruction::Add:
6473 case Instruction::And:
6474 case Instruction::Or:
6475 case Instruction::Xor: {
6476 // These operators commute.
6477 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6478 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6479 match(Op0BO->getOperand(1),
6480 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006481 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006482 Op0BO->getOperand(0), Op1,
6483 Op0BO->getName());
6484 InsertNewInstBefore(YS, I); // (Y << C)
6485 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006486 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006487 Op0BO->getOperand(1)->getName());
6488 InsertNewInstBefore(X, I); // (X + (Y << C))
6489 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006490 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006491 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6492 }
6493
6494 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6495 Value *Op0BOOp1 = Op0BO->getOperand(1);
6496 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6497 match(Op0BOOp1,
6498 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6499 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6500 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006501 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006502 Op0BO->getOperand(0), Op1,
6503 Op0BO->getName());
6504 InsertNewInstBefore(YS, I); // (Y << C)
6505 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006506 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006507 V1->getName()+".mask");
6508 InsertNewInstBefore(XM, I); // X & (CC << C)
6509
Gabor Greifa645dd32008-05-16 19:29:10 +00006510 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511 }
6512 }
6513
6514 // FALL THROUGH.
6515 case Instruction::Sub: {
6516 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6517 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6518 match(Op0BO->getOperand(0),
6519 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006520 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006521 Op0BO->getOperand(1), Op1,
6522 Op0BO->getName());
6523 InsertNewInstBefore(YS, I); // (Y << C)
6524 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006525 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006526 Op0BO->getOperand(0)->getName());
6527 InsertNewInstBefore(X, I); // (X + (Y << C))
6528 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006529 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006530 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6531 }
6532
6533 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6534 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6535 match(Op0BO->getOperand(0),
6536 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6537 m_ConstantInt(CC))) && V2 == Op1 &&
6538 cast<BinaryOperator>(Op0BO->getOperand(0))
6539 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006540 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006541 Op0BO->getOperand(1), Op1,
6542 Op0BO->getName());
6543 InsertNewInstBefore(YS, I); // (Y << C)
6544 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006545 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006546 V1->getName()+".mask");
6547 InsertNewInstBefore(XM, I); // X & (CC << C)
6548
Gabor Greifa645dd32008-05-16 19:29:10 +00006549 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550 }
6551
6552 break;
6553 }
6554 }
6555
6556
6557 // If the operand is an bitwise operator with a constant RHS, and the
6558 // shift is the only use, we can pull it out of the shift.
6559 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6560 bool isValid = true; // Valid only for And, Or, Xor
6561 bool highBitSet = false; // Transform if high bit of constant set?
6562
6563 switch (Op0BO->getOpcode()) {
6564 default: isValid = false; break; // Do not perform transform!
6565 case Instruction::Add:
6566 isValid = isLeftShift;
6567 break;
6568 case Instruction::Or:
6569 case Instruction::Xor:
6570 highBitSet = false;
6571 break;
6572 case Instruction::And:
6573 highBitSet = true;
6574 break;
6575 }
6576
6577 // If this is a signed shift right, and the high bit is modified
6578 // by the logical operation, do not perform the transformation.
6579 // The highBitSet boolean indicates the value of the high bit of
6580 // the constant which would cause it to be modified for this
6581 // operation.
6582 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006583 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006584 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006585
6586 if (isValid) {
6587 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6588
6589 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006590 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591 InsertNewInstBefore(NewShift, I);
6592 NewShift->takeName(Op0BO);
6593
Gabor Greifa645dd32008-05-16 19:29:10 +00006594 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006595 NewRHS);
6596 }
6597 }
6598 }
6599 }
6600
6601 // Find out if this is a shift of a shift by a constant.
6602 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6603 if (ShiftOp && !ShiftOp->isShift())
6604 ShiftOp = 0;
6605
6606 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6607 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6608 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6609 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6610 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6611 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6612 Value *X = ShiftOp->getOperand(0);
6613
6614 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6615 if (AmtSum > TypeBits)
6616 AmtSum = TypeBits;
6617
6618 const IntegerType *Ty = cast<IntegerType>(I.getType());
6619
6620 // Check for (X << c1) << c2 and (X >> c1) >> c2
6621 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006622 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006623 ConstantInt::get(Ty, AmtSum));
6624 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6625 I.getOpcode() == Instruction::AShr) {
6626 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006627 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6629 I.getOpcode() == Instruction::LShr) {
6630 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6631 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006632 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006633 InsertNewInstBefore(Shift, I);
6634
6635 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006636 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006637 }
6638
6639 // Okay, if we get here, one shift must be left, and the other shift must be
6640 // right. See if the amounts are equal.
6641 if (ShiftAmt1 == ShiftAmt2) {
6642 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6643 if (I.getOpcode() == Instruction::Shl) {
6644 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006645 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006646 }
6647 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6648 if (I.getOpcode() == Instruction::LShr) {
6649 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006650 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 }
6652 // We can simplify ((X << C) >>s C) into a trunc + sext.
6653 // NOTE: we could do this for any C, but that would make 'unusual' integer
6654 // types. For now, just stick to ones well-supported by the code
6655 // generators.
6656 const Type *SExtType = 0;
6657 switch (Ty->getBitWidth() - ShiftAmt1) {
6658 case 1 :
6659 case 8 :
6660 case 16 :
6661 case 32 :
6662 case 64 :
6663 case 128:
6664 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6665 break;
6666 default: break;
6667 }
6668 if (SExtType) {
6669 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6670 InsertNewInstBefore(NewTrunc, I);
6671 return new SExtInst(NewTrunc, Ty);
6672 }
6673 // Otherwise, we can't handle it yet.
6674 } else if (ShiftAmt1 < ShiftAmt2) {
6675 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6676
6677 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6678 if (I.getOpcode() == Instruction::Shl) {
6679 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6680 ShiftOp->getOpcode() == Instruction::AShr);
6681 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006682 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 InsertNewInstBefore(Shift, I);
6684
6685 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006686 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006687 }
6688
6689 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6690 if (I.getOpcode() == Instruction::LShr) {
6691 assert(ShiftOp->getOpcode() == Instruction::Shl);
6692 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006693 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006694 InsertNewInstBefore(Shift, I);
6695
6696 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006697 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 }
6699
6700 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6701 } else {
6702 assert(ShiftAmt2 < ShiftAmt1);
6703 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6704
6705 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6706 if (I.getOpcode() == Instruction::Shl) {
6707 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6708 ShiftOp->getOpcode() == Instruction::AShr);
6709 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006710 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006711 ConstantInt::get(Ty, ShiftDiff));
6712 InsertNewInstBefore(Shift, I);
6713
6714 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006715 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716 }
6717
6718 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6719 if (I.getOpcode() == Instruction::LShr) {
6720 assert(ShiftOp->getOpcode() == Instruction::Shl);
6721 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006722 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006723 InsertNewInstBefore(Shift, I);
6724
6725 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006726 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 }
6728
6729 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6730 }
6731 }
6732 return 0;
6733}
6734
6735
6736/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6737/// expression. If so, decompose it, returning some value X, such that Val is
6738/// X*Scale+Offset.
6739///
6740static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6741 int &Offset) {
6742 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6743 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6744 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006745 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006746 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006747 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6748 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6749 if (I->getOpcode() == Instruction::Shl) {
6750 // This is a value scaled by '1 << the shift amt'.
6751 Scale = 1U << RHS->getZExtValue();
6752 Offset = 0;
6753 return I->getOperand(0);
6754 } else if (I->getOpcode() == Instruction::Mul) {
6755 // This value is scaled by 'RHS'.
6756 Scale = RHS->getZExtValue();
6757 Offset = 0;
6758 return I->getOperand(0);
6759 } else if (I->getOpcode() == Instruction::Add) {
6760 // We have X+C. Check to see if we really have (X*C2)+C1,
6761 // where C1 is divisible by C2.
6762 unsigned SubScale;
6763 Value *SubVal =
6764 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6765 Offset += RHS->getZExtValue();
6766 Scale = SubScale;
6767 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006768 }
6769 }
6770 }
6771
6772 // Otherwise, we can't look past this.
6773 Scale = 1;
6774 Offset = 0;
6775 return Val;
6776}
6777
6778
6779/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6780/// try to eliminate the cast by moving the type information into the alloc.
6781Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6782 AllocationInst &AI) {
6783 const PointerType *PTy = cast<PointerType>(CI.getType());
6784
6785 // Remove any uses of AI that are dead.
6786 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6787
6788 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6789 Instruction *User = cast<Instruction>(*UI++);
6790 if (isInstructionTriviallyDead(User)) {
6791 while (UI != E && *UI == User)
6792 ++UI; // If this instruction uses AI more than once, don't break UI.
6793
6794 ++NumDeadInst;
6795 DOUT << "IC: DCE: " << *User;
6796 EraseInstFromFunction(*User);
6797 }
6798 }
6799
6800 // Get the type really allocated and the type casted to.
6801 const Type *AllocElTy = AI.getAllocatedType();
6802 const Type *CastElTy = PTy->getElementType();
6803 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6804
6805 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6806 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6807 if (CastElTyAlign < AllocElTyAlign) return 0;
6808
6809 // If the allocation has multiple uses, only promote it if we are strictly
6810 // increasing the alignment of the resultant allocation. If we keep it the
6811 // same, we open the door to infinite loops of various kinds.
6812 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6813
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006814 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6815 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006816 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6817
6818 // See if we can satisfy the modulus by pulling a scale out of the array
6819 // size argument.
6820 unsigned ArraySizeScale;
6821 int ArrayOffset;
6822 Value *NumElements = // See if the array size is a decomposable linear expr.
6823 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6824
6825 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6826 // do the xform.
6827 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6828 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6829
6830 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6831 Value *Amt = 0;
6832 if (Scale == 1) {
6833 Amt = NumElements;
6834 } else {
6835 // If the allocation size is constant, form a constant mul expression
6836 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6837 if (isa<ConstantInt>(NumElements))
6838 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6839 // otherwise multiply the amount and the number of elements
6840 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006841 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842 Amt = InsertNewInstBefore(Tmp, AI);
6843 }
6844 }
6845
6846 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6847 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00006848 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006849 Amt = InsertNewInstBefore(Tmp, AI);
6850 }
6851
6852 AllocationInst *New;
6853 if (isa<MallocInst>(AI))
6854 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6855 else
6856 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6857 InsertNewInstBefore(New, AI);
6858 New->takeName(&AI);
6859
6860 // If the allocation has multiple uses, insert a cast and change all things
6861 // that used it to use the new cast. This will also hack on CI, but it will
6862 // die soon.
6863 if (!AI.hasOneUse()) {
6864 AddUsesToWorkList(AI);
6865 // New is the allocation instruction, pointer typed. AI is the original
6866 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6867 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6868 InsertNewInstBefore(NewCast, AI);
6869 AI.replaceAllUsesWith(NewCast);
6870 }
6871 return ReplaceInstUsesWith(CI, New);
6872}
6873
6874/// CanEvaluateInDifferentType - Return true if we can take the specified value
6875/// and return it as type Ty without inserting any new casts and without
6876/// changing the computed value. This is used by code that tries to decide
6877/// whether promoting or shrinking integer operations to wider or smaller types
6878/// will allow us to eliminate a truncate or extend.
6879///
6880/// This is a truncation operation if Ty is smaller than V->getType(), or an
6881/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00006882bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6883 unsigned CastOpc,
6884 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 // We can always evaluate constants in another type.
6886 if (isa<ConstantInt>(V))
6887 return true;
6888
6889 Instruction *I = dyn_cast<Instruction>(V);
6890 if (!I) return false;
6891
6892 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6893
Chris Lattneref70bb82007-08-02 06:11:14 +00006894 // If this is an extension or truncate, we can often eliminate it.
6895 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6896 // If this is a cast from the destination type, we can trivially eliminate
6897 // it, and this will remove a cast overall.
6898 if (I->getOperand(0)->getType() == Ty) {
6899 // If the first operand is itself a cast, and is eliminable, do not count
6900 // this as an eliminable cast. We would prefer to eliminate those two
6901 // casts first.
6902 if (!isa<CastInst>(I->getOperand(0)))
6903 ++NumCastsRemoved;
6904 return true;
6905 }
6906 }
6907
6908 // We can't extend or shrink something that has multiple uses: doing so would
6909 // require duplicating the instruction in general, which isn't profitable.
6910 if (!I->hasOneUse()) return false;
6911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006912 switch (I->getOpcode()) {
6913 case Instruction::Add:
6914 case Instruction::Sub:
6915 case Instruction::And:
6916 case Instruction::Or:
6917 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006919 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6920 NumCastsRemoved) &&
6921 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6922 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006923
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006924 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006925 // A multiply can be truncated by truncating its operands.
6926 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6927 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6928 NumCastsRemoved) &&
6929 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6930 NumCastsRemoved);
6931
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006932 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006933 // If we are truncating the result of this SHL, and if it's a shift of a
6934 // constant amount, we can always perform a SHL in a smaller type.
6935 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6936 uint32_t BitWidth = Ty->getBitWidth();
6937 if (BitWidth < OrigTy->getBitWidth() &&
6938 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006939 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6940 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006941 }
6942 break;
6943 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006944 // If this is a truncate of a logical shr, we can truncate it to a smaller
6945 // lshr iff we know that the bits we would otherwise be shifting in are
6946 // already zeros.
6947 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6948 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6949 uint32_t BitWidth = Ty->getBitWidth();
6950 if (BitWidth < OrigBitWidth &&
6951 MaskedValueIsZero(I->getOperand(0),
6952 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6953 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006954 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6955 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006956 }
6957 }
6958 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006959 case Instruction::ZExt:
6960 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006961 case Instruction::Trunc:
6962 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006963 // can safely replace it. Note that replacing it does not reduce the number
6964 // of casts in the input.
6965 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006966 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006968 break;
6969 default:
6970 // TODO: Can handle more cases here.
6971 break;
6972 }
6973
6974 return false;
6975}
6976
6977/// EvaluateInDifferentType - Given an expression that
6978/// CanEvaluateInDifferentType returns true for, actually insert the code to
6979/// evaluate the expression.
6980Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6981 bool isSigned) {
6982 if (Constant *C = dyn_cast<Constant>(V))
6983 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6984
6985 // Otherwise, it must be an instruction.
6986 Instruction *I = cast<Instruction>(V);
6987 Instruction *Res = 0;
6988 switch (I->getOpcode()) {
6989 case Instruction::Add:
6990 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006991 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006992 case Instruction::And:
6993 case Instruction::Or:
6994 case Instruction::Xor:
6995 case Instruction::AShr:
6996 case Instruction::LShr:
6997 case Instruction::Shl: {
6998 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6999 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007000 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007001 LHS, RHS, I->getName());
7002 break;
7003 }
7004 case Instruction::Trunc:
7005 case Instruction::ZExt:
7006 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007007 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007008 // just return the source. There's no need to insert it because it is not
7009 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007010 if (I->getOperand(0)->getType() == Ty)
7011 return I->getOperand(0);
7012
Chris Lattneref70bb82007-08-02 06:11:14 +00007013 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007014 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007015 Ty, I->getName());
7016 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007017 default:
7018 // TODO: Can handle more cases here.
7019 assert(0 && "Unreachable!");
7020 break;
7021 }
7022
7023 return InsertNewInstBefore(Res, *I);
7024}
7025
7026/// @brief Implement the transforms common to all CastInst visitors.
7027Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7028 Value *Src = CI.getOperand(0);
7029
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007030 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7031 // eliminate it now.
7032 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7033 if (Instruction::CastOps opc =
7034 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7035 // The first cast (CSrc) is eliminable so we need to fix up or replace
7036 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007037 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007038 }
7039 }
7040
7041 // If we are casting a select then fold the cast into the select
7042 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7043 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7044 return NV;
7045
7046 // If we are casting a PHI then fold the cast into the PHI
7047 if (isa<PHINode>(Src))
7048 if (Instruction *NV = FoldOpIntoPhi(CI))
7049 return NV;
7050
7051 return 0;
7052}
7053
7054/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7055Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7056 Value *Src = CI.getOperand(0);
7057
7058 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7059 // If casting the result of a getelementptr instruction with no offset, turn
7060 // this into a cast of the original pointer!
7061 if (GEP->hasAllZeroIndices()) {
7062 // Changing the cast operand is usually not a good idea but it is safe
7063 // here because the pointer operand is being replaced with another
7064 // pointer operand so the opcode doesn't need to change.
7065 AddToWorkList(GEP);
7066 CI.setOperand(0, GEP->getOperand(0));
7067 return &CI;
7068 }
7069
7070 // If the GEP has a single use, and the base pointer is a bitcast, and the
7071 // GEP computes a constant offset, see if we can convert these three
7072 // instructions into fewer. This typically happens with unions and other
7073 // non-type-safe code.
7074 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7075 if (GEP->hasAllConstantIndices()) {
7076 // We are guaranteed to get a constant from EmitGEPOffset.
7077 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7078 int64_t Offset = OffsetV->getSExtValue();
7079
7080 // Get the base pointer input of the bitcast, and the type it points to.
7081 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7082 const Type *GEPIdxTy =
7083 cast<PointerType>(OrigBase->getType())->getElementType();
7084 if (GEPIdxTy->isSized()) {
7085 SmallVector<Value*, 8> NewIndices;
7086
7087 // Start with the index over the outer type. Note that the type size
7088 // might be zero (even if the offset isn't zero) if the indexed type
7089 // is something like [0 x {int, int}]
7090 const Type *IntPtrTy = TD->getIntPtrType();
7091 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007092 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007093 FirstIdx = Offset/TySize;
7094 Offset %= TySize;
7095
7096 // Handle silly modulus not returning values values [0..TySize).
7097 if (Offset < 0) {
7098 --FirstIdx;
7099 Offset += TySize;
7100 assert(Offset >= 0);
7101 }
7102 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7103 }
7104
7105 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7106
7107 // Index into the types. If we fail, set OrigBase to null.
7108 while (Offset) {
7109 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7110 const StructLayout *SL = TD->getStructLayout(STy);
7111 if (Offset < (int64_t)SL->getSizeInBytes()) {
7112 unsigned Elt = SL->getElementContainingOffset(Offset);
7113 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7114
7115 Offset -= SL->getElementOffset(Elt);
7116 GEPIdxTy = STy->getElementType(Elt);
7117 } else {
7118 // Otherwise, we can't index into this, bail out.
7119 Offset = 0;
7120 OrigBase = 0;
7121 }
7122 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7123 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007124 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7126 Offset %= EltSize;
7127 } else {
7128 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7129 }
7130 GEPIdxTy = STy->getElementType();
7131 } else {
7132 // Otherwise, we can't index into this, bail out.
7133 Offset = 0;
7134 OrigBase = 0;
7135 }
7136 }
7137 if (OrigBase) {
7138 // If we were able to index down into an element, create the GEP
7139 // and bitcast the result. This eliminates one bitcast, potentially
7140 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007141 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7142 NewIndices.begin(),
7143 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 InsertNewInstBefore(NGEP, CI);
7145 NGEP->takeName(GEP);
7146
7147 if (isa<BitCastInst>(CI))
7148 return new BitCastInst(NGEP, CI.getType());
7149 assert(isa<PtrToIntInst>(CI));
7150 return new PtrToIntInst(NGEP, CI.getType());
7151 }
7152 }
7153 }
7154 }
7155 }
7156
7157 return commonCastTransforms(CI);
7158}
7159
7160
7161
7162/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7163/// integer types. This function implements the common transforms for all those
7164/// cases.
7165/// @brief Implement the transforms common to CastInst with integer operands
7166Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7167 if (Instruction *Result = commonCastTransforms(CI))
7168 return Result;
7169
7170 Value *Src = CI.getOperand(0);
7171 const Type *SrcTy = Src->getType();
7172 const Type *DestTy = CI.getType();
7173 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7174 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7175
7176 // See if we can simplify any instructions used by the LHS whose sole
7177 // purpose is to compute bits we don't care about.
7178 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7179 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7180 KnownZero, KnownOne))
7181 return &CI;
7182
7183 // If the source isn't an instruction or has more than one use then we
7184 // can't do anything more.
7185 Instruction *SrcI = dyn_cast<Instruction>(Src);
7186 if (!SrcI || !Src->hasOneUse())
7187 return 0;
7188
7189 // Attempt to propagate the cast into the instruction for int->int casts.
7190 int NumCastsRemoved = 0;
7191 if (!isa<BitCastInst>(CI) &&
7192 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007193 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007194 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007195 // eliminates the cast, so it is always a win. If this is a zero-extension,
7196 // we need to do an AND to maintain the clear top-part of the computation,
7197 // so we require that the input have eliminated at least one cast. If this
7198 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007199 // require that two casts have been eliminated.
7200 bool DoXForm;
7201 switch (CI.getOpcode()) {
7202 default:
7203 // All the others use floating point so we shouldn't actually
7204 // get here because of the check above.
7205 assert(0 && "Unknown cast type");
7206 case Instruction::Trunc:
7207 DoXForm = true;
7208 break;
7209 case Instruction::ZExt:
7210 DoXForm = NumCastsRemoved >= 1;
7211 break;
7212 case Instruction::SExt:
7213 DoXForm = NumCastsRemoved >= 2;
7214 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007215 }
7216
7217 if (DoXForm) {
7218 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7219 CI.getOpcode() == Instruction::SExt);
7220 assert(Res->getType() == DestTy);
7221 switch (CI.getOpcode()) {
7222 default: assert(0 && "Unknown cast type!");
7223 case Instruction::Trunc:
7224 case Instruction::BitCast:
7225 // Just replace this cast with the result.
7226 return ReplaceInstUsesWith(CI, Res);
7227 case Instruction::ZExt: {
7228 // We need to emit an AND to clear the high bits.
7229 assert(SrcBitSize < DestBitSize && "Not a zext?");
7230 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7231 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007232 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007233 }
7234 case Instruction::SExt:
7235 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007236 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007237 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7238 CI), DestTy);
7239 }
7240 }
7241 }
7242
7243 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7244 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7245
7246 switch (SrcI->getOpcode()) {
7247 case Instruction::Add:
7248 case Instruction::Mul:
7249 case Instruction::And:
7250 case Instruction::Or:
7251 case Instruction::Xor:
7252 // If we are discarding information, rewrite.
7253 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7254 // Don't insert two casts if they cannot be eliminated. We allow
7255 // two casts to be inserted if the sizes are the same. This could
7256 // only be converting signedness, which is a noop.
7257 if (DestBitSize == SrcBitSize ||
7258 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7259 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7260 Instruction::CastOps opcode = CI.getOpcode();
7261 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7262 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007263 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007264 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7265 }
7266 }
7267
7268 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7269 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7270 SrcI->getOpcode() == Instruction::Xor &&
7271 Op1 == ConstantInt::getTrue() &&
7272 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7273 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007274 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007275 }
7276 break;
7277 case Instruction::SDiv:
7278 case Instruction::UDiv:
7279 case Instruction::SRem:
7280 case Instruction::URem:
7281 // If we are just changing the sign, rewrite.
7282 if (DestBitSize == SrcBitSize) {
7283 // Don't insert two casts if they cannot be eliminated. We allow
7284 // two casts to be inserted if the sizes are the same. This could
7285 // only be converting signedness, which is a noop.
7286 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7287 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7288 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7289 Op0, DestTy, SrcI);
7290 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7291 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007292 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007293 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7294 }
7295 }
7296 break;
7297
7298 case Instruction::Shl:
7299 // Allow changing the sign of the source operand. Do not allow
7300 // changing the size of the shift, UNLESS the shift amount is a
7301 // constant. We must not change variable sized shifts to a smaller
7302 // size, because it is undefined to shift more bits out than exist
7303 // in the value.
7304 if (DestBitSize == SrcBitSize ||
7305 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7306 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7307 Instruction::BitCast : Instruction::Trunc);
7308 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7309 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007310 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007311 }
7312 break;
7313 case Instruction::AShr:
7314 // If this is a signed shr, and if all bits shifted in are about to be
7315 // truncated off, turn it into an unsigned shr to allow greater
7316 // simplifications.
7317 if (DestBitSize < SrcBitSize &&
7318 isa<ConstantInt>(Op1)) {
7319 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7320 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7321 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007322 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007323 }
7324 }
7325 break;
7326 }
7327 return 0;
7328}
7329
7330Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7331 if (Instruction *Result = commonIntCastTransforms(CI))
7332 return Result;
7333
7334 Value *Src = CI.getOperand(0);
7335 const Type *Ty = CI.getType();
7336 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7337 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7338
7339 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7340 switch (SrcI->getOpcode()) {
7341 default: break;
7342 case Instruction::LShr:
7343 // We can shrink lshr to something smaller if we know the bits shifted in
7344 // are already zeros.
7345 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7346 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7347
7348 // Get a mask for the bits shifting in.
7349 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7350 Value* SrcIOp0 = SrcI->getOperand(0);
7351 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7352 if (ShAmt >= DestBitWidth) // All zeros.
7353 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7354
7355 // Okay, we can shrink this. Truncate the input, then return a new
7356 // shift.
7357 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7358 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7359 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007360 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007361 }
7362 } else { // This is a variable shr.
7363
7364 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7365 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7366 // loop-invariant and CSE'd.
7367 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7368 Value *One = ConstantInt::get(SrcI->getType(), 1);
7369
7370 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007371 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007372 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007373 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007374 SrcI->getOperand(0),
7375 "tmp"), CI);
7376 Value *Zero = Constant::getNullValue(V->getType());
7377 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7378 }
7379 }
7380 break;
7381 }
7382 }
7383
7384 return 0;
7385}
7386
Evan Chenge3779cf2008-03-24 00:21:34 +00007387/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7388/// in order to eliminate the icmp.
7389Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7390 bool DoXform) {
7391 // If we are just checking for a icmp eq of a single bit and zext'ing it
7392 // to an integer, then shift the bit to the appropriate place and then
7393 // cast to integer to avoid the comparison.
7394 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7395 const APInt &Op1CV = Op1C->getValue();
7396
7397 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7398 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7399 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7400 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7401 if (!DoXform) return ICI;
7402
7403 Value *In = ICI->getOperand(0);
7404 Value *Sh = ConstantInt::get(In->getType(),
7405 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007406 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007407 In->getName()+".lobit"),
7408 CI);
7409 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007410 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007411 false/*ZExt*/, "tmp", &CI);
7412
7413 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7414 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007415 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007416 In->getName()+".not"),
7417 CI);
7418 }
7419
7420 return ReplaceInstUsesWith(CI, In);
7421 }
7422
7423
7424
7425 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7426 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7427 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7428 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7429 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7430 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7431 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7432 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7433 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7434 // This only works for EQ and NE
7435 ICI->isEquality()) {
7436 // If Op1C some other power of two, convert:
7437 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7438 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7439 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7440 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7441
7442 APInt KnownZeroMask(~KnownZero);
7443 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7444 if (!DoXform) return ICI;
7445
7446 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7447 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7448 // (X&4) == 2 --> false
7449 // (X&4) != 2 --> true
7450 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7451 Res = ConstantExpr::getZExt(Res, CI.getType());
7452 return ReplaceInstUsesWith(CI, Res);
7453 }
7454
7455 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7456 Value *In = ICI->getOperand(0);
7457 if (ShiftAmt) {
7458 // Perform a logical shr by shiftamt.
7459 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007460 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007461 ConstantInt::get(In->getType(), ShiftAmt),
7462 In->getName()+".lobit"), CI);
7463 }
7464
7465 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7466 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007467 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007468 InsertNewInstBefore(cast<Instruction>(In), CI);
7469 }
7470
7471 if (CI.getType() == In->getType())
7472 return ReplaceInstUsesWith(CI, In);
7473 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007474 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007475 }
7476 }
7477 }
7478
7479 return 0;
7480}
7481
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007482Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7483 // If one of the common conversion will work ..
7484 if (Instruction *Result = commonIntCastTransforms(CI))
7485 return Result;
7486
7487 Value *Src = CI.getOperand(0);
7488
7489 // If this is a cast of a cast
7490 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7491 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7492 // types and if the sizes are just right we can convert this into a logical
7493 // 'and' which will be much cheaper than the pair of casts.
7494 if (isa<TruncInst>(CSrc)) {
7495 // Get the sizes of the types involved
7496 Value *A = CSrc->getOperand(0);
7497 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7498 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7499 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7500 // If we're actually extending zero bits and the trunc is a no-op
7501 if (MidSize < DstSize && SrcSize == DstSize) {
7502 // Replace both of the casts with an And of the type mask.
7503 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7504 Constant *AndConst = ConstantInt::get(AndValue);
7505 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007506 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507 // Unfortunately, if the type changed, we need to cast it back.
7508 if (And->getType() != CI.getType()) {
7509 And->setName(CSrc->getName()+".mask");
7510 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007511 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007512 }
7513 return And;
7514 }
7515 }
7516 }
7517
Evan Chenge3779cf2008-03-24 00:21:34 +00007518 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7519 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007520
Evan Chenge3779cf2008-03-24 00:21:34 +00007521 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7522 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7523 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7524 // of the (zext icmp) will be transformed.
7525 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7526 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7527 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7528 (transformZExtICmp(LHS, CI, false) ||
7529 transformZExtICmp(RHS, CI, false))) {
7530 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7531 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007532 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007533 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007534 }
7535
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007536 return 0;
7537}
7538
7539Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7540 if (Instruction *I = commonIntCastTransforms(CI))
7541 return I;
7542
7543 Value *Src = CI.getOperand(0);
7544
7545 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7546 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7547 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7548 // If we are just checking for a icmp eq of a single bit and zext'ing it
7549 // to an integer, then shift the bit to the appropriate place and then
7550 // cast to integer to avoid the comparison.
7551 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7552 const APInt &Op1CV = Op1C->getValue();
7553
7554 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7555 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7556 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7557 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7558 Value *In = ICI->getOperand(0);
7559 Value *Sh = ConstantInt::get(In->getType(),
7560 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007561 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007562 In->getName()+".lobit"),
7563 CI);
7564 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007565 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007566 true/*SExt*/, "tmp", &CI);
7567
7568 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007569 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007570 In->getName()+".not"), CI);
7571
7572 return ReplaceInstUsesWith(CI, In);
7573 }
7574 }
7575 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00007576
7577 // See if the value being truncated is already sign extended. If so, just
7578 // eliminate the trunc/sext pair.
7579 if (getOpcode(Src) == Instruction::Trunc) {
7580 Value *Op = cast<User>(Src)->getOperand(0);
7581 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7582 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7583 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7584 unsigned NumSignBits = ComputeNumSignBits(Op);
7585
7586 if (OpBits == DestBits) {
7587 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7588 // bits, it is already ready.
7589 if (NumSignBits > DestBits-MidBits)
7590 return ReplaceInstUsesWith(CI, Op);
7591 } else if (OpBits < DestBits) {
7592 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7593 // bits, just sext from i32.
7594 if (NumSignBits > OpBits-MidBits)
7595 return new SExtInst(Op, CI.getType(), "tmp");
7596 } else {
7597 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7598 // bits, just truncate to i32.
7599 if (NumSignBits > OpBits-MidBits)
7600 return new TruncInst(Op, CI.getType(), "tmp");
7601 }
7602 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603
7604 return 0;
7605}
7606
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007607/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7608/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007609static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007610 APFloat F = CFP->getValueAPF();
7611 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007612 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007613 return 0;
7614}
7615
7616/// LookThroughFPExtensions - If this is an fp extension instruction, look
7617/// through it until we get the source value.
7618static Value *LookThroughFPExtensions(Value *V) {
7619 if (Instruction *I = dyn_cast<Instruction>(V))
7620 if (I->getOpcode() == Instruction::FPExt)
7621 return LookThroughFPExtensions(I->getOperand(0));
7622
7623 // If this value is a constant, return the constant in the smallest FP type
7624 // that can accurately represent it. This allows us to turn
7625 // (float)((double)X+2.0) into x+2.0f.
7626 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7627 if (CFP->getType() == Type::PPC_FP128Ty)
7628 return V; // No constant folding of this.
7629 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007630 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007631 return V;
7632 if (CFP->getType() == Type::DoubleTy)
7633 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007634 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007635 return V;
7636 // Don't try to shrink to various long double types.
7637 }
7638
7639 return V;
7640}
7641
7642Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7643 if (Instruction *I = commonCastTransforms(CI))
7644 return I;
7645
7646 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7647 // smaller than the destination type, we can eliminate the truncate by doing
7648 // the add as the smaller type. This applies to add/sub/mul/div as well as
7649 // many builtins (sqrt, etc).
7650 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7651 if (OpI && OpI->hasOneUse()) {
7652 switch (OpI->getOpcode()) {
7653 default: break;
7654 case Instruction::Add:
7655 case Instruction::Sub:
7656 case Instruction::Mul:
7657 case Instruction::FDiv:
7658 case Instruction::FRem:
7659 const Type *SrcTy = OpI->getType();
7660 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7661 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7662 if (LHSTrunc->getType() != SrcTy &&
7663 RHSTrunc->getType() != SrcTy) {
7664 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7665 // If the source types were both smaller than the destination type of
7666 // the cast, do this xform.
7667 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7668 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7669 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7670 CI.getType(), CI);
7671 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7672 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007673 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007674 }
7675 }
7676 break;
7677 }
7678 }
7679 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007680}
7681
7682Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7683 return commonCastTransforms(CI);
7684}
7685
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007686Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7687 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7688 // mantissa to accurately represent all values of X. For example, do not
7689 // do this with i64->float->i64.
7690 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7691 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7692 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner9ce836b2008-05-19 21:17:23 +00007693 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007694 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7695
7696 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007697}
7698
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007699Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7700 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7701 // mantissa to accurately represent all values of X. For example, do not
7702 // do this with i64->float->i64.
7703 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7704 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7705 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner9ce836b2008-05-19 21:17:23 +00007706 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007707 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7708
7709 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007710}
7711
7712Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7713 return commonCastTransforms(CI);
7714}
7715
7716Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7717 return commonCastTransforms(CI);
7718}
7719
7720Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7721 return commonPointerCastTransforms(CI);
7722}
7723
Chris Lattner7c1626482008-01-08 07:23:51 +00007724Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7725 if (Instruction *I = commonCastTransforms(CI))
7726 return I;
7727
7728 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7729 if (!DestPointee->isSized()) return 0;
7730
7731 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7732 ConstantInt *Cst;
7733 Value *X;
7734 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7735 m_ConstantInt(Cst)))) {
7736 // If the source and destination operands have the same type, see if this
7737 // is a single-index GEP.
7738 if (X->getType() == CI.getType()) {
7739 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007740 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007741
7742 // Convert the constant to intptr type.
7743 APInt Offset = Cst->getValue();
7744 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7745
7746 // If Offset is evenly divisible by Size, we can do this xform.
7747 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7748 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007749 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007750 }
7751 }
7752 // TODO: Could handle other cases, e.g. where add is indexing into field of
7753 // struct etc.
7754 } else if (CI.getOperand(0)->hasOneUse() &&
7755 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7756 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7757 // "inttoptr+GEP" instead of "add+intptr".
7758
7759 // Get the size of the pointee type.
7760 uint64_t Size = TD->getABITypeSize(DestPointee);
7761
7762 // Convert the constant to intptr type.
7763 APInt Offset = Cst->getValue();
7764 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7765
7766 // If Offset is evenly divisible by Size, we can do this xform.
7767 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7768 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7769
7770 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7771 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007772 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007773 }
7774 }
7775 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007776}
7777
7778Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7779 // If the operands are integer typed then apply the integer transforms,
7780 // otherwise just apply the common ones.
7781 Value *Src = CI.getOperand(0);
7782 const Type *SrcTy = Src->getType();
7783 const Type *DestTy = CI.getType();
7784
7785 if (SrcTy->isInteger() && DestTy->isInteger()) {
7786 if (Instruction *Result = commonIntCastTransforms(CI))
7787 return Result;
7788 } else if (isa<PointerType>(SrcTy)) {
7789 if (Instruction *I = commonPointerCastTransforms(CI))
7790 return I;
7791 } else {
7792 if (Instruction *Result = commonCastTransforms(CI))
7793 return Result;
7794 }
7795
7796
7797 // Get rid of casts from one type to the same type. These are useless and can
7798 // be replaced by the operand.
7799 if (DestTy == Src->getType())
7800 return ReplaceInstUsesWith(CI, Src);
7801
7802 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7803 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7804 const Type *DstElTy = DstPTy->getElementType();
7805 const Type *SrcElTy = SrcPTy->getElementType();
7806
Nate Begemandf5b3612008-03-31 00:22:16 +00007807 // If the address spaces don't match, don't eliminate the bitcast, which is
7808 // required for changing types.
7809 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7810 return 0;
7811
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007812 // If we are casting a malloc or alloca to a pointer to a type of the same
7813 // size, rewrite the allocation instruction to allocate the "right" type.
7814 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7815 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7816 return V;
7817
7818 // If the source and destination are pointers, and this cast is equivalent
7819 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7820 // This can enhance SROA and other transforms that want type-safe pointers.
7821 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7822 unsigned NumZeros = 0;
7823 while (SrcElTy != DstElTy &&
7824 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7825 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7826 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7827 ++NumZeros;
7828 }
7829
7830 // If we found a path from the src to dest, create the getelementptr now.
7831 if (SrcElTy == DstElTy) {
7832 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007833 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7834 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007835 }
7836 }
7837
7838 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7839 if (SVI->hasOneUse()) {
7840 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7841 // a bitconvert to a vector with the same # elts.
7842 if (isa<VectorType>(DestTy) &&
7843 cast<VectorType>(DestTy)->getNumElements() ==
7844 SVI->getType()->getNumElements()) {
7845 CastInst *Tmp;
7846 // If either of the operands is a cast from CI.getType(), then
7847 // evaluating the shuffle in the casted destination's type will allow
7848 // us to eliminate at least one cast.
7849 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7850 Tmp->getOperand(0)->getType() == DestTy) ||
7851 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7852 Tmp->getOperand(0)->getType() == DestTy)) {
7853 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7854 SVI->getOperand(0), DestTy, &CI);
7855 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7856 SVI->getOperand(1), DestTy, &CI);
7857 // Return a new shuffle vector. Use the same element ID's, as we
7858 // know the vector types match #elts.
7859 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7860 }
7861 }
7862 }
7863 }
7864 return 0;
7865}
7866
7867/// GetSelectFoldableOperands - We want to turn code that looks like this:
7868/// %C = or %A, %B
7869/// %D = select %cond, %C, %A
7870/// into:
7871/// %C = select %cond, %B, 0
7872/// %D = or %A, %C
7873///
7874/// Assuming that the specified instruction is an operand to the select, return
7875/// a bitmask indicating which operands of this instruction are foldable if they
7876/// equal the other incoming value of the select.
7877///
7878static unsigned GetSelectFoldableOperands(Instruction *I) {
7879 switch (I->getOpcode()) {
7880 case Instruction::Add:
7881 case Instruction::Mul:
7882 case Instruction::And:
7883 case Instruction::Or:
7884 case Instruction::Xor:
7885 return 3; // Can fold through either operand.
7886 case Instruction::Sub: // Can only fold on the amount subtracted.
7887 case Instruction::Shl: // Can only fold on the shift amount.
7888 case Instruction::LShr:
7889 case Instruction::AShr:
7890 return 1;
7891 default:
7892 return 0; // Cannot fold
7893 }
7894}
7895
7896/// GetSelectFoldableConstant - For the same transformation as the previous
7897/// function, return the identity constant that goes into the select.
7898static Constant *GetSelectFoldableConstant(Instruction *I) {
7899 switch (I->getOpcode()) {
7900 default: assert(0 && "This cannot happen!"); abort();
7901 case Instruction::Add:
7902 case Instruction::Sub:
7903 case Instruction::Or:
7904 case Instruction::Xor:
7905 case Instruction::Shl:
7906 case Instruction::LShr:
7907 case Instruction::AShr:
7908 return Constant::getNullValue(I->getType());
7909 case Instruction::And:
7910 return Constant::getAllOnesValue(I->getType());
7911 case Instruction::Mul:
7912 return ConstantInt::get(I->getType(), 1);
7913 }
7914}
7915
7916/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7917/// have the same opcode and only one use each. Try to simplify this.
7918Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7919 Instruction *FI) {
7920 if (TI->getNumOperands() == 1) {
7921 // If this is a non-volatile load or a cast from the same type,
7922 // merge.
7923 if (TI->isCast()) {
7924 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7925 return 0;
7926 } else {
7927 return 0; // unknown unary op.
7928 }
7929
7930 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007931 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7932 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007933 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007934 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 TI->getType());
7936 }
7937
7938 // Only handle binary operators here.
7939 if (!isa<BinaryOperator>(TI))
7940 return 0;
7941
7942 // Figure out if the operations have any operands in common.
7943 Value *MatchOp, *OtherOpT, *OtherOpF;
7944 bool MatchIsOpZero;
7945 if (TI->getOperand(0) == FI->getOperand(0)) {
7946 MatchOp = TI->getOperand(0);
7947 OtherOpT = TI->getOperand(1);
7948 OtherOpF = FI->getOperand(1);
7949 MatchIsOpZero = true;
7950 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7951 MatchOp = TI->getOperand(1);
7952 OtherOpT = TI->getOperand(0);
7953 OtherOpF = FI->getOperand(0);
7954 MatchIsOpZero = false;
7955 } else if (!TI->isCommutative()) {
7956 return 0;
7957 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7958 MatchOp = TI->getOperand(0);
7959 OtherOpT = TI->getOperand(1);
7960 OtherOpF = FI->getOperand(0);
7961 MatchIsOpZero = true;
7962 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7963 MatchOp = TI->getOperand(1);
7964 OtherOpT = TI->getOperand(0);
7965 OtherOpF = FI->getOperand(1);
7966 MatchIsOpZero = true;
7967 } else {
7968 return 0;
7969 }
7970
7971 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007972 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7973 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007974 InsertNewInstBefore(NewSI, SI);
7975
7976 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7977 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00007978 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007979 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007980 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007981 }
7982 assert(0 && "Shouldn't get here");
7983 return 0;
7984}
7985
7986Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7987 Value *CondVal = SI.getCondition();
7988 Value *TrueVal = SI.getTrueValue();
7989 Value *FalseVal = SI.getFalseValue();
7990
7991 // select true, X, Y -> X
7992 // select false, X, Y -> Y
7993 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7994 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7995
7996 // select C, X, X -> X
7997 if (TrueVal == FalseVal)
7998 return ReplaceInstUsesWith(SI, TrueVal);
7999
8000 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8001 return ReplaceInstUsesWith(SI, FalseVal);
8002 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8003 return ReplaceInstUsesWith(SI, TrueVal);
8004 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8005 if (isa<Constant>(TrueVal))
8006 return ReplaceInstUsesWith(SI, TrueVal);
8007 else
8008 return ReplaceInstUsesWith(SI, FalseVal);
8009 }
8010
8011 if (SI.getType() == Type::Int1Ty) {
8012 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8013 if (C->getZExtValue()) {
8014 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008015 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008016 } else {
8017 // Change: A = select B, false, C --> A = and !B, C
8018 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008019 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008020 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008021 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008022 }
8023 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8024 if (C->getZExtValue() == false) {
8025 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008026 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008027 } else {
8028 // Change: A = select B, C, true --> A = or !B, C
8029 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008030 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008032 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008033 }
8034 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008035
8036 // select a, b, a -> a&b
8037 // select a, a, b -> a|b
8038 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008039 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008040 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008041 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008042 }
8043
8044 // Selecting between two integer constants?
8045 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8046 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8047 // select C, 1, 0 -> zext C to int
8048 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008049 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008050 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8051 // select C, 0, 1 -> zext !C to int
8052 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008053 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008054 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008055 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008056 }
8057
8058 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8059
8060 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8061
8062 // (x <s 0) ? -1 : 0 -> ashr x, 31
8063 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8064 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8065 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8066 // The comparison constant and the result are not neccessarily the
8067 // same width. Make an all-ones value by inserting a AShr.
8068 Value *X = IC->getOperand(0);
8069 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8070 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008071 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008072 ShAmt, "ones");
8073 InsertNewInstBefore(SRA, SI);
8074
8075 // Finally, convert to the type of the select RHS. We figure out
8076 // if this requires a SExt, Trunc or BitCast based on the sizes.
8077 Instruction::CastOps opc = Instruction::BitCast;
8078 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8079 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8080 if (SRASize < SISize)
8081 opc = Instruction::SExt;
8082 else if (SRASize > SISize)
8083 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008084 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008085 }
8086 }
8087
8088
8089 // If one of the constants is zero (we know they can't both be) and we
8090 // have an icmp instruction with zero, and we have an 'and' with the
8091 // non-constant value, eliminate this whole mess. This corresponds to
8092 // cases like this: ((X & 27) ? 27 : 0)
8093 if (TrueValC->isZero() || FalseValC->isZero())
8094 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8095 cast<Constant>(IC->getOperand(1))->isNullValue())
8096 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8097 if (ICA->getOpcode() == Instruction::And &&
8098 isa<ConstantInt>(ICA->getOperand(1)) &&
8099 (ICA->getOperand(1) == TrueValC ||
8100 ICA->getOperand(1) == FalseValC) &&
8101 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8102 // Okay, now we know that everything is set up, we just don't
8103 // know whether we have a icmp_ne or icmp_eq and whether the
8104 // true or false val is the zero.
8105 bool ShouldNotVal = !TrueValC->isZero();
8106 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8107 Value *V = ICA;
8108 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008109 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 Instruction::Xor, V, ICA->getOperand(1)), SI);
8111 return ReplaceInstUsesWith(SI, V);
8112 }
8113 }
8114 }
8115
8116 // See if we are selecting two values based on a comparison of the two values.
8117 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8118 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8119 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008120 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8121 // This is not safe in general for floating point:
8122 // consider X== -0, Y== +0.
8123 // It becomes safe if either operand is a nonzero constant.
8124 ConstantFP *CFPt, *CFPf;
8125 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8126 !CFPt->getValueAPF().isZero()) ||
8127 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8128 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008130 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008131 // Transform (X != Y) ? X : Y -> X
8132 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8133 return ReplaceInstUsesWith(SI, TrueVal);
8134 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8135
8136 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8137 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008138 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8139 // This is not safe in general for floating point:
8140 // consider X== -0, Y== +0.
8141 // It becomes safe if either operand is a nonzero constant.
8142 ConstantFP *CFPt, *CFPf;
8143 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8144 !CFPt->getValueAPF().isZero()) ||
8145 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8146 !CFPf->getValueAPF().isZero()))
8147 return ReplaceInstUsesWith(SI, FalseVal);
8148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008149 // Transform (X != Y) ? Y : X -> Y
8150 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8151 return ReplaceInstUsesWith(SI, TrueVal);
8152 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8153 }
8154 }
8155
8156 // See if we are selecting two values based on a comparison of the two values.
8157 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8158 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8159 // Transform (X == Y) ? X : Y -> Y
8160 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8161 return ReplaceInstUsesWith(SI, FalseVal);
8162 // Transform (X != Y) ? X : Y -> X
8163 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8164 return ReplaceInstUsesWith(SI, TrueVal);
8165 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8166
8167 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8168 // Transform (X == Y) ? Y : X -> X
8169 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8170 return ReplaceInstUsesWith(SI, FalseVal);
8171 // Transform (X != Y) ? Y : X -> Y
8172 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8173 return ReplaceInstUsesWith(SI, TrueVal);
8174 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8175 }
8176 }
8177
8178 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8179 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8180 if (TI->hasOneUse() && FI->hasOneUse()) {
8181 Instruction *AddOp = 0, *SubOp = 0;
8182
8183 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8184 if (TI->getOpcode() == FI->getOpcode())
8185 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8186 return IV;
8187
8188 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8189 // even legal for FP.
8190 if (TI->getOpcode() == Instruction::Sub &&
8191 FI->getOpcode() == Instruction::Add) {
8192 AddOp = FI; SubOp = TI;
8193 } else if (FI->getOpcode() == Instruction::Sub &&
8194 TI->getOpcode() == Instruction::Add) {
8195 AddOp = TI; SubOp = FI;
8196 }
8197
8198 if (AddOp) {
8199 Value *OtherAddOp = 0;
8200 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8201 OtherAddOp = AddOp->getOperand(1);
8202 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8203 OtherAddOp = AddOp->getOperand(0);
8204 }
8205
8206 if (OtherAddOp) {
8207 // So at this point we know we have (Y -> OtherAddOp):
8208 // select C, (add X, Y), (sub X, Z)
8209 Value *NegVal; // Compute -Z
8210 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8211 NegVal = ConstantExpr::getNeg(C);
8212 } else {
8213 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008214 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008215 }
8216
8217 Value *NewTrueOp = OtherAddOp;
8218 Value *NewFalseOp = NegVal;
8219 if (AddOp != TI)
8220 std::swap(NewTrueOp, NewFalseOp);
8221 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008222 SelectInst::Create(CondVal, NewTrueOp,
8223 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008224
8225 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008226 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008227 }
8228 }
8229 }
8230
8231 // See if we can fold the select into one of our operands.
8232 if (SI.getType()->isInteger()) {
8233 // See the comment above GetSelectFoldableOperands for a description of the
8234 // transformation we are doing here.
8235 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8236 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8237 !isa<Constant>(FalseVal))
8238 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8239 unsigned OpToFold = 0;
8240 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8241 OpToFold = 1;
8242 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8243 OpToFold = 2;
8244 }
8245
8246 if (OpToFold) {
8247 Constant *C = GetSelectFoldableConstant(TVI);
8248 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008249 SelectInst::Create(SI.getCondition(),
8250 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251 InsertNewInstBefore(NewSel, SI);
8252 NewSel->takeName(TVI);
8253 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008254 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255 else {
8256 assert(0 && "Unknown instruction!!");
8257 }
8258 }
8259 }
8260
8261 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8262 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8263 !isa<Constant>(TrueVal))
8264 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8265 unsigned OpToFold = 0;
8266 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8267 OpToFold = 1;
8268 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8269 OpToFold = 2;
8270 }
8271
8272 if (OpToFold) {
8273 Constant *C = GetSelectFoldableConstant(FVI);
8274 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008275 SelectInst::Create(SI.getCondition(), C,
8276 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008277 InsertNewInstBefore(NewSel, SI);
8278 NewSel->takeName(FVI);
8279 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008280 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 else
8282 assert(0 && "Unknown instruction!!");
8283 }
8284 }
8285 }
8286
8287 if (BinaryOperator::isNot(CondVal)) {
8288 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8289 SI.setOperand(1, FalseVal);
8290 SI.setOperand(2, TrueVal);
8291 return &SI;
8292 }
8293
8294 return 0;
8295}
8296
Dan Gohman2d648bb2008-04-10 18:43:06 +00008297/// EnforceKnownAlignment - If the specified pointer points to an object that
8298/// we control, modify the object's alignment to PrefAlign. This isn't
8299/// often possible though. If alignment is important, a more reliable approach
8300/// is to simply align all global variables and allocation instructions to
8301/// their preferred alignment from the beginning.
8302///
8303static unsigned EnforceKnownAlignment(Value *V,
8304 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008305
Dan Gohman2d648bb2008-04-10 18:43:06 +00008306 User *U = dyn_cast<User>(V);
8307 if (!U) return Align;
8308
8309 switch (getOpcode(U)) {
8310 default: break;
8311 case Instruction::BitCast:
8312 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8313 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008314 // If all indexes are zero, it is just the alignment of the base pointer.
8315 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008316 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8317 if (!isa<Constant>(U->getOperand(i)) ||
8318 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319 AllZeroOperands = false;
8320 break;
8321 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008322
8323 if (AllZeroOperands) {
8324 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008325 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008326 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008327 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008328 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008329 }
8330
8331 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8332 // If there is a large requested alignment and we can, bump up the alignment
8333 // of the global.
8334 if (!GV->isDeclaration()) {
8335 GV->setAlignment(PrefAlign);
8336 Align = PrefAlign;
8337 }
8338 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8339 // If there is a requested alignment and if this is an alloca, round up. We
8340 // don't do this for malloc, because some systems can't respect the request.
8341 if (isa<AllocaInst>(AI)) {
8342 AI->setAlignment(PrefAlign);
8343 Align = PrefAlign;
8344 }
8345 }
8346
8347 return Align;
8348}
8349
8350/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8351/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8352/// and it is more than the alignment of the ultimate object, see if we can
8353/// increase the alignment of the ultimate object, making this check succeed.
8354unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8355 unsigned PrefAlign) {
8356 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8357 sizeof(PrefAlign) * CHAR_BIT;
8358 APInt Mask = APInt::getAllOnesValue(BitWidth);
8359 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8360 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8361 unsigned TrailZ = KnownZero.countTrailingOnes();
8362 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8363
8364 if (PrefAlign > Align)
8365 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8366
8367 // We don't need to make any adjustment.
8368 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369}
8370
Chris Lattner00ae5132008-01-13 23:50:23 +00008371Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008372 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8373 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008374 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8375 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8376
8377 if (CopyAlign < MinAlign) {
8378 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8379 return MI;
8380 }
8381
8382 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8383 // load/store.
8384 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8385 if (MemOpLength == 0) return 0;
8386
Chris Lattnerc669fb62008-01-14 00:28:35 +00008387 // Source and destination pointer types are always "i8*" for intrinsic. See
8388 // if the size is something we can handle with a single primitive load/store.
8389 // A single load+store correctly handles overlapping memory in the memmove
8390 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008391 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008392 if (Size == 0) return MI; // Delete this mem transfer.
8393
8394 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008395 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008396
Chris Lattnerc669fb62008-01-14 00:28:35 +00008397 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008398 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008399
8400 // Memcpy forces the use of i8* for the source and destination. That means
8401 // that if you're using memcpy to move one double around, you'll get a cast
8402 // from double* to i8*. We'd much rather use a double load+store rather than
8403 // an i64 load+store, here because this improves the odds that the source or
8404 // dest address will be promotable. See if we can find a better type than the
8405 // integer datatype.
8406 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8407 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8408 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8409 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8410 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008411 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00008412 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8413 if (STy->getNumElements() == 1)
8414 SrcETy = STy->getElementType(0);
8415 else
8416 break;
8417 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8418 if (ATy->getNumElements() == 1)
8419 SrcETy = ATy->getElementType();
8420 else
8421 break;
8422 } else
8423 break;
8424 }
8425
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008426 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00008427 NewPtrTy = PointerType::getUnqual(SrcETy);
8428 }
8429 }
8430
8431
Chris Lattner00ae5132008-01-13 23:50:23 +00008432 // If the memcpy/memmove provides better alignment info than we can
8433 // infer, use it.
8434 SrcAlign = std::max(SrcAlign, CopyAlign);
8435 DstAlign = std::max(DstAlign, CopyAlign);
8436
8437 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8438 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008439 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8440 InsertNewInstBefore(L, *MI);
8441 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8442
8443 // Set the size of the copy to 0, it will be deleted on the next iteration.
8444 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8445 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008446}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008447
Chris Lattner5af8a912008-04-30 06:39:11 +00008448Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8449 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8450 if (MI->getAlignment()->getZExtValue() < Alignment) {
8451 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8452 return MI;
8453 }
8454
8455 // Extract the length and alignment and fill if they are constant.
8456 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8457 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8458 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8459 return 0;
8460 uint64_t Len = LenC->getZExtValue();
8461 Alignment = MI->getAlignment()->getZExtValue();
8462
8463 // If the length is zero, this is a no-op
8464 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8465
8466 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8467 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8468 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8469
8470 Value *Dest = MI->getDest();
8471 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8472
8473 // Alignment 0 is identity for alignment 1 for memset, but not store.
8474 if (Alignment == 0) Alignment = 1;
8475
8476 // Extract the fill value and store.
8477 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8478 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8479 Alignment), *MI);
8480
8481 // Set the size of the copy to 0, it will be deleted on the next iteration.
8482 MI->setLength(Constant::getNullValue(LenC->getType()));
8483 return MI;
8484 }
8485
8486 return 0;
8487}
8488
8489
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008490/// visitCallInst - CallInst simplification. This mostly only handles folding
8491/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8492/// the heavy lifting.
8493///
8494Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8495 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8496 if (!II) return visitCallSite(&CI);
8497
8498 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8499 // visitCallSite.
8500 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8501 bool Changed = false;
8502
8503 // memmove/cpy/set of zero bytes is a noop.
8504 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8505 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8506
8507 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8508 if (CI->getZExtValue() == 1) {
8509 // Replace the instruction with just byte operations. We would
8510 // transform other cases to loads/stores, but we don't know if
8511 // alignment is sufficient.
8512 }
8513 }
8514
8515 // If we have a memmove and the source operation is a constant global,
8516 // then the source and dest pointers can't alias, so we can change this
8517 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008518 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008519 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8520 if (GVSrc->isConstant()) {
8521 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008522 Intrinsic::ID MemCpyID;
8523 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8524 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008525 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008526 MemCpyID = Intrinsic::memcpy_i64;
8527 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008528 Changed = true;
8529 }
Chris Lattner59b27d92008-05-28 05:30:41 +00008530
8531 // memmove(x,x,size) -> noop.
8532 if (MMI->getSource() == MMI->getDest())
8533 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008534 }
8535
8536 // If we can determine a pointer alignment that is bigger than currently
8537 // set, update the alignment.
8538 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008539 if (Instruction *I = SimplifyMemTransfer(MI))
8540 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008541 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8542 if (Instruction *I = SimplifyMemSet(MSI))
8543 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008544 }
8545
8546 if (Changed) return II;
8547 } else {
8548 switch (II->getIntrinsicID()) {
8549 default: break;
8550 case Intrinsic::ppc_altivec_lvx:
8551 case Intrinsic::ppc_altivec_lvxl:
8552 case Intrinsic::x86_sse_loadu_ps:
8553 case Intrinsic::x86_sse2_loadu_pd:
8554 case Intrinsic::x86_sse2_loadu_dq:
8555 // Turn PPC lvx -> load if the pointer is known aligned.
8556 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008557 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008558 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8559 PointerType::getUnqual(II->getType()),
8560 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008561 return new LoadInst(Ptr);
8562 }
8563 break;
8564 case Intrinsic::ppc_altivec_stvx:
8565 case Intrinsic::ppc_altivec_stvxl:
8566 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008567 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008568 const Type *OpPtrTy =
8569 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008570 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008571 return new StoreInst(II->getOperand(1), Ptr);
8572 }
8573 break;
8574 case Intrinsic::x86_sse_storeu_ps:
8575 case Intrinsic::x86_sse2_storeu_pd:
8576 case Intrinsic::x86_sse2_storeu_dq:
8577 case Intrinsic::x86_sse2_storel_dq:
8578 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008579 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008580 const Type *OpPtrTy =
8581 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008582 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008583 return new StoreInst(II->getOperand(2), Ptr);
8584 }
8585 break;
8586
8587 case Intrinsic::x86_sse_cvttss2si: {
8588 // These intrinsics only demands the 0th element of its input vector. If
8589 // we can simplify the input based on that, do so now.
8590 uint64_t UndefElts;
8591 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8592 UndefElts)) {
8593 II->setOperand(1, V);
8594 return II;
8595 }
8596 break;
8597 }
8598
8599 case Intrinsic::ppc_altivec_vperm:
8600 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8601 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8602 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8603
8604 // Check that all of the elements are integer constants or undefs.
8605 bool AllEltsOk = true;
8606 for (unsigned i = 0; i != 16; ++i) {
8607 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8608 !isa<UndefValue>(Mask->getOperand(i))) {
8609 AllEltsOk = false;
8610 break;
8611 }
8612 }
8613
8614 if (AllEltsOk) {
8615 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008616 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8617 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008618 Value *Result = UndefValue::get(Op0->getType());
8619
8620 // Only extract each element once.
8621 Value *ExtractedElts[32];
8622 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8623
8624 for (unsigned i = 0; i != 16; ++i) {
8625 if (isa<UndefValue>(Mask->getOperand(i)))
8626 continue;
8627 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8628 Idx &= 31; // Match the hardware behavior.
8629
8630 if (ExtractedElts[Idx] == 0) {
8631 Instruction *Elt =
8632 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8633 InsertNewInstBefore(Elt, CI);
8634 ExtractedElts[Idx] = Elt;
8635 }
8636
8637 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008638 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8639 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008640 InsertNewInstBefore(cast<Instruction>(Result), CI);
8641 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008642 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008643 }
8644 }
8645 break;
8646
8647 case Intrinsic::stackrestore: {
8648 // If the save is right next to the restore, remove the restore. This can
8649 // happen when variable allocas are DCE'd.
8650 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8651 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8652 BasicBlock::iterator BI = SS;
8653 if (&*++BI == II)
8654 return EraseInstFromFunction(CI);
8655 }
8656 }
8657
Chris Lattner416d91c2008-02-18 06:12:38 +00008658 // Scan down this block to see if there is another stack restore in the
8659 // same block without an intervening call/alloca.
8660 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008661 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008662 bool CannotRemove = false;
8663 for (++BI; &*BI != TI; ++BI) {
8664 if (isa<AllocaInst>(BI)) {
8665 CannotRemove = true;
8666 break;
8667 }
8668 if (isa<CallInst>(BI)) {
8669 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008670 CannotRemove = true;
8671 break;
8672 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008673 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008674 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008675 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008676 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008677
8678 // If the stack restore is in a return/unwind block and if there are no
8679 // allocas or calls between the restore and the return, nuke the restore.
8680 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8681 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008682 break;
8683 }
8684 }
8685 }
8686
8687 return visitCallSite(II);
8688}
8689
8690// InvokeInst simplification
8691//
8692Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8693 return visitCallSite(&II);
8694}
8695
Dale Johannesen96021832008-04-25 21:16:07 +00008696/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8697/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008698static bool isSafeToEliminateVarargsCast(const CallSite CS,
8699 const CastInst * const CI,
8700 const TargetData * const TD,
8701 const int ix) {
8702 if (!CI->isLosslessCast())
8703 return false;
8704
8705 // The size of ByVal arguments is derived from the type, so we
8706 // can't change to a type with a different size. If the size were
8707 // passed explicitly we could avoid this check.
8708 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8709 return true;
8710
8711 const Type* SrcTy =
8712 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8713 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8714 if (!SrcTy->isSized() || !DstTy->isSized())
8715 return false;
8716 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8717 return false;
8718 return true;
8719}
8720
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008721// visitCallSite - Improvements for call and invoke instructions.
8722//
8723Instruction *InstCombiner::visitCallSite(CallSite CS) {
8724 bool Changed = false;
8725
8726 // If the callee is a constexpr cast of a function, attempt to move the cast
8727 // to the arguments of the call/invoke.
8728 if (transformConstExprCastCall(CS)) return 0;
8729
8730 Value *Callee = CS.getCalledValue();
8731
8732 if (Function *CalleeF = dyn_cast<Function>(Callee))
8733 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8734 Instruction *OldCall = CS.getInstruction();
8735 // If the call and callee calling conventions don't match, this call must
8736 // be unreachable, as the call is undefined.
8737 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008738 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8739 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008740 if (!OldCall->use_empty())
8741 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8742 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8743 return EraseInstFromFunction(*OldCall);
8744 return 0;
8745 }
8746
8747 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8748 // This instruction is not reachable, just remove it. We insert a store to
8749 // undef so that we know that this code is not reachable, despite the fact
8750 // that we can't modify the CFG here.
8751 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008752 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008753 CS.getInstruction());
8754
8755 if (!CS.getInstruction()->use_empty())
8756 CS.getInstruction()->
8757 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8758
8759 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8760 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008761 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8762 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008763 }
8764 return EraseInstFromFunction(*CS.getInstruction());
8765 }
8766
Duncan Sands74833f22007-09-17 10:26:40 +00008767 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8768 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8769 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8770 return transformCallThroughTrampoline(CS);
8771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008772 const PointerType *PTy = cast<PointerType>(Callee->getType());
8773 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8774 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00008775 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008776 // See if we can optimize any arguments passed through the varargs area of
8777 // the call.
8778 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00008779 E = CS.arg_end(); I != E; ++I, ++ix) {
8780 CastInst *CI = dyn_cast<CastInst>(*I);
8781 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8782 *I = CI->getOperand(0);
8783 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008784 }
Dale Johannesen35615462008-04-23 18:34:37 +00008785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008786 }
8787
Duncan Sands2937e352007-12-19 21:13:37 +00008788 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008789 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008790 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008791 Changed = true;
8792 }
8793
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008794 return Changed ? CS.getInstruction() : 0;
8795}
8796
8797// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8798// attempt to move the cast to the arguments of the call/invoke.
8799//
8800bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8801 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8802 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8803 if (CE->getOpcode() != Instruction::BitCast ||
8804 !isa<Function>(CE->getOperand(0)))
8805 return false;
8806 Function *Callee = cast<Function>(CE->getOperand(0));
8807 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008808 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008809
8810 // Okay, this is a cast from a function to a different type. Unless doing so
8811 // would cause a type conversion of one of our arguments, change this call to
8812 // be a direct call with arguments casted to the appropriate types.
8813 //
8814 const FunctionType *FT = Callee->getFunctionType();
8815 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00008816 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008817
Duncan Sands7901ce12008-06-01 07:38:42 +00008818 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00008819 return false; // TODO: Handle multiple return values.
8820
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008821 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00008822 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00008823 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00008824 // Conversion is ok if changing from one pointer type to another or from
8825 // a pointer to an integer of the same size.
8826 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8827 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008828 return false; // Cannot transform this return value.
8829
Duncan Sands5c489582008-01-06 10:12:28 +00008830 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008831 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00008832 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008833 return false; // Cannot transform this return value.
8834
Chris Lattner1c8733e2008-03-12 17:45:29 +00008835 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8836 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands7901ce12008-06-01 07:38:42 +00008837 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008838 return false; // Attribute not compatible with transformed value.
8839 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008840
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008841 // If the callsite is an invoke instruction, and the return value is used by
8842 // a PHI node in a successor, we cannot change the return type of the call
8843 // because there is no place to put the cast instruction (without breaking
8844 // the critical edge). Bail out in this case.
8845 if (!Caller->use_empty())
8846 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8847 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8848 UI != E; ++UI)
8849 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8850 if (PN->getParent() == II->getNormalDest() ||
8851 PN->getParent() == II->getUnwindDest())
8852 return false;
8853 }
8854
8855 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8856 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8857
8858 CallSite::arg_iterator AI = CS.arg_begin();
8859 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8860 const Type *ParamTy = FT->getParamType(i);
8861 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008862
8863 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008864 return false; // Cannot transform this parameter value.
8865
Chris Lattner1c8733e2008-03-12 17:45:29 +00008866 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8867 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008868
Duncan Sands7901ce12008-06-01 07:38:42 +00008869 // Converting from one pointer type to another or between a pointer and an
8870 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008871 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00008872 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8873 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008874 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008875 }
8876
8877 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8878 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00008879 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008880
Chris Lattner1c8733e2008-03-12 17:45:29 +00008881 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8882 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00008883 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008884 // won't be dropping them. Check that these extra arguments have attributes
8885 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008886 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8887 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00008888 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008889 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00008890 if (PAttrs & ParamAttr::VarArgsIncompatible)
8891 return false;
8892 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008893
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008894 // Okay, we decided that this is a safe thing to do: go ahead and start
8895 // inserting cast instructions as necessary...
8896 std::vector<Value*> Args;
8897 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008898 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00008899 attrVec.reserve(NumCommonArgs);
8900
8901 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008902 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00008903
8904 // If the return value is not being used, the type may not be compatible
8905 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands7901ce12008-06-01 07:38:42 +00008906 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00008907
8908 // Add the new return attributes.
8909 if (RAttrs)
8910 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008911
8912 AI = CS.arg_begin();
8913 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8914 const Type *ParamTy = FT->getParamType(i);
8915 if ((*AI)->getType() == ParamTy) {
8916 Args.push_back(*AI);
8917 } else {
8918 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8919 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008920 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008921 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8922 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008923
8924 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008925 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00008926 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927 }
8928
8929 // If the function takes more arguments than the call was taking, add them
8930 // now...
8931 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8932 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8933
8934 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008935 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008936 if (!FT->isVarArg()) {
8937 cerr << "WARNING: While resolving call to function '"
8938 << Callee->getName() << "' arguments were dropped!\n";
8939 } else {
8940 // Add all of the arguments in their promoted form to the arg list...
8941 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8942 const Type *PTy = getPromotedType((*AI)->getType());
8943 if (PTy != (*AI)->getType()) {
8944 // Must promote to pass through va_arg area!
8945 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8946 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008947 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008948 InsertNewInstBefore(Cast, *Caller);
8949 Args.push_back(Cast);
8950 } else {
8951 Args.push_back(*AI);
8952 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008953
Duncan Sands4ced1f82008-01-13 08:02:44 +00008954 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008955 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00008956 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8957 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008958 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008959 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008960
Duncan Sands7901ce12008-06-01 07:38:42 +00008961 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008962 Caller->setName(""); // Void type should not have a name.
8963
Chris Lattner1c8733e2008-03-12 17:45:29 +00008964 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00008965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008966 Instruction *NC;
8967 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008968 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008969 Args.begin(), Args.end(),
8970 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008971 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008972 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008973 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008974 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8975 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008976 CallInst *CI = cast<CallInst>(Caller);
8977 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008978 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008979 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008980 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008981 }
8982
8983 // Insert a cast of the return type as necessary.
8984 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008985 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008986 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008987 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008988 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008989 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008990
8991 // If this is an invoke instruction, we should insert it after the first
8992 // non-phi, instruction in the normal successor block.
8993 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00008994 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008995 InsertNewInstBefore(NC, *I);
8996 } else {
8997 // Otherwise, it's a call, just insert cast right after the call instr
8998 InsertNewInstBefore(NC, *Caller);
8999 }
9000 AddUsersToWorkList(*Caller);
9001 } else {
9002 NV = UndefValue::get(Caller->getType());
9003 }
9004 }
9005
9006 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9007 Caller->replaceAllUsesWith(NV);
9008 Caller->eraseFromParent();
9009 RemoveFromWorkList(Caller);
9010 return true;
9011}
9012
Duncan Sands74833f22007-09-17 10:26:40 +00009013// transformCallThroughTrampoline - Turn a call to a function created by the
9014// init_trampoline intrinsic into a direct call to the underlying function.
9015//
9016Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9017 Value *Callee = CS.getCalledValue();
9018 const PointerType *PTy = cast<PointerType>(Callee->getType());
9019 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009020 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009021
9022 // If the call already has the 'nest' attribute somewhere then give up -
9023 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009024 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009025 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009026
9027 IntrinsicInst *Tramp =
9028 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9029
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009030 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009031 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9032 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9033
Chris Lattner1c8733e2008-03-12 17:45:29 +00009034 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9035 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009036 unsigned NestIdx = 1;
9037 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009038 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009039
9040 // Look for a parameter marked with the 'nest' attribute.
9041 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9042 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009043 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009044 // Record the parameter type and any other attributes.
9045 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009046 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009047 break;
9048 }
9049
9050 if (NestTy) {
9051 Instruction *Caller = CS.getInstruction();
9052 std::vector<Value*> NewArgs;
9053 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9054
Chris Lattner1c8733e2008-03-12 17:45:29 +00009055 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9056 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009057
Duncan Sands74833f22007-09-17 10:26:40 +00009058 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009059 // mean appending it. Likewise for attributes.
9060
9061 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009062 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9063 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009064
Duncan Sands74833f22007-09-17 10:26:40 +00009065 {
9066 unsigned Idx = 1;
9067 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9068 do {
9069 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009070 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009071 Value *NestVal = Tramp->getOperand(3);
9072 if (NestVal->getType() != NestTy)
9073 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9074 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009075 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009076 }
9077
9078 if (I == E)
9079 break;
9080
Duncan Sands48b81112008-01-14 19:52:09 +00009081 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009082 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009083 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009084 NewAttrs.push_back
9085 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009086
9087 ++Idx, ++I;
9088 } while (1);
9089 }
9090
9091 // The trampoline may have been bitcast to a bogus type (FTy).
9092 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009093 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009094
Duncan Sands74833f22007-09-17 10:26:40 +00009095 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009096 NewTypes.reserve(FTy->getNumParams()+1);
9097
Duncan Sands74833f22007-09-17 10:26:40 +00009098 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009099 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009100 {
9101 unsigned Idx = 1;
9102 FunctionType::param_iterator I = FTy->param_begin(),
9103 E = FTy->param_end();
9104
9105 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009106 if (Idx == NestIdx)
9107 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009108 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009109
9110 if (I == E)
9111 break;
9112
Duncan Sands48b81112008-01-14 19:52:09 +00009113 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009114 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009115
9116 ++Idx, ++I;
9117 } while (1);
9118 }
9119
9120 // Replace the trampoline call with a direct call. Let the generic
9121 // code sort out any function type mismatches.
9122 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009123 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009124 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9125 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009126 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009127
9128 Instruction *NewCaller;
9129 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009130 NewCaller = InvokeInst::Create(NewCallee,
9131 II->getNormalDest(), II->getUnwindDest(),
9132 NewArgs.begin(), NewArgs.end(),
9133 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009134 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009135 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009136 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009137 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9138 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009139 if (cast<CallInst>(Caller)->isTailCall())
9140 cast<CallInst>(NewCaller)->setTailCall();
9141 cast<CallInst>(NewCaller)->
9142 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009143 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009144 }
9145 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9146 Caller->replaceAllUsesWith(NewCaller);
9147 Caller->eraseFromParent();
9148 RemoveFromWorkList(Caller);
9149 return 0;
9150 }
9151 }
9152
9153 // Replace the trampoline call with a direct call. Since there is no 'nest'
9154 // parameter, there is no need to adjust the argument list. Let the generic
9155 // code sort out any function type mismatches.
9156 Constant *NewCallee =
9157 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9158 CS.setCalledFunction(NewCallee);
9159 return CS.getInstruction();
9160}
9161
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009162/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9163/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9164/// and a single binop.
9165Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9166 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9167 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9168 isa<CmpInst>(FirstInst));
9169 unsigned Opc = FirstInst->getOpcode();
9170 Value *LHSVal = FirstInst->getOperand(0);
9171 Value *RHSVal = FirstInst->getOperand(1);
9172
9173 const Type *LHSType = LHSVal->getType();
9174 const Type *RHSType = RHSVal->getType();
9175
9176 // Scan to see if all operands are the same opcode, all have one use, and all
9177 // kill their operands (i.e. the operands have one use).
9178 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9179 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9180 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9181 // Verify type of the LHS matches so we don't fold cmp's of different
9182 // types or GEP's with different index types.
9183 I->getOperand(0)->getType() != LHSType ||
9184 I->getOperand(1)->getType() != RHSType)
9185 return 0;
9186
9187 // If they are CmpInst instructions, check their predicates
9188 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9189 if (cast<CmpInst>(I)->getPredicate() !=
9190 cast<CmpInst>(FirstInst)->getPredicate())
9191 return 0;
9192
9193 // Keep track of which operand needs a phi node.
9194 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9195 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9196 }
9197
9198 // Otherwise, this is safe to transform, determine if it is profitable.
9199
9200 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9201 // Indexes are often folded into load/store instructions, so we don't want to
9202 // hide them behind a phi.
9203 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9204 return 0;
9205
9206 Value *InLHS = FirstInst->getOperand(0);
9207 Value *InRHS = FirstInst->getOperand(1);
9208 PHINode *NewLHS = 0, *NewRHS = 0;
9209 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009210 NewLHS = PHINode::Create(LHSType,
9211 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009212 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9213 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9214 InsertNewInstBefore(NewLHS, PN);
9215 LHSVal = NewLHS;
9216 }
9217
9218 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009219 NewRHS = PHINode::Create(RHSType,
9220 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009221 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9222 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9223 InsertNewInstBefore(NewRHS, PN);
9224 RHSVal = NewRHS;
9225 }
9226
9227 // Add all operands to the new PHIs.
9228 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9229 if (NewLHS) {
9230 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9231 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9232 }
9233 if (NewRHS) {
9234 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9235 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9236 }
9237 }
9238
9239 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009240 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009241 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009242 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009243 RHSVal);
9244 else {
9245 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009246 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009247 }
9248}
9249
9250/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9251/// of the block that defines it. This means that it must be obvious the value
9252/// of the load is not changed from the point of the load to the end of the
9253/// block it is in.
9254///
9255/// Finally, it is safe, but not profitable, to sink a load targetting a
9256/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9257/// to a register.
9258static bool isSafeToSinkLoad(LoadInst *L) {
9259 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9260
9261 for (++BBI; BBI != E; ++BBI)
9262 if (BBI->mayWriteToMemory())
9263 return false;
9264
9265 // Check for non-address taken alloca. If not address-taken already, it isn't
9266 // profitable to do this xform.
9267 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9268 bool isAddressTaken = false;
9269 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9270 UI != E; ++UI) {
9271 if (isa<LoadInst>(UI)) continue;
9272 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9273 // If storing TO the alloca, then the address isn't taken.
9274 if (SI->getOperand(1) == AI) continue;
9275 }
9276 isAddressTaken = true;
9277 break;
9278 }
9279
9280 if (!isAddressTaken)
9281 return false;
9282 }
9283
9284 return true;
9285}
9286
9287
9288// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9289// operator and they all are only used by the PHI, PHI together their
9290// inputs, and do the operation once, to the result of the PHI.
9291Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9292 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9293
9294 // Scan the instruction, looking for input operations that can be folded away.
9295 // If all input operands to the phi are the same instruction (e.g. a cast from
9296 // the same type or "+42") we can pull the operation through the PHI, reducing
9297 // code size and simplifying code.
9298 Constant *ConstantOp = 0;
9299 const Type *CastSrcTy = 0;
9300 bool isVolatile = false;
9301 if (isa<CastInst>(FirstInst)) {
9302 CastSrcTy = FirstInst->getOperand(0)->getType();
9303 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9304 // Can fold binop, compare or shift here if the RHS is a constant,
9305 // otherwise call FoldPHIArgBinOpIntoPHI.
9306 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9307 if (ConstantOp == 0)
9308 return FoldPHIArgBinOpIntoPHI(PN);
9309 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9310 isVolatile = LI->isVolatile();
9311 // We can't sink the load if the loaded value could be modified between the
9312 // load and the PHI.
9313 if (LI->getParent() != PN.getIncomingBlock(0) ||
9314 !isSafeToSinkLoad(LI))
9315 return 0;
9316 } else if (isa<GetElementPtrInst>(FirstInst)) {
9317 if (FirstInst->getNumOperands() == 2)
9318 return FoldPHIArgBinOpIntoPHI(PN);
9319 // Can't handle general GEPs yet.
9320 return 0;
9321 } else {
9322 return 0; // Cannot fold this operation.
9323 }
9324
9325 // Check to see if all arguments are the same operation.
9326 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9327 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9328 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9329 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9330 return 0;
9331 if (CastSrcTy) {
9332 if (I->getOperand(0)->getType() != CastSrcTy)
9333 return 0; // Cast operation must match.
9334 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9335 // We can't sink the load if the loaded value could be modified between
9336 // the load and the PHI.
9337 if (LI->isVolatile() != isVolatile ||
9338 LI->getParent() != PN.getIncomingBlock(i) ||
9339 !isSafeToSinkLoad(LI))
9340 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009341
9342 // If the PHI is volatile and its block has multiple successors, sinking
9343 // it would remove a load of the volatile value from the path through the
9344 // other successor.
9345 if (isVolatile &&
9346 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9347 return 0;
9348
9349
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009350 } else if (I->getOperand(1) != ConstantOp) {
9351 return 0;
9352 }
9353 }
9354
9355 // Okay, they are all the same operation. Create a new PHI node of the
9356 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009357 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9358 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009359 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9360
9361 Value *InVal = FirstInst->getOperand(0);
9362 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9363
9364 // Add all operands to the new PHI.
9365 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9366 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9367 if (NewInVal != InVal)
9368 InVal = 0;
9369 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9370 }
9371
9372 Value *PhiVal;
9373 if (InVal) {
9374 // The new PHI unions all of the same values together. This is really
9375 // common, so we handle it intelligently here for compile-time speed.
9376 PhiVal = InVal;
9377 delete NewPN;
9378 } else {
9379 InsertNewInstBefore(NewPN, PN);
9380 PhiVal = NewPN;
9381 }
9382
9383 // Insert and return the new operation.
9384 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009385 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009386 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009387 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009388 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009389 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009390 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009391 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9392
9393 // If this was a volatile load that we are merging, make sure to loop through
9394 // and mark all the input loads as non-volatile. If we don't do this, we will
9395 // insert a new volatile load and the old ones will not be deletable.
9396 if (isVolatile)
9397 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9398 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9399
9400 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009401}
9402
9403/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9404/// that is dead.
9405static bool DeadPHICycle(PHINode *PN,
9406 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9407 if (PN->use_empty()) return true;
9408 if (!PN->hasOneUse()) return false;
9409
9410 // Remember this node, and if we find the cycle, return.
9411 if (!PotentiallyDeadPHIs.insert(PN))
9412 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009413
9414 // Don't scan crazily complex things.
9415 if (PotentiallyDeadPHIs.size() == 16)
9416 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009417
9418 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9419 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9420
9421 return false;
9422}
9423
Chris Lattner27b695d2007-11-06 21:52:06 +00009424/// PHIsEqualValue - Return true if this phi node is always equal to
9425/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9426/// z = some value; x = phi (y, z); y = phi (x, z)
9427static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9428 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9429 // See if we already saw this PHI node.
9430 if (!ValueEqualPHIs.insert(PN))
9431 return true;
9432
9433 // Don't scan crazily complex things.
9434 if (ValueEqualPHIs.size() == 16)
9435 return false;
9436
9437 // Scan the operands to see if they are either phi nodes or are equal to
9438 // the value.
9439 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9440 Value *Op = PN->getIncomingValue(i);
9441 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9442 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9443 return false;
9444 } else if (Op != NonPhiInVal)
9445 return false;
9446 }
9447
9448 return true;
9449}
9450
9451
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009452// PHINode simplification
9453//
9454Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9455 // If LCSSA is around, don't mess with Phi nodes
9456 if (MustPreserveLCSSA) return 0;
9457
9458 if (Value *V = PN.hasConstantValue())
9459 return ReplaceInstUsesWith(PN, V);
9460
9461 // If all PHI operands are the same operation, pull them through the PHI,
9462 // reducing code size.
9463 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9464 PN.getIncomingValue(0)->hasOneUse())
9465 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9466 return Result;
9467
9468 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9469 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9470 // PHI)... break the cycle.
9471 if (PN.hasOneUse()) {
9472 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9473 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9474 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9475 PotentiallyDeadPHIs.insert(&PN);
9476 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9477 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9478 }
9479
9480 // If this phi has a single use, and if that use just computes a value for
9481 // the next iteration of a loop, delete the phi. This occurs with unused
9482 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9483 // common case here is good because the only other things that catch this
9484 // are induction variable analysis (sometimes) and ADCE, which is only run
9485 // late.
9486 if (PHIUser->hasOneUse() &&
9487 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9488 PHIUser->use_back() == &PN) {
9489 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9490 }
9491 }
9492
Chris Lattner27b695d2007-11-06 21:52:06 +00009493 // We sometimes end up with phi cycles that non-obviously end up being the
9494 // same value, for example:
9495 // z = some value; x = phi (y, z); y = phi (x, z)
9496 // where the phi nodes don't necessarily need to be in the same block. Do a
9497 // quick check to see if the PHI node only contains a single non-phi value, if
9498 // so, scan to see if the phi cycle is actually equal to that value.
9499 {
9500 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9501 // Scan for the first non-phi operand.
9502 while (InValNo != NumOperandVals &&
9503 isa<PHINode>(PN.getIncomingValue(InValNo)))
9504 ++InValNo;
9505
9506 if (InValNo != NumOperandVals) {
9507 Value *NonPhiInVal = PN.getOperand(InValNo);
9508
9509 // Scan the rest of the operands to see if there are any conflicts, if so
9510 // there is no need to recursively scan other phis.
9511 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9512 Value *OpVal = PN.getIncomingValue(InValNo);
9513 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9514 break;
9515 }
9516
9517 // If we scanned over all operands, then we have one unique value plus
9518 // phi values. Scan PHI nodes to see if they all merge in each other or
9519 // the value.
9520 if (InValNo == NumOperandVals) {
9521 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9522 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9523 return ReplaceInstUsesWith(PN, NonPhiInVal);
9524 }
9525 }
9526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009527 return 0;
9528}
9529
9530static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9531 Instruction *InsertPoint,
9532 InstCombiner *IC) {
9533 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9534 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9535 // We must cast correctly to the pointer type. Ensure that we
9536 // sign extend the integer value if it is smaller as this is
9537 // used for address computation.
9538 Instruction::CastOps opcode =
9539 (VTySize < PtrSize ? Instruction::SExt :
9540 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9541 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9542}
9543
9544
9545Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9546 Value *PtrOp = GEP.getOperand(0);
9547 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9548 // If so, eliminate the noop.
9549 if (GEP.getNumOperands() == 1)
9550 return ReplaceInstUsesWith(GEP, PtrOp);
9551
9552 if (isa<UndefValue>(GEP.getOperand(0)))
9553 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9554
9555 bool HasZeroPointerIndex = false;
9556 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9557 HasZeroPointerIndex = C->isNullValue();
9558
9559 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9560 return ReplaceInstUsesWith(GEP, PtrOp);
9561
9562 // Eliminate unneeded casts for indices.
9563 bool MadeChange = false;
9564
9565 gep_type_iterator GTI = gep_type_begin(GEP);
9566 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9567 if (isa<SequentialType>(*GTI)) {
9568 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9569 if (CI->getOpcode() == Instruction::ZExt ||
9570 CI->getOpcode() == Instruction::SExt) {
9571 const Type *SrcTy = CI->getOperand(0)->getType();
9572 // We can eliminate a cast from i32 to i64 iff the target
9573 // is a 32-bit pointer target.
9574 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9575 MadeChange = true;
9576 GEP.setOperand(i, CI->getOperand(0));
9577 }
9578 }
9579 }
9580 // If we are using a wider index than needed for this platform, shrink it
9581 // to what we need. If the incoming value needs a cast instruction,
9582 // insert it. This explicit cast can make subsequent optimizations more
9583 // obvious.
9584 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009585 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009586 if (Constant *C = dyn_cast<Constant>(Op)) {
9587 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9588 MadeChange = true;
9589 } else {
9590 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9591 GEP);
9592 GEP.setOperand(i, Op);
9593 MadeChange = true;
9594 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009595 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009596 }
9597 }
9598 if (MadeChange) return &GEP;
9599
9600 // If this GEP instruction doesn't move the pointer, and if the input operand
9601 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9602 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009603 if (GEP.hasAllZeroIndices()) {
9604 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9605 // If the bitcast is of an allocation, and the allocation will be
9606 // converted to match the type of the cast, don't touch this.
9607 if (isa<AllocationInst>(BCI->getOperand(0))) {
9608 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009609 if (Instruction *I = visitBitCast(*BCI)) {
9610 if (I != BCI) {
9611 I->takeName(BCI);
9612 BCI->getParent()->getInstList().insert(BCI, I);
9613 ReplaceInstUsesWith(*BCI, I);
9614 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009615 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009616 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009617 }
9618 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9619 }
9620 }
9621
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009622 // Combine Indices - If the source pointer to this getelementptr instruction
9623 // is a getelementptr instruction, combine the indices of the two
9624 // getelementptr instructions into a single instruction.
9625 //
9626 SmallVector<Value*, 8> SrcGEPOperands;
9627 if (User *Src = dyn_castGetElementPtr(PtrOp))
9628 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9629
9630 if (!SrcGEPOperands.empty()) {
9631 // Note that if our source is a gep chain itself that we wait for that
9632 // chain to be resolved before we perform this transformation. This
9633 // avoids us creating a TON of code in some cases.
9634 //
9635 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9636 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9637 return 0; // Wait until our source is folded to completion.
9638
9639 SmallVector<Value*, 8> Indices;
9640
9641 // Find out whether the last index in the source GEP is a sequential idx.
9642 bool EndsWithSequential = false;
9643 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9644 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9645 EndsWithSequential = !isa<StructType>(*I);
9646
9647 // Can we combine the two pointer arithmetics offsets?
9648 if (EndsWithSequential) {
9649 // Replace: gep (gep %P, long B), long A, ...
9650 // With: T = long A+B; gep %P, T, ...
9651 //
9652 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9653 if (SO1 == Constant::getNullValue(SO1->getType())) {
9654 Sum = GO1;
9655 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9656 Sum = SO1;
9657 } else {
9658 // If they aren't the same type, convert both to an integer of the
9659 // target's pointer size.
9660 if (SO1->getType() != GO1->getType()) {
9661 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9662 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9663 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9664 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9665 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009666 unsigned PS = TD->getPointerSizeInBits();
9667 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009668 // Convert GO1 to SO1's type.
9669 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9670
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009671 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009672 // Convert SO1 to GO1's type.
9673 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9674 } else {
9675 const Type *PT = TD->getIntPtrType();
9676 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9677 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9678 }
9679 }
9680 }
9681 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9682 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9683 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009684 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009685 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9686 }
9687 }
9688
9689 // Recycle the GEP we already have if possible.
9690 if (SrcGEPOperands.size() == 2) {
9691 GEP.setOperand(0, SrcGEPOperands[0]);
9692 GEP.setOperand(1, Sum);
9693 return &GEP;
9694 } else {
9695 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9696 SrcGEPOperands.end()-1);
9697 Indices.push_back(Sum);
9698 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9699 }
9700 } else if (isa<Constant>(*GEP.idx_begin()) &&
9701 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9702 SrcGEPOperands.size() != 1) {
9703 // Otherwise we can do the fold if the first index of the GEP is a zero
9704 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9705 SrcGEPOperands.end());
9706 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9707 }
9708
9709 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009710 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9711 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009712
9713 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9714 // GEP of global variable. If all of the indices for this GEP are
9715 // constants, we can promote this to a constexpr instead of an instruction.
9716
9717 // Scan for nonconstants...
9718 SmallVector<Constant*, 8> Indices;
9719 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9720 for (; I != E && isa<Constant>(*I); ++I)
9721 Indices.push_back(cast<Constant>(*I));
9722
9723 if (I == E) { // If they are all constants...
9724 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9725 &Indices[0],Indices.size());
9726
9727 // Replace all uses of the GEP with the new constexpr...
9728 return ReplaceInstUsesWith(GEP, CE);
9729 }
9730 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9731 if (!isa<PointerType>(X->getType())) {
9732 // Not interesting. Source pointer must be a cast from pointer.
9733 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009734 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9735 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009736 //
9737 // This occurs when the program declares an array extern like "int X[];"
9738 //
9739 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9740 const PointerType *XTy = cast<PointerType>(X->getType());
9741 if (const ArrayType *XATy =
9742 dyn_cast<ArrayType>(XTy->getElementType()))
9743 if (const ArrayType *CATy =
9744 dyn_cast<ArrayType>(CPTy->getElementType()))
9745 if (CATy->getElementType() == XATy->getElementType()) {
9746 // At this point, we know that the cast source type is a pointer
9747 // to an array of the same type as the destination pointer
9748 // array. Because the array type is never stepped over (there
9749 // is a leading zero) we can fold the cast into this GEP.
9750 GEP.setOperand(0, X);
9751 return &GEP;
9752 }
9753 } else if (GEP.getNumOperands() == 2) {
9754 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009755 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9756 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009757 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9758 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9759 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009760 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9761 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009762 Value *Idx[2];
9763 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9764 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009765 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009766 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009767 // V and GEP are both pointer types --> BitCast
9768 return new BitCastInst(V, GEP.getType());
9769 }
9770
9771 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009772 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009773 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009774 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009775
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009776 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009777 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009778 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009779
9780 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9781 // allow either a mul, shift, or constant here.
9782 Value *NewIdx = 0;
9783 ConstantInt *Scale = 0;
9784 if (ArrayEltSize == 1) {
9785 NewIdx = GEP.getOperand(1);
9786 Scale = ConstantInt::get(NewIdx->getType(), 1);
9787 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9788 NewIdx = ConstantInt::get(CI->getType(), 1);
9789 Scale = CI;
9790 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9791 if (Inst->getOpcode() == Instruction::Shl &&
9792 isa<ConstantInt>(Inst->getOperand(1))) {
9793 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9794 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9795 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9796 NewIdx = Inst->getOperand(0);
9797 } else if (Inst->getOpcode() == Instruction::Mul &&
9798 isa<ConstantInt>(Inst->getOperand(1))) {
9799 Scale = cast<ConstantInt>(Inst->getOperand(1));
9800 NewIdx = Inst->getOperand(0);
9801 }
9802 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009805 // out, perform the transformation. Note, we don't know whether Scale is
9806 // signed or not. We'll use unsigned version of division/modulo
9807 // operation after making sure Scale doesn't have the sign bit set.
9808 if (Scale && Scale->getSExtValue() >= 0LL &&
9809 Scale->getZExtValue() % ArrayEltSize == 0) {
9810 Scale = ConstantInt::get(Scale->getType(),
9811 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009812 if (Scale->getZExtValue() != 1) {
9813 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009814 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +00009815 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009816 NewIdx = InsertNewInstBefore(Sc, GEP);
9817 }
9818
9819 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009820 Value *Idx[2];
9821 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9822 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009823 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +00009824 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009825 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9826 // The NewGEP must be pointer typed, so must the old one -> BitCast
9827 return new BitCastInst(NewGEP, GEP.getType());
9828 }
9829 }
9830 }
9831 }
9832
9833 return 0;
9834}
9835
9836Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9837 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009838 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009839 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9840 const Type *NewTy =
9841 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9842 AllocationInst *New = 0;
9843
9844 // Create and insert the replacement instruction...
9845 if (isa<MallocInst>(AI))
9846 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9847 else {
9848 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9849 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9850 }
9851
9852 InsertNewInstBefore(New, AI);
9853
9854 // Scan to the end of the allocation instructions, to skip over a block of
9855 // allocas if possible...
9856 //
9857 BasicBlock::iterator It = New;
9858 while (isa<AllocationInst>(*It)) ++It;
9859
9860 // Now that I is pointing to the first non-allocation-inst in the block,
9861 // insert our getelementptr instruction...
9862 //
9863 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009864 Value *Idx[2];
9865 Idx[0] = NullIdx;
9866 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +00009867 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9868 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009869
9870 // Now make everything use the getelementptr instead of the original
9871 // allocation.
9872 return ReplaceInstUsesWith(AI, V);
9873 } else if (isa<UndefValue>(AI.getArraySize())) {
9874 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9875 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009876 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009877
9878 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9879 // Note that we only do this for alloca's, because malloc should allocate and
9880 // return a unique pointer, even for a zero byte allocation.
9881 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009882 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009883 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9884
9885 return 0;
9886}
9887
9888Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9889 Value *Op = FI.getOperand(0);
9890
9891 // free undef -> unreachable.
9892 if (isa<UndefValue>(Op)) {
9893 // Insert a new store to null because we cannot modify the CFG here.
9894 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009895 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009896 return EraseInstFromFunction(FI);
9897 }
9898
9899 // If we have 'free null' delete the instruction. This can happen in stl code
9900 // when lots of inlining happens.
9901 if (isa<ConstantPointerNull>(Op))
9902 return EraseInstFromFunction(FI);
9903
9904 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9905 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9906 FI.setOperand(0, CI->getOperand(0));
9907 return &FI;
9908 }
9909
9910 // Change free (gep X, 0,0,0,0) into free(X)
9911 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9912 if (GEPI->hasAllZeroIndices()) {
9913 AddToWorkList(GEPI);
9914 FI.setOperand(0, GEPI->getOperand(0));
9915 return &FI;
9916 }
9917 }
9918
9919 // Change free(malloc) into nothing, if the malloc has a single use.
9920 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9921 if (MI->hasOneUse()) {
9922 EraseInstFromFunction(FI);
9923 return EraseInstFromFunction(*MI);
9924 }
9925
9926 return 0;
9927}
9928
9929
9930/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009931static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00009932 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009933 User *CI = cast<User>(LI.getOperand(0));
9934 Value *CastOp = CI->getOperand(0);
9935
Devang Patela0f8ea82007-10-18 19:52:32 +00009936 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9937 // Instead of loading constant c string, use corresponding integer value
9938 // directly if string length is small enough.
9939 const std::string &Str = CE->getOperand(0)->getStringValue();
9940 if (!Str.empty()) {
9941 unsigned len = Str.length();
9942 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9943 unsigned numBits = Ty->getPrimitiveSizeInBits();
9944 // Replace LI with immediate integer store.
9945 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00009946 APInt StrVal(numBits, 0);
9947 APInt SingleChar(numBits, 0);
9948 if (TD->isLittleEndian()) {
9949 for (signed i = len-1; i >= 0; i--) {
9950 SingleChar = (uint64_t) Str[i];
9951 StrVal = (StrVal << 8) | SingleChar;
9952 }
9953 } else {
9954 for (unsigned i = 0; i < len; i++) {
9955 SingleChar = (uint64_t) Str[i];
9956 StrVal = (StrVal << 8) | SingleChar;
9957 }
9958 // Append NULL at the end.
9959 SingleChar = 0;
9960 StrVal = (StrVal << 8) | SingleChar;
9961 }
9962 Value *NL = ConstantInt::get(StrVal);
9963 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +00009964 }
9965 }
9966 }
9967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009968 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9969 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9970 const Type *SrcPTy = SrcTy->getElementType();
9971
9972 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9973 isa<VectorType>(DestPTy)) {
9974 // If the source is an array, the code below will not succeed. Check to
9975 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9976 // constants.
9977 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9978 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9979 if (ASrcTy->getNumElements() != 0) {
9980 Value *Idxs[2];
9981 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9982 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9983 SrcTy = cast<PointerType>(CastOp->getType());
9984 SrcPTy = SrcTy->getElementType();
9985 }
9986
9987 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9988 isa<VectorType>(SrcPTy)) &&
9989 // Do not allow turning this into a load of an integer, which is then
9990 // casted to a pointer, this pessimizes pointer analysis a lot.
9991 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9992 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9993 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9994
9995 // Okay, we are casting from one integer or pointer type to another of
9996 // the same size. Instead of casting the pointer before the load, cast
9997 // the result of the loaded value.
9998 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9999 CI->getName(),
10000 LI.isVolatile()),LI);
10001 // Now cast the result of the load.
10002 return new BitCastInst(NewLoad, LI.getType());
10003 }
10004 }
10005 }
10006 return 0;
10007}
10008
10009/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10010/// from this value cannot trap. If it is not obviously safe to load from the
10011/// specified pointer, we do a quick local scan of the basic block containing
10012/// ScanFrom, to determine if the address is already accessed.
10013static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010014 // If it is an alloca it is always safe to load from.
10015 if (isa<AllocaInst>(V)) return true;
10016
Duncan Sandse40a94a2007-09-19 10:25:38 +000010017 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010018 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010019 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010020 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010021
10022 // Otherwise, be a little bit agressive by scanning the local block where we
10023 // want to check to see if the pointer is already being loaded or stored
10024 // from/to. If so, the previous load or store would have already trapped,
10025 // so there is no harm doing an extra load (also, CSE will later eliminate
10026 // the load entirely).
10027 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10028
10029 while (BBI != E) {
10030 --BBI;
10031
10032 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10033 if (LI->getOperand(0) == V) return true;
10034 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10035 if (SI->getOperand(1) == V) return true;
10036
10037 }
10038 return false;
10039}
10040
Chris Lattner0270a112007-08-11 18:48:48 +000010041/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10042/// until we find the underlying object a pointer is referring to or something
10043/// we don't understand. Note that the returned pointer may be offset from the
10044/// input, because we ignore GEP indices.
10045static Value *GetUnderlyingObject(Value *Ptr) {
10046 while (1) {
10047 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10048 if (CE->getOpcode() == Instruction::BitCast ||
10049 CE->getOpcode() == Instruction::GetElementPtr)
10050 Ptr = CE->getOperand(0);
10051 else
10052 return Ptr;
10053 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10054 Ptr = BCI->getOperand(0);
10055 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10056 Ptr = GEP->getOperand(0);
10057 } else {
10058 return Ptr;
10059 }
10060 }
10061}
10062
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10064 Value *Op = LI.getOperand(0);
10065
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010066 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010067 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10068 if (KnownAlign >
10069 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10070 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010071 LI.setAlignment(KnownAlign);
10072
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010073 // load (cast X) --> cast (load X) iff safe
10074 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010075 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010076 return Res;
10077
10078 // None of the following transforms are legal for volatile loads.
10079 if (LI.isVolatile()) return 0;
10080
10081 if (&LI.getParent()->front() != &LI) {
10082 BasicBlock::iterator BBI = &LI; --BBI;
10083 // If the instruction immediately before this is a store to the same
10084 // address, do a simple form of store->load forwarding.
10085 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10086 if (SI->getOperand(1) == LI.getOperand(0))
10087 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10088 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10089 if (LIB->getOperand(0) == LI.getOperand(0))
10090 return ReplaceInstUsesWith(LI, LIB);
10091 }
10092
Christopher Lamb2c175392007-12-29 07:56:53 +000010093 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10094 const Value *GEPI0 = GEPI->getOperand(0);
10095 // TODO: Consider a target hook for valid address spaces for this xform.
10096 if (isa<ConstantPointerNull>(GEPI0) &&
10097 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010098 // Insert a new store to null instruction before the load to indicate
10099 // that this code is not reachable. We do this instead of inserting
10100 // an unreachable instruction directly because we cannot modify the
10101 // CFG.
10102 new StoreInst(UndefValue::get(LI.getType()),
10103 Constant::getNullValue(Op->getType()), &LI);
10104 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10105 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010106 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010107
10108 if (Constant *C = dyn_cast<Constant>(Op)) {
10109 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010110 // TODO: Consider a target hook for valid address spaces for this xform.
10111 if (isa<UndefValue>(C) || (C->isNullValue() &&
10112 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010113 // Insert a new store to null instruction before the load to indicate that
10114 // this code is not reachable. We do this instead of inserting an
10115 // unreachable instruction directly because we cannot modify the CFG.
10116 new StoreInst(UndefValue::get(LI.getType()),
10117 Constant::getNullValue(Op->getType()), &LI);
10118 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10119 }
10120
10121 // Instcombine load (constant global) into the value loaded.
10122 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10123 if (GV->isConstant() && !GV->isDeclaration())
10124 return ReplaceInstUsesWith(LI, GV->getInitializer());
10125
10126 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010128 if (CE->getOpcode() == Instruction::GetElementPtr) {
10129 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10130 if (GV->isConstant() && !GV->isDeclaration())
10131 if (Constant *V =
10132 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10133 return ReplaceInstUsesWith(LI, V);
10134 if (CE->getOperand(0)->isNullValue()) {
10135 // Insert a new store to null instruction before the load to indicate
10136 // that this code is not reachable. We do this instead of inserting
10137 // an unreachable instruction directly because we cannot modify the
10138 // CFG.
10139 new StoreInst(UndefValue::get(LI.getType()),
10140 Constant::getNullValue(Op->getType()), &LI);
10141 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10142 }
10143
10144 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010145 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146 return Res;
10147 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010149 }
Chris Lattner0270a112007-08-11 18:48:48 +000010150
10151 // If this load comes from anywhere in a constant global, and if the global
10152 // is all undef or zero, we know what it loads.
10153 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10154 if (GV->isConstant() && GV->hasInitializer()) {
10155 if (GV->getInitializer()->isNullValue())
10156 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10157 else if (isa<UndefValue>(GV->getInitializer()))
10158 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10159 }
10160 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010161
10162 if (Op->hasOneUse()) {
10163 // Change select and PHI nodes to select values instead of addresses: this
10164 // helps alias analysis out a lot, allows many others simplifications, and
10165 // exposes redundancy in the code.
10166 //
10167 // Note that we cannot do the transformation unless we know that the
10168 // introduced loads cannot trap! Something like this is valid as long as
10169 // the condition is always false: load (select bool %C, int* null, int* %G),
10170 // but it would not be valid if we transformed it to load from null
10171 // unconditionally.
10172 //
10173 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10174 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10175 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10176 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10177 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10178 SI->getOperand(1)->getName()+".val"), LI);
10179 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10180 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010181 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010182 }
10183
10184 // load (select (cond, null, P)) -> load P
10185 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10186 if (C->isNullValue()) {
10187 LI.setOperand(0, SI->getOperand(2));
10188 return &LI;
10189 }
10190
10191 // load (select (cond, P, null)) -> load P
10192 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10193 if (C->isNullValue()) {
10194 LI.setOperand(0, SI->getOperand(1));
10195 return &LI;
10196 }
10197 }
10198 }
10199 return 0;
10200}
10201
10202/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10203/// when possible.
10204static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10205 User *CI = cast<User>(SI.getOperand(1));
10206 Value *CastOp = CI->getOperand(0);
10207
10208 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10209 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10210 const Type *SrcPTy = SrcTy->getElementType();
10211
10212 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10213 // If the source is an array, the code below will not succeed. Check to
10214 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10215 // constants.
10216 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10217 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10218 if (ASrcTy->getNumElements() != 0) {
10219 Value* Idxs[2];
10220 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10221 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10222 SrcTy = cast<PointerType>(CastOp->getType());
10223 SrcPTy = SrcTy->getElementType();
10224 }
10225
10226 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10227 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10228 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10229
10230 // Okay, we are casting from one integer or pointer type to another of
10231 // the same size. Instead of casting the pointer before
10232 // the store, cast the value to be stored.
10233 Value *NewCast;
10234 Value *SIOp0 = SI.getOperand(0);
10235 Instruction::CastOps opcode = Instruction::BitCast;
10236 const Type* CastSrcTy = SIOp0->getType();
10237 const Type* CastDstTy = SrcPTy;
10238 if (isa<PointerType>(CastDstTy)) {
10239 if (CastSrcTy->isInteger())
10240 opcode = Instruction::IntToPtr;
10241 } else if (isa<IntegerType>(CastDstTy)) {
10242 if (isa<PointerType>(SIOp0->getType()))
10243 opcode = Instruction::PtrToInt;
10244 }
10245 if (Constant *C = dyn_cast<Constant>(SIOp0))
10246 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10247 else
10248 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010249 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010250 SI);
10251 return new StoreInst(NewCast, CastOp);
10252 }
10253 }
10254 }
10255 return 0;
10256}
10257
10258Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10259 Value *Val = SI.getOperand(0);
10260 Value *Ptr = SI.getOperand(1);
10261
10262 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10263 EraseInstFromFunction(SI);
10264 ++NumCombined;
10265 return 0;
10266 }
10267
10268 // If the RHS is an alloca with a single use, zapify the store, making the
10269 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010270 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010271 if (isa<AllocaInst>(Ptr)) {
10272 EraseInstFromFunction(SI);
10273 ++NumCombined;
10274 return 0;
10275 }
10276
10277 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10278 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10279 GEP->getOperand(0)->hasOneUse()) {
10280 EraseInstFromFunction(SI);
10281 ++NumCombined;
10282 return 0;
10283 }
10284 }
10285
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010286 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010287 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10288 if (KnownAlign >
10289 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10290 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010291 SI.setAlignment(KnownAlign);
10292
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010293 // Do really simple DSE, to catch cases where there are several consequtive
10294 // stores to the same location, separated by a few arithmetic operations. This
10295 // situation often occurs with bitfield accesses.
10296 BasicBlock::iterator BBI = &SI;
10297 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10298 --ScanInsts) {
10299 --BBI;
10300
10301 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10302 // Prev store isn't volatile, and stores to the same location?
10303 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10304 ++NumDeadStore;
10305 ++BBI;
10306 EraseInstFromFunction(*PrevSI);
10307 continue;
10308 }
10309 break;
10310 }
10311
10312 // If this is a load, we have to stop. However, if the loaded value is from
10313 // the pointer we're loading and is producing the pointer we're storing,
10314 // then *this* store is dead (X = load P; store X -> P).
10315 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010316 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010317 EraseInstFromFunction(SI);
10318 ++NumCombined;
10319 return 0;
10320 }
10321 // Otherwise, this is a load from some other location. Stores before it
10322 // may not be dead.
10323 break;
10324 }
10325
10326 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010327 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010328 break;
10329 }
10330
10331
10332 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10333
10334 // store X, null -> turns into 'unreachable' in SimplifyCFG
10335 if (isa<ConstantPointerNull>(Ptr)) {
10336 if (!isa<UndefValue>(Val)) {
10337 SI.setOperand(0, UndefValue::get(Val->getType()));
10338 if (Instruction *U = dyn_cast<Instruction>(Val))
10339 AddToWorkList(U); // Dropped a use.
10340 ++NumCombined;
10341 }
10342 return 0; // Do not modify these!
10343 }
10344
10345 // store undef, Ptr -> noop
10346 if (isa<UndefValue>(Val)) {
10347 EraseInstFromFunction(SI);
10348 ++NumCombined;
10349 return 0;
10350 }
10351
10352 // If the pointer destination is a cast, see if we can fold the cast into the
10353 // source instead.
10354 if (isa<CastInst>(Ptr))
10355 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10356 return Res;
10357 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10358 if (CE->isCast())
10359 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10360 return Res;
10361
10362
10363 // If this store is the last instruction in the basic block, and if the block
10364 // ends with an unconditional branch, try to move it to the successor block.
10365 BBI = &SI; ++BBI;
10366 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10367 if (BI->isUnconditional())
10368 if (SimplifyStoreAtEndOfBlock(SI))
10369 return 0; // xform done!
10370
10371 return 0;
10372}
10373
10374/// SimplifyStoreAtEndOfBlock - Turn things like:
10375/// if () { *P = v1; } else { *P = v2 }
10376/// into a phi node with a store in the successor.
10377///
10378/// Simplify things like:
10379/// *P = v1; if () { *P = v2; }
10380/// into a phi node with a store in the successor.
10381///
10382bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10383 BasicBlock *StoreBB = SI.getParent();
10384
10385 // Check to see if the successor block has exactly two incoming edges. If
10386 // so, see if the other predecessor contains a store to the same location.
10387 // if so, insert a PHI node (if needed) and move the stores down.
10388 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10389
10390 // Determine whether Dest has exactly two predecessors and, if so, compute
10391 // the other predecessor.
10392 pred_iterator PI = pred_begin(DestBB);
10393 BasicBlock *OtherBB = 0;
10394 if (*PI != StoreBB)
10395 OtherBB = *PI;
10396 ++PI;
10397 if (PI == pred_end(DestBB))
10398 return false;
10399
10400 if (*PI != StoreBB) {
10401 if (OtherBB)
10402 return false;
10403 OtherBB = *PI;
10404 }
10405 if (++PI != pred_end(DestBB))
10406 return false;
10407
10408
10409 // Verify that the other block ends in a branch and is not otherwise empty.
10410 BasicBlock::iterator BBI = OtherBB->getTerminator();
10411 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10412 if (!OtherBr || BBI == OtherBB->begin())
10413 return false;
10414
10415 // If the other block ends in an unconditional branch, check for the 'if then
10416 // else' case. there is an instruction before the branch.
10417 StoreInst *OtherStore = 0;
10418 if (OtherBr->isUnconditional()) {
10419 // If this isn't a store, or isn't a store to the same location, bail out.
10420 --BBI;
10421 OtherStore = dyn_cast<StoreInst>(BBI);
10422 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10423 return false;
10424 } else {
10425 // Otherwise, the other block ended with a conditional branch. If one of the
10426 // destinations is StoreBB, then we have the if/then case.
10427 if (OtherBr->getSuccessor(0) != StoreBB &&
10428 OtherBr->getSuccessor(1) != StoreBB)
10429 return false;
10430
10431 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10432 // if/then triangle. See if there is a store to the same ptr as SI that
10433 // lives in OtherBB.
10434 for (;; --BBI) {
10435 // Check to see if we find the matching store.
10436 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10437 if (OtherStore->getOperand(1) != SI.getOperand(1))
10438 return false;
10439 break;
10440 }
10441 // If we find something that may be using the stored value, or if we run
10442 // out of instructions, we can't do the xform.
10443 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10444 BBI == OtherBB->begin())
10445 return false;
10446 }
10447
10448 // In order to eliminate the store in OtherBr, we have to
10449 // make sure nothing reads the stored value in StoreBB.
10450 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10451 // FIXME: This should really be AA driven.
10452 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10453 return false;
10454 }
10455 }
10456
10457 // Insert a PHI node now if we need it.
10458 Value *MergedVal = OtherStore->getOperand(0);
10459 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010460 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010461 PN->reserveOperandSpace(2);
10462 PN->addIncoming(SI.getOperand(0), SI.getParent());
10463 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10464 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10465 }
10466
10467 // Advance to a place where it is safe to insert the new store and
10468 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000010469 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010470 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10471 OtherStore->isVolatile()), *BBI);
10472
10473 // Nuke the old stores.
10474 EraseInstFromFunction(SI);
10475 EraseInstFromFunction(*OtherStore);
10476 ++NumCombined;
10477 return true;
10478}
10479
10480
10481Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10482 // Change br (not X), label True, label False to: br X, label False, True
10483 Value *X = 0;
10484 BasicBlock *TrueDest;
10485 BasicBlock *FalseDest;
10486 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10487 !isa<Constant>(X)) {
10488 // Swap Destinations and condition...
10489 BI.setCondition(X);
10490 BI.setSuccessor(0, FalseDest);
10491 BI.setSuccessor(1, TrueDest);
10492 return &BI;
10493 }
10494
10495 // Cannonicalize fcmp_one -> fcmp_oeq
10496 FCmpInst::Predicate FPred; Value *Y;
10497 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10498 TrueDest, FalseDest)))
10499 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10500 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10501 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10502 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10503 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10504 NewSCC->takeName(I);
10505 // Swap Destinations and condition...
10506 BI.setCondition(NewSCC);
10507 BI.setSuccessor(0, FalseDest);
10508 BI.setSuccessor(1, TrueDest);
10509 RemoveFromWorkList(I);
10510 I->eraseFromParent();
10511 AddToWorkList(NewSCC);
10512 return &BI;
10513 }
10514
10515 // Cannonicalize icmp_ne -> icmp_eq
10516 ICmpInst::Predicate IPred;
10517 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10518 TrueDest, FalseDest)))
10519 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10520 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10521 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10522 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10523 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10524 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10525 NewSCC->takeName(I);
10526 // Swap Destinations and condition...
10527 BI.setCondition(NewSCC);
10528 BI.setSuccessor(0, FalseDest);
10529 BI.setSuccessor(1, TrueDest);
10530 RemoveFromWorkList(I);
10531 I->eraseFromParent();;
10532 AddToWorkList(NewSCC);
10533 return &BI;
10534 }
10535
10536 return 0;
10537}
10538
10539Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10540 Value *Cond = SI.getCondition();
10541 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10542 if (I->getOpcode() == Instruction::Add)
10543 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10544 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10545 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10546 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10547 AddRHS));
10548 SI.setOperand(0, I->getOperand(0));
10549 AddToWorkList(I);
10550 return &SI;
10551 }
10552 }
10553 return 0;
10554}
10555
10556/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10557/// is to leave as a vector operation.
10558static bool CheapToScalarize(Value *V, bool isConstant) {
10559 if (isa<ConstantAggregateZero>(V))
10560 return true;
10561 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10562 if (isConstant) return true;
10563 // If all elts are the same, we can extract.
10564 Constant *Op0 = C->getOperand(0);
10565 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10566 if (C->getOperand(i) != Op0)
10567 return false;
10568 return true;
10569 }
10570 Instruction *I = dyn_cast<Instruction>(V);
10571 if (!I) return false;
10572
10573 // Insert element gets simplified to the inserted element or is deleted if
10574 // this is constant idx extract element and its a constant idx insertelt.
10575 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10576 isa<ConstantInt>(I->getOperand(2)))
10577 return true;
10578 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10579 return true;
10580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10581 if (BO->hasOneUse() &&
10582 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10583 CheapToScalarize(BO->getOperand(1), isConstant)))
10584 return true;
10585 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10586 if (CI->hasOneUse() &&
10587 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10588 CheapToScalarize(CI->getOperand(1), isConstant)))
10589 return true;
10590
10591 return false;
10592}
10593
10594/// Read and decode a shufflevector mask.
10595///
10596/// It turns undef elements into values that are larger than the number of
10597/// elements in the input.
10598static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10599 unsigned NElts = SVI->getType()->getNumElements();
10600 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10601 return std::vector<unsigned>(NElts, 0);
10602 if (isa<UndefValue>(SVI->getOperand(2)))
10603 return std::vector<unsigned>(NElts, 2*NElts);
10604
10605 std::vector<unsigned> Result;
10606 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10607 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10608 if (isa<UndefValue>(CP->getOperand(i)))
10609 Result.push_back(NElts*2); // undef -> 8
10610 else
10611 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10612 return Result;
10613}
10614
10615/// FindScalarElement - Given a vector and an element number, see if the scalar
10616/// value is already around as a register, for example if it were inserted then
10617/// extracted from the vector.
10618static Value *FindScalarElement(Value *V, unsigned EltNo) {
10619 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10620 const VectorType *PTy = cast<VectorType>(V->getType());
10621 unsigned Width = PTy->getNumElements();
10622 if (EltNo >= Width) // Out of range access.
10623 return UndefValue::get(PTy->getElementType());
10624
10625 if (isa<UndefValue>(V))
10626 return UndefValue::get(PTy->getElementType());
10627 else if (isa<ConstantAggregateZero>(V))
10628 return Constant::getNullValue(PTy->getElementType());
10629 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10630 return CP->getOperand(EltNo);
10631 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10632 // If this is an insert to a variable element, we don't know what it is.
10633 if (!isa<ConstantInt>(III->getOperand(2)))
10634 return 0;
10635 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10636
10637 // If this is an insert to the element we are looking for, return the
10638 // inserted value.
10639 if (EltNo == IIElt)
10640 return III->getOperand(1);
10641
10642 // Otherwise, the insertelement doesn't modify the value, recurse on its
10643 // vector input.
10644 return FindScalarElement(III->getOperand(0), EltNo);
10645 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10646 unsigned InEl = getShuffleMask(SVI)[EltNo];
10647 if (InEl < Width)
10648 return FindScalarElement(SVI->getOperand(0), InEl);
10649 else if (InEl < Width*2)
10650 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10651 else
10652 return UndefValue::get(PTy->getElementType());
10653 }
10654
10655 // Otherwise, we don't know.
10656 return 0;
10657}
10658
10659Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10660
10661 // If vector val is undef, replace extract with scalar undef.
10662 if (isa<UndefValue>(EI.getOperand(0)))
10663 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10664
10665 // If vector val is constant 0, replace extract with scalar 0.
10666 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10667 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10668
10669 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10670 // If vector val is constant with uniform operands, replace EI
10671 // with that operand
10672 Constant *op0 = C->getOperand(0);
10673 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10674 if (C->getOperand(i) != op0) {
10675 op0 = 0;
10676 break;
10677 }
10678 if (op0)
10679 return ReplaceInstUsesWith(EI, op0);
10680 }
10681
10682 // If extracting a specified index from the vector, see if we can recursively
10683 // find a previously computed scalar that was inserted into the vector.
10684 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10685 unsigned IndexVal = IdxC->getZExtValue();
10686 unsigned VectorWidth =
10687 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10688
10689 // If this is extracting an invalid index, turn this into undef, to avoid
10690 // crashing the code below.
10691 if (IndexVal >= VectorWidth)
10692 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10693
10694 // This instruction only demands the single element from the input vector.
10695 // If the input vector has a single use, simplify it based on this use
10696 // property.
10697 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10698 uint64_t UndefElts;
10699 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10700 1 << IndexVal,
10701 UndefElts)) {
10702 EI.setOperand(0, V);
10703 return &EI;
10704 }
10705 }
10706
10707 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10708 return ReplaceInstUsesWith(EI, Elt);
10709
10710 // If the this extractelement is directly using a bitcast from a vector of
10711 // the same number of elements, see if we can find the source element from
10712 // it. In this case, we will end up needing to bitcast the scalars.
10713 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10714 if (const VectorType *VT =
10715 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10716 if (VT->getNumElements() == VectorWidth)
10717 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10718 return new BitCastInst(Elt, EI.getType());
10719 }
10720 }
10721
10722 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10723 if (I->hasOneUse()) {
10724 // Push extractelement into predecessor operation if legal and
10725 // profitable to do so
10726 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10727 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10728 if (CheapToScalarize(BO, isConstantElt)) {
10729 ExtractElementInst *newEI0 =
10730 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10731 EI.getName()+".lhs");
10732 ExtractElementInst *newEI1 =
10733 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10734 EI.getName()+".rhs");
10735 InsertNewInstBefore(newEI0, EI);
10736 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000010737 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010738 }
10739 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010740 unsigned AS =
10741 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010742 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10743 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010744 GetElementPtrInst *GEP =
10745 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010746 InsertNewInstBefore(GEP, EI);
10747 return new LoadInst(GEP);
10748 }
10749 }
10750 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10751 // Extracting the inserted element?
10752 if (IE->getOperand(2) == EI.getOperand(1))
10753 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10754 // If the inserted and extracted elements are constants, they must not
10755 // be the same value, extract from the pre-inserted value instead.
10756 if (isa<Constant>(IE->getOperand(2)) &&
10757 isa<Constant>(EI.getOperand(1))) {
10758 AddUsesToWorkList(EI);
10759 EI.setOperand(0, IE->getOperand(0));
10760 return &EI;
10761 }
10762 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10763 // If this is extracting an element from a shufflevector, figure out where
10764 // it came from and extract from the appropriate input element instead.
10765 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10766 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10767 Value *Src;
10768 if (SrcIdx < SVI->getType()->getNumElements())
10769 Src = SVI->getOperand(0);
10770 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10771 SrcIdx -= SVI->getType()->getNumElements();
10772 Src = SVI->getOperand(1);
10773 } else {
10774 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10775 }
10776 return new ExtractElementInst(Src, SrcIdx);
10777 }
10778 }
10779 }
10780 return 0;
10781}
10782
10783/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10784/// elements from either LHS or RHS, return the shuffle mask and true.
10785/// Otherwise, return false.
10786static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10787 std::vector<Constant*> &Mask) {
10788 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10789 "Invalid CollectSingleShuffleElements");
10790 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10791
10792 if (isa<UndefValue>(V)) {
10793 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10794 return true;
10795 } else if (V == LHS) {
10796 for (unsigned i = 0; i != NumElts; ++i)
10797 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10798 return true;
10799 } else if (V == RHS) {
10800 for (unsigned i = 0; i != NumElts; ++i)
10801 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10802 return true;
10803 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10804 // If this is an insert of an extract from some other vector, include it.
10805 Value *VecOp = IEI->getOperand(0);
10806 Value *ScalarOp = IEI->getOperand(1);
10807 Value *IdxOp = IEI->getOperand(2);
10808
10809 if (!isa<ConstantInt>(IdxOp))
10810 return false;
10811 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10812
10813 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10814 // Okay, we can handle this if the vector we are insertinting into is
10815 // transitively ok.
10816 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10817 // If so, update the mask to reflect the inserted undef.
10818 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10819 return true;
10820 }
10821 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10822 if (isa<ConstantInt>(EI->getOperand(1)) &&
10823 EI->getOperand(0)->getType() == V->getType()) {
10824 unsigned ExtractedIdx =
10825 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10826
10827 // This must be extracting from either LHS or RHS.
10828 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10829 // Okay, we can handle this if the vector we are insertinting into is
10830 // transitively ok.
10831 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10832 // If so, update the mask to reflect the inserted value.
10833 if (EI->getOperand(0) == LHS) {
10834 Mask[InsertedIdx & (NumElts-1)] =
10835 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10836 } else {
10837 assert(EI->getOperand(0) == RHS);
10838 Mask[InsertedIdx & (NumElts-1)] =
10839 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10840
10841 }
10842 return true;
10843 }
10844 }
10845 }
10846 }
10847 }
10848 // TODO: Handle shufflevector here!
10849
10850 return false;
10851}
10852
10853/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10854/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10855/// that computes V and the LHS value of the shuffle.
10856static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10857 Value *&RHS) {
10858 assert(isa<VectorType>(V->getType()) &&
10859 (RHS == 0 || V->getType() == RHS->getType()) &&
10860 "Invalid shuffle!");
10861 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10862
10863 if (isa<UndefValue>(V)) {
10864 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10865 return V;
10866 } else if (isa<ConstantAggregateZero>(V)) {
10867 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10868 return V;
10869 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10870 // If this is an insert of an extract from some other vector, include it.
10871 Value *VecOp = IEI->getOperand(0);
10872 Value *ScalarOp = IEI->getOperand(1);
10873 Value *IdxOp = IEI->getOperand(2);
10874
10875 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10876 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10877 EI->getOperand(0)->getType() == V->getType()) {
10878 unsigned ExtractedIdx =
10879 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10880 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10881
10882 // Either the extracted from or inserted into vector must be RHSVec,
10883 // otherwise we'd end up with a shuffle of three inputs.
10884 if (EI->getOperand(0) == RHS || RHS == 0) {
10885 RHS = EI->getOperand(0);
10886 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10887 Mask[InsertedIdx & (NumElts-1)] =
10888 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10889 return V;
10890 }
10891
10892 if (VecOp == RHS) {
10893 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10894 // Everything but the extracted element is replaced with the RHS.
10895 for (unsigned i = 0; i != NumElts; ++i) {
10896 if (i != InsertedIdx)
10897 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10898 }
10899 return V;
10900 }
10901
10902 // If this insertelement is a chain that comes from exactly these two
10903 // vectors, return the vector and the effective shuffle.
10904 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10905 return EI->getOperand(0);
10906
10907 }
10908 }
10909 }
10910 // TODO: Handle shufflevector here!
10911
10912 // Otherwise, can't do anything fancy. Return an identity vector.
10913 for (unsigned i = 0; i != NumElts; ++i)
10914 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10915 return V;
10916}
10917
10918Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10919 Value *VecOp = IE.getOperand(0);
10920 Value *ScalarOp = IE.getOperand(1);
10921 Value *IdxOp = IE.getOperand(2);
10922
10923 // Inserting an undef or into an undefined place, remove this.
10924 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10925 ReplaceInstUsesWith(IE, VecOp);
10926
10927 // If the inserted element was extracted from some other vector, and if the
10928 // indexes are constant, try to turn this into a shufflevector operation.
10929 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10930 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10931 EI->getOperand(0)->getType() == IE.getType()) {
10932 unsigned NumVectorElts = IE.getType()->getNumElements();
10933 unsigned ExtractedIdx =
10934 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10935 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10936
10937 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10938 return ReplaceInstUsesWith(IE, VecOp);
10939
10940 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10941 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10942
10943 // If we are extracting a value from a vector, then inserting it right
10944 // back into the same place, just use the input vector.
10945 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10946 return ReplaceInstUsesWith(IE, VecOp);
10947
10948 // We could theoretically do this for ANY input. However, doing so could
10949 // turn chains of insertelement instructions into a chain of shufflevector
10950 // instructions, and right now we do not merge shufflevectors. As such,
10951 // only do this in a situation where it is clear that there is benefit.
10952 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10953 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10954 // the values of VecOp, except then one read from EIOp0.
10955 // Build a new shuffle mask.
10956 std::vector<Constant*> Mask;
10957 if (isa<UndefValue>(VecOp))
10958 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10959 else {
10960 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10961 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10962 NumVectorElts));
10963 }
10964 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10965 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10966 ConstantVector::get(Mask));
10967 }
10968
10969 // If this insertelement isn't used by some other insertelement, turn it
10970 // (and any insertelements it points to), into one big shuffle.
10971 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10972 std::vector<Constant*> Mask;
10973 Value *RHS = 0;
10974 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10975 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10976 // We now have a shuffle of LHS, RHS, Mask.
10977 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10978 }
10979 }
10980 }
10981
10982 return 0;
10983}
10984
10985
10986Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10987 Value *LHS = SVI.getOperand(0);
10988 Value *RHS = SVI.getOperand(1);
10989 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10990
10991 bool MadeChange = false;
10992
10993 // Undefined shuffle mask -> undefined value.
10994 if (isa<UndefValue>(SVI.getOperand(2)))
10995 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10996
10997 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10998 // the undef, change them to undefs.
10999 if (isa<UndefValue>(SVI.getOperand(1))) {
11000 // Scan to see if there are any references to the RHS. If so, replace them
11001 // with undef element refs and set MadeChange to true.
11002 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11003 if (Mask[i] >= e && Mask[i] != 2*e) {
11004 Mask[i] = 2*e;
11005 MadeChange = true;
11006 }
11007 }
11008
11009 if (MadeChange) {
11010 // Remap any references to RHS to use LHS.
11011 std::vector<Constant*> Elts;
11012 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11013 if (Mask[i] == 2*e)
11014 Elts.push_back(UndefValue::get(Type::Int32Ty));
11015 else
11016 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11017 }
11018 SVI.setOperand(2, ConstantVector::get(Elts));
11019 }
11020 }
11021
11022 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11023 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11024 if (LHS == RHS || isa<UndefValue>(LHS)) {
11025 if (isa<UndefValue>(LHS) && LHS == RHS) {
11026 // shuffle(undef,undef,mask) -> undef.
11027 return ReplaceInstUsesWith(SVI, LHS);
11028 }
11029
11030 // Remap any references to RHS to use LHS.
11031 std::vector<Constant*> Elts;
11032 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11033 if (Mask[i] >= 2*e)
11034 Elts.push_back(UndefValue::get(Type::Int32Ty));
11035 else {
11036 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11037 (Mask[i] < e && isa<UndefValue>(LHS)))
11038 Mask[i] = 2*e; // Turn into undef.
11039 else
11040 Mask[i] &= (e-1); // Force to LHS.
11041 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11042 }
11043 }
11044 SVI.setOperand(0, SVI.getOperand(1));
11045 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11046 SVI.setOperand(2, ConstantVector::get(Elts));
11047 LHS = SVI.getOperand(0);
11048 RHS = SVI.getOperand(1);
11049 MadeChange = true;
11050 }
11051
11052 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11053 bool isLHSID = true, isRHSID = true;
11054
11055 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11056 if (Mask[i] >= e*2) continue; // Ignore undef values.
11057 // Is this an identity shuffle of the LHS value?
11058 isLHSID &= (Mask[i] == i);
11059
11060 // Is this an identity shuffle of the RHS value?
11061 isRHSID &= (Mask[i]-e == i);
11062 }
11063
11064 // Eliminate identity shuffles.
11065 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11066 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11067
11068 // If the LHS is a shufflevector itself, see if we can combine it with this
11069 // one without producing an unusual shuffle. Here we are really conservative:
11070 // we are absolutely afraid of producing a shuffle mask not in the input
11071 // program, because the code gen may not be smart enough to turn a merged
11072 // shuffle into two specific shuffles: it may produce worse code. As such,
11073 // we only merge two shuffles if the result is one of the two input shuffle
11074 // masks. In this case, merging the shuffles just removes one instruction,
11075 // which we know is safe. This is good for things like turning:
11076 // (splat(splat)) -> splat.
11077 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11078 if (isa<UndefValue>(RHS)) {
11079 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11080
11081 std::vector<unsigned> NewMask;
11082 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11083 if (Mask[i] >= 2*e)
11084 NewMask.push_back(2*e);
11085 else
11086 NewMask.push_back(LHSMask[Mask[i]]);
11087
11088 // If the result mask is equal to the src shuffle or this shuffle mask, do
11089 // the replacement.
11090 if (NewMask == LHSMask || NewMask == Mask) {
11091 std::vector<Constant*> Elts;
11092 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11093 if (NewMask[i] >= e*2) {
11094 Elts.push_back(UndefValue::get(Type::Int32Ty));
11095 } else {
11096 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11097 }
11098 }
11099 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11100 LHSSVI->getOperand(1),
11101 ConstantVector::get(Elts));
11102 }
11103 }
11104 }
11105
11106 return MadeChange ? &SVI : 0;
11107}
11108
11109
11110
11111
11112/// TryToSinkInstruction - Try to move the specified instruction from its
11113/// current block into the beginning of DestBlock, which can only happen if it's
11114/// safe to move the instruction past all of the instructions between it and the
11115/// end of its block.
11116static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11117 assert(I->hasOneUse() && "Invariants didn't hold!");
11118
11119 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011120 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11121 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011122
11123 // Do not sink alloca instructions out of the entry block.
11124 if (isa<AllocaInst>(I) && I->getParent() ==
11125 &DestBlock->getParent()->getEntryBlock())
11126 return false;
11127
11128 // We can only sink load instructions if there is nothing between the load and
11129 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011130 if (I->mayReadFromMemory()) {
11131 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011132 Scan != E; ++Scan)
11133 if (Scan->mayWriteToMemory())
11134 return false;
11135 }
11136
Dan Gohman514277c2008-05-23 21:05:58 +000011137 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011138
11139 I->moveBefore(InsertPos);
11140 ++NumSunkInst;
11141 return true;
11142}
11143
11144
11145/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11146/// all reachable code to the worklist.
11147///
11148/// This has a couple of tricks to make the code faster and more powerful. In
11149/// particular, we constant fold and DCE instructions as we go, to avoid adding
11150/// them to the worklist (this significantly speeds up instcombine on code where
11151/// many instructions are dead or constant). Additionally, if we find a branch
11152/// whose condition is a known constant, we only visit the reachable successors.
11153///
11154static void AddReachableCodeToWorklist(BasicBlock *BB,
11155 SmallPtrSet<BasicBlock*, 64> &Visited,
11156 InstCombiner &IC,
11157 const TargetData *TD) {
11158 std::vector<BasicBlock*> Worklist;
11159 Worklist.push_back(BB);
11160
11161 while (!Worklist.empty()) {
11162 BB = Worklist.back();
11163 Worklist.pop_back();
11164
11165 // We have now visited this block! If we've already been here, ignore it.
11166 if (!Visited.insert(BB)) continue;
11167
11168 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11169 Instruction *Inst = BBI++;
11170
11171 // DCE instruction if trivially dead.
11172 if (isInstructionTriviallyDead(Inst)) {
11173 ++NumDeadInst;
11174 DOUT << "IC: DCE: " << *Inst;
11175 Inst->eraseFromParent();
11176 continue;
11177 }
11178
11179 // ConstantProp instruction if trivially constant.
11180 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11181 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11182 Inst->replaceAllUsesWith(C);
11183 ++NumConstProp;
11184 Inst->eraseFromParent();
11185 continue;
11186 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011187
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011188 IC.AddToWorkList(Inst);
11189 }
11190
11191 // Recursively visit successors. If this is a branch or switch on a
11192 // constant, only visit the reachable successor.
11193 TerminatorInst *TI = BB->getTerminator();
11194 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11195 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11196 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011197 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011198 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011199 continue;
11200 }
11201 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11202 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11203 // See if this is an explicit destination.
11204 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11205 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011206 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011207 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011208 continue;
11209 }
11210
11211 // Otherwise it is the default destination.
11212 Worklist.push_back(SI->getSuccessor(0));
11213 continue;
11214 }
11215 }
11216
11217 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11218 Worklist.push_back(TI->getSuccessor(i));
11219 }
11220}
11221
11222bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11223 bool Changed = false;
11224 TD = &getAnalysis<TargetData>();
11225
11226 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11227 << F.getNameStr() << "\n");
11228
11229 {
11230 // Do a depth-first traversal of the function, populate the worklist with
11231 // the reachable instructions. Ignore blocks that are not reachable. Keep
11232 // track of which blocks we visit.
11233 SmallPtrSet<BasicBlock*, 64> Visited;
11234 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11235
11236 // Do a quick scan over the function. If we find any blocks that are
11237 // unreachable, remove any instructions inside of them. This prevents
11238 // the instcombine code from having to deal with some bad special cases.
11239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11240 if (!Visited.count(BB)) {
11241 Instruction *Term = BB->getTerminator();
11242 while (Term != BB->begin()) { // Remove instrs bottom-up
11243 BasicBlock::iterator I = Term; --I;
11244
11245 DOUT << "IC: DCE: " << *I;
11246 ++NumDeadInst;
11247
11248 if (!I->use_empty())
11249 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11250 I->eraseFromParent();
11251 }
11252 }
11253 }
11254
11255 while (!Worklist.empty()) {
11256 Instruction *I = RemoveOneFromWorkList();
11257 if (I == 0) continue; // skip null values.
11258
11259 // Check to see if we can DCE the instruction.
11260 if (isInstructionTriviallyDead(I)) {
11261 // Add operands to the worklist.
11262 if (I->getNumOperands() < 4)
11263 AddUsesToWorkList(*I);
11264 ++NumDeadInst;
11265
11266 DOUT << "IC: DCE: " << *I;
11267
11268 I->eraseFromParent();
11269 RemoveFromWorkList(I);
11270 continue;
11271 }
11272
11273 // Instruction isn't dead, see if we can constant propagate it.
11274 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11275 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11276
11277 // Add operands to the worklist.
11278 AddUsesToWorkList(*I);
11279 ReplaceInstUsesWith(*I, C);
11280
11281 ++NumConstProp;
11282 I->eraseFromParent();
11283 RemoveFromWorkList(I);
11284 continue;
11285 }
11286
Nick Lewyckyadb67922008-05-25 20:56:15 +000011287 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11288 // See if we can constant fold its operands.
11289 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11290 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11291 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11292 i->set(NewC);
11293 }
11294 }
11295 }
11296
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011297 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011298 // FIXME: Remove GetResultInst test when first class support for aggregates
11299 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011300 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011301 BasicBlock *BB = I->getParent();
11302 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11303 if (UserParent != BB) {
11304 bool UserIsSuccessor = false;
11305 // See if the user is one of our successors.
11306 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11307 if (*SI == UserParent) {
11308 UserIsSuccessor = true;
11309 break;
11310 }
11311
11312 // If the user is one of our immediate successors, and if that successor
11313 // only has us as a predecessors (we'd have to split the critical edge
11314 // otherwise), we can keep going.
11315 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11316 next(pred_begin(UserParent)) == pred_end(UserParent))
11317 // Okay, the CFG is simple enough, try to sink this instruction.
11318 Changed |= TryToSinkInstruction(I, UserParent);
11319 }
11320 }
11321
11322 // Now that we have an instruction, try combining it to simplify it...
11323#ifndef NDEBUG
11324 std::string OrigI;
11325#endif
11326 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11327 if (Instruction *Result = visit(*I)) {
11328 ++NumCombined;
11329 // Should we replace the old instruction with a new one?
11330 if (Result != I) {
11331 DOUT << "IC: Old = " << *I
11332 << " New = " << *Result;
11333
11334 // Everything uses the new instruction now.
11335 I->replaceAllUsesWith(Result);
11336
11337 // Push the new instruction and any users onto the worklist.
11338 AddToWorkList(Result);
11339 AddUsersToWorkList(*Result);
11340
11341 // Move the name to the new instruction first.
11342 Result->takeName(I);
11343
11344 // Insert the new instruction into the basic block...
11345 BasicBlock *InstParent = I->getParent();
11346 BasicBlock::iterator InsertPos = I;
11347
11348 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11349 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11350 ++InsertPos;
11351
11352 InstParent->getInstList().insert(InsertPos, Result);
11353
11354 // Make sure that we reprocess all operands now that we reduced their
11355 // use counts.
11356 AddUsesToWorkList(*I);
11357
11358 // Instructions can end up on the worklist more than once. Make sure
11359 // we do not process an instruction that has been deleted.
11360 RemoveFromWorkList(I);
11361
11362 // Erase the old instruction.
11363 InstParent->getInstList().erase(I);
11364 } else {
11365#ifndef NDEBUG
11366 DOUT << "IC: Mod = " << OrigI
11367 << " New = " << *I;
11368#endif
11369
11370 // If the instruction was modified, it's possible that it is now dead.
11371 // if so, remove it.
11372 if (isInstructionTriviallyDead(I)) {
11373 // Make sure we process all operands now that we are reducing their
11374 // use counts.
11375 AddUsesToWorkList(*I);
11376
11377 // Instructions may end up in the worklist more than once. Erase all
11378 // occurrences of this instruction.
11379 RemoveFromWorkList(I);
11380 I->eraseFromParent();
11381 } else {
11382 AddToWorkList(I);
11383 AddUsersToWorkList(*I);
11384 }
11385 }
11386 Changed = true;
11387 }
11388 }
11389
11390 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011391
11392 // Do an explicit clear, this shrinks the map if needed.
11393 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011394 return Changed;
11395}
11396
11397
11398bool InstCombiner::runOnFunction(Function &F) {
11399 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11400
11401 bool EverMadeChange = false;
11402
11403 // Iterate while there is work to do.
11404 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011405 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011406 EverMadeChange = true;
11407 return EverMadeChange;
11408}
11409
11410FunctionPass *llvm::createInstructionCombiningPass() {
11411 return new InstCombiner();
11412}
11413