blob: 675f7ec57146f76f99546b59dbe799c4ccac9878 [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) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 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) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 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
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
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);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236
237 // visitInstruction - Specify what to return for unhandled instructions...
238 Instruction *visitInstruction(Instruction &I) { return 0; }
239
240 private:
241 Instruction *visitCallSite(CallSite CS);
242 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000243 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247
248 public:
249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
251 //
252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
257 AddToWorkList(New);
258 return New;
259 }
260
261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
263 /// cast.
264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265 Instruction &Pos) {
266 if (V->getType() == Ty) return V;
267
268 if (Constant *CV = dyn_cast<Constant>(V))
269 return ConstantExpr::getCast(opc, CV, Ty);
270
Gabor Greifa645dd32008-05-16 19:29:10 +0000271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 AddToWorkList(C);
273 return C;
274 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000275
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278 }
279
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280
281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
285 // modified.
286 //
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288 AddUsersToWorkList(I); // Add all modified instrs to worklist
289 if (&I != V) {
290 I.replaceAllUsesWith(V);
291 return &I;
292 } else {
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
296 return &I;
297 }
298 }
299
300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
305 //
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
308 if (Old != New)
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
311 AddToWorkList(I);
312 if (Instruction *I = dyn_cast<Instruction>(New))
313 AddToWorkList(I);
314 return true;
315 }
316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
324 RemoveFromWorkList(&I);
325 I.eraseFromParent();
326 return 0; // Don't do anything with FI
327 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341
342 private:
343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
346 ///
347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
349 Instruction *InsertBefore);
350
351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
353 bool SimplifyCommutative(BinaryOperator &I);
354
355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
358
359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
363 unsigned Depth = 0);
364
365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
367
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378
379
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
382
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000392
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395
Dan Gohman2d648bb2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397 unsigned CastOpc,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000401
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403}
404
Dan Gohman089efff2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414 return 3;
415 return 4;
416 }
417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419}
420
421// isOnlyUse - Return true if this instruction will be deleted if we stop using
422// it.
423static bool isOnlyUse(Value *V) {
424 return V->hasOneUse() || isa<Constant>(V);
425}
426
427// getPromotedType - Return the specified type promoted as it would be to pass
428// though a va_arg area...
429static const Type *getPromotedType(const Type *Ty) {
430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
433 }
434 return Ty;
435}
436
437/// getBitCastOperand - If the specified operand is a CastInst or a constant
438/// expression bitcast, return the operand value, otherwise return null.
439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441 return I->getOperand(0);
442 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443 if (CE->getOpcode() == Instruction::BitCast)
444 return CE->getOperand(0);
445 return 0;
446}
447
448/// This function is a wrapper around CastInst::isEliminableCastPair. It
449/// simply extracts arguments and returns what that function returns.
450static Instruction::CastOps
451isEliminableCastPair(
452 const CastInst *CI, ///< The first cast instruction
453 unsigned opcode, ///< The opcode of the second cast instruction
454 const Type *DstTy, ///< The target type for the second cast instruction
455 TargetData *TD ///< The target data for pointer size
456) {
457
458 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
459 const Type *MidTy = CI->getType(); // B from above
460
461 // Get the opcodes of the two Cast instructions
462 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465 return Instruction::CastOps(
466 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467 DstTy, TD->getIntPtrType()));
468}
469
470/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471/// in any code being generated. It does not require codegen if V is simple
472/// enough or if the cast can be folded into other casts.
473static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
474 const Type *Ty, TargetData *TD) {
475 if (V->getType() == Ty || isa<Constant>(V)) return false;
476
477 // If this is another cast that can be eliminated, it isn't codegen either.
478 if (const CastInst *CI = dyn_cast<CastInst>(V))
479 if (isEliminableCastPair(CI, opcode, Ty, TD))
480 return false;
481 return true;
482}
483
484/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485/// InsertBefore instruction. This is specialized a bit to avoid inserting
486/// casts that are known to not do anything...
487///
488Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489 Value *V, const Type *DestTy,
490 Instruction *InsertBefore) {
491 if (V->getType() == DestTy) return V;
492 if (Constant *C = dyn_cast<Constant>(V))
493 return ConstantExpr::getCast(opcode, C, DestTy);
494
495 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496}
497
498// SimplifyCommutative - This performs a few simplifications for commutative
499// operators:
500//
501// 1. Order operands such that they are listed from right (least complex) to
502// left (most complex). This puts constants before unary operators before
503// binary operators.
504//
505// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507//
508bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509 bool Changed = false;
510 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511 Changed = !I.swapOperands();
512
513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
518 Constant *Folded = ConstantExpr::get(I.getOpcode(),
519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
535 AddToWorkList(New);
536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
539 }
540 }
541 return Changed;
542}
543
544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
548 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549 return false;
550 I.swapOperands();
551 // Compare instructions are not associative so there's nothing else we can do.
552 return true;
553}
554
555// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556// if the LHS is a constant zero (which is the 'negate' form).
557//
558static inline Value *dyn_castNegVal(Value *V) {
559 if (BinaryOperator::isNeg(V))
560 return BinaryOperator::getNegArgument(V);
561
562 // Constants can be considered to be negated values if they can be folded.
563 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000565
566 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567 if (C->getType()->getElementType()->isInteger())
568 return ConstantExpr::getNeg(C);
569
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 return 0;
571}
572
573static inline Value *dyn_castNotVal(Value *V) {
574 if (BinaryOperator::isNot(V))
575 return BinaryOperator::getNotArgument(V);
576
577 // Constants can be considered to be not'ed values...
578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579 return ConstantInt::get(~C->getValue());
580 return 0;
581}
582
583// dyn_castFoldableMul - If this value is a multiply that can be folded into
584// other computations (because it has a constant operand), return the
585// non-constant operand of the multiply, and set CST to point to the multiplier.
586// Otherwise, return null.
587//
588static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589 if (V->hasOneUse() && V->getType()->isInteger())
590 if (Instruction *I = dyn_cast<Instruction>(V)) {
591 if (I->getOpcode() == Instruction::Mul)
592 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593 return I->getOperand(0);
594 if (I->getOpcode() == Instruction::Shl)
595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596 // The multiplier is really 1 << CST.
597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600 return I->getOperand(0);
601 }
602 }
603 return 0;
604}
605
606/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607/// expression, return it.
608static User *dyn_castGetElementPtr(Value *V) {
609 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611 if (CE->getOpcode() == Instruction::GetElementPtr)
612 return cast<User>(V);
613 return false;
614}
615
Dan Gohman2d648bb2008-04-10 18:43:06 +0000616/// getOpcode - If this is an Instruction or a ConstantExpr, return the
617/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000618static unsigned getOpcode(const Value *V) {
619 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000620 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000621 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000622 return CE->getOpcode();
623 // Use UserOp1 to mean there's no opcode.
624 return Instruction::UserOp1;
625}
626
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627/// AddOne - Add one to a ConstantInt
628static ConstantInt *AddOne(ConstantInt *C) {
629 APInt Val(C->getValue());
630 return ConstantInt::get(++Val);
631}
632/// SubOne - Subtract one from a ConstantInt
633static ConstantInt *SubOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(--Val);
636}
637/// Add - Add two ConstantInts together
638static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() + C2->getValue());
640}
641/// And - Bitwise AND two ConstantInts together
642static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() & C2->getValue());
644}
645/// Subtract - Subtract one ConstantInt from another
646static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() - C2->getValue());
648}
649/// Multiply - Multiply two ConstantInts together
650static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651 return ConstantInt::get(C1->getValue() * C2->getValue());
652}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000653/// MultiplyOverflows - True if the multiply can not be expressed in an int
654/// this size.
655static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656 uint32_t W = C1->getBitWidth();
657 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658 if (sign) {
659 LHSExt.sext(W * 2);
660 RHSExt.sext(W * 2);
661 } else {
662 LHSExt.zext(W * 2);
663 RHSExt.zext(W * 2);
664 }
665
666 APInt MulExt = LHSExt * RHSExt;
667
668 if (sign) {
669 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671 return MulExt.slt(Min) || MulExt.sgt(Max);
672 } else
673 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676
677/// ShrinkDemandedConstant - Check to see if the specified operand of the
678/// specified instruction is a constant integer. If so, check to see if there
679/// are any bits set in the constant that are not demanded. If so, shrink the
680/// constant and return true.
681static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
682 APInt Demanded) {
683 assert(I && "No instruction?");
684 assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686 // If the operand is not a constant integer, nothing to do.
687 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688 if (!OpC) return false;
689
690 // If there are no bits set that aren't demanded, nothing to do.
691 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692 if ((~Demanded & OpC->getValue()) == 0)
693 return false;
694
695 // This instruction is producing bits that are not demanded. Shrink the RHS.
696 Demanded &= OpC->getValue();
697 I->setOperand(OpNo, ConstantInt::get(Demanded));
698 return true;
699}
700
701// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
702// set of known zero and one bits, compute the maximum and minimum values that
703// could have the specified known zero and known one bits, returning them in
704// min/max.
705static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706 const APInt& KnownZero,
707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
709 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710 assert(KnownZero.getBitWidth() == BitWidth &&
711 KnownOne.getBitWidth() == BitWidth &&
712 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714 APInt UnknownBits = ~(KnownZero|KnownOne);
715
716 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717 // bit if it is unknown.
718 Min = KnownOne;
719 Max = KnownOne|UnknownBits;
720
721 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722 Min.set(BitWidth-1);
723 Max.clear(BitWidth-1);
724 }
725}
726
727// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728// a set of known zero and one bits, compute the maximum and minimum values that
729// could have the specified known zero and known one bits, returning them in
730// min/max.
731static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000732 const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 assert(KnownZero.getBitWidth() == BitWidth &&
737 KnownOne.getBitWidth() == BitWidth &&
738 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740 APInt UnknownBits = ~(KnownZero|KnownOne);
741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
747
748/// SimplifyDemandedBits - This function attempts to replace V with a simpler
749/// value based on the demanded bits. When this function is called, it is known
750/// that only the bits set in DemandedMask of the result of V are ever used
751/// downstream. Consequently, depending on the mask and V, it may be possible
752/// to replace V with a constant or one of its operands. In such cases, this
753/// function does the replacement and returns true. In all other cases, it
754/// returns false after analyzing the expression and setting KnownOne and known
755/// to be one in the expression. KnownZero contains all the bits that are known
756/// to be zero in the expression. These are provided to potentially allow the
757/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758/// the expression. KnownOne and KnownZero always follow the invariant that
759/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760/// the bits in KnownOne and KnownZero may only be accurate for those bits set
761/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762/// and KnownOne must all be the same.
763bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764 APInt& KnownZero, APInt& KnownOne,
765 unsigned Depth) {
766 assert(V != 0 && "Null pointer of Value???");
767 assert(Depth <= 6 && "Limit Search Depth");
768 uint32_t BitWidth = DemandedMask.getBitWidth();
769 const IntegerType *VTy = cast<IntegerType>(V->getType());
770 assert(VTy->getBitWidth() == BitWidth &&
771 KnownZero.getBitWidth() == BitWidth &&
772 KnownOne.getBitWidth() == BitWidth &&
773 "Value *V, DemandedMask, KnownZero and KnownOne \
774 must have same BitWidth");
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776 // We know all of the bits for a constant!
777 KnownOne = CI->getValue() & DemandedMask;
778 KnownZero = ~KnownOne & DemandedMask;
779 return false;
780 }
781
782 KnownZero.clear();
783 KnownOne.clear();
784 if (!V->hasOneUse()) { // Other users may use these bits.
785 if (Depth != 0) { // Not at the root.
786 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788 return false;
789 }
790 // If this is the root being simplified, allow it to have multiple uses,
791 // just set the DemandedMask to all bits.
792 DemandedMask = APInt::getAllOnesValue(BitWidth);
793 } else if (DemandedMask == 0) { // Not demanding any bits from V.
794 if (V != UndefValue::get(VTy))
795 return UpdateValueUsesWith(V, UndefValue::get(VTy));
796 return false;
797 } else if (Depth == 6) { // Limit search depth.
798 return false;
799 }
800
801 Instruction *I = dyn_cast<Instruction>(V);
802 if (!I) return false; // Only analyze instructions.
803
804 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000807 default:
808 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 case Instruction::And:
811 // If either the LHS or the RHS are Zero, the result is zero.
812 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813 RHSKnownZero, RHSKnownOne, Depth+1))
814 return true;
815 assert((RHSKnownZero & RHSKnownOne) == 0 &&
816 "Bits known to be one AND zero?");
817
818 // If something is known zero on the RHS, the bits aren't demanded on the
819 // LHS.
820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821 LHSKnownZero, LHSKnownOne, Depth+1))
822 return true;
823 assert((LHSKnownZero & LHSKnownOne) == 0 &&
824 "Bits known to be one AND zero?");
825
826 // If all of the demanded bits are known 1 on one side, return the other.
827 // These bits cannot contribute to the result of the 'and'.
828 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
829 (DemandedMask & ~LHSKnownZero))
830 return UpdateValueUsesWith(I, I->getOperand(0));
831 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
832 (DemandedMask & ~RHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(1));
834
835 // If all of the demanded bits in the inputs are known zeros, return zero.
836 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838
839 // If the RHS is a constant, see if we can simplify it.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841 return UpdateValueUsesWith(I, I);
842
843 // Output known-1 bits are only known if set in both the LHS & RHS.
844 RHSKnownOne &= LHSKnownOne;
845 // Output known-0 are known to be clear if zero in either the LHS | RHS.
846 RHSKnownZero |= LHSKnownZero;
847 break;
848 case Instruction::Or:
849 // If either the LHS or the RHS are One, the result is One.
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1))
852 return true;
853 assert((RHSKnownZero & RHSKnownOne) == 0 &&
854 "Bits known to be one AND zero?");
855 // If something is known one on the RHS, the bits aren't demanded on the
856 // LHS.
857 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
858 LHSKnownZero, LHSKnownOne, Depth+1))
859 return true;
860 assert((LHSKnownZero & LHSKnownOne) == 0 &&
861 "Bits known to be one AND zero?");
862
863 // If all of the demanded bits are known zero on one side, return the other.
864 // These bits cannot contribute to the result of the 'or'.
865 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
866 (DemandedMask & ~LHSKnownOne))
867 return UpdateValueUsesWith(I, I->getOperand(0));
868 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
869 (DemandedMask & ~RHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(1));
871
872 // If all of the potentially set bits on one side are known to be set on
873 // the other side, just use the 'other' side.
874 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
875 (DemandedMask & (~RHSKnownZero)))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
878 (DemandedMask & (~LHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(1));
880
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask))
883 return UpdateValueUsesWith(I, I);
884
885 // Output known-0 bits are only known if clear in both the LHS & RHS.
886 RHSKnownZero &= LHSKnownZero;
887 // Output known-1 are known to be set if set in either the LHS | RHS.
888 RHSKnownOne |= LHSKnownOne;
889 break;
890 case Instruction::Xor: {
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 RHSKnownZero, RHSKnownOne, Depth+1))
893 return true;
894 assert((RHSKnownZero & RHSKnownOne) == 0 &&
895 "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
897 LHSKnownZero, LHSKnownOne, Depth+1))
898 return true;
899 assert((LHSKnownZero & LHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901
902 // If all of the demanded bits are known zero on one side, return the other.
903 // These bits cannot contribute to the result of the 'xor'.
904 if ((DemandedMask & RHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(0));
906 if ((DemandedMask & LHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(1));
908
909 // Output known-0 bits are known if clear or set in both the LHS & RHS.
910 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
911 (RHSKnownOne & LHSKnownOne);
912 // Output known-1 are known to be set if set in only one of the LHS, RHS.
913 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
914 (RHSKnownOne & LHSKnownZero);
915
916 // If all of the demanded bits are known to be zero on one side or the
917 // other, turn this into an *inclusive* or.
918 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000921 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 I->getName());
923 InsertNewInstBefore(Or, *I);
924 return UpdateValueUsesWith(I, Or);
925 }
926
927 // If all of the demanded bits on one side are known, and all of the set
928 // bits on that side are also known to be set on the other side, turn this
929 // into an AND, as we know the bits will be cleared.
930 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
932 // all known
933 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000936 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 InsertNewInstBefore(And, *I);
938 return UpdateValueUsesWith(I, And);
939 }
940 }
941
942 // If the RHS is a constant, see if we can simplify it.
943 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
946
947 RHSKnownZero = KnownZeroOut;
948 RHSKnownOne = KnownOneOut;
949 break;
950 }
951 case Instruction::Select:
952 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
954 return true;
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 LHSKnownZero, LHSKnownOne, Depth+1))
957 return true;
958 assert((RHSKnownZero & RHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962
963 // If the operands are constants, see if we can simplify them.
964 if (ShrinkDemandedConstant(I, 1, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966 if (ShrinkDemandedConstant(I, 2, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968
969 // Only known if known in both the LHS and RHS.
970 RHSKnownOne &= LHSKnownOne;
971 RHSKnownZero &= LHSKnownZero;
972 break;
973 case Instruction::Trunc: {
974 uint32_t truncBf =
975 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976 DemandedMask.zext(truncBf);
977 RHSKnownZero.zext(truncBf);
978 RHSKnownOne.zext(truncBf);
979 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1))
981 return true;
982 DemandedMask.trunc(BitWidth);
983 RHSKnownZero.trunc(BitWidth);
984 RHSKnownOne.trunc(BitWidth);
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
987 break;
988 }
989 case Instruction::BitCast:
990 if (!I->getOperand(0)->getType()->isInteger())
991 return false;
992
993 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1))
995 return true;
996 assert((RHSKnownZero & RHSKnownOne) == 0 &&
997 "Bits known to be one AND zero?");
998 break;
999 case Instruction::ZExt: {
1000 // Compute the bits in the result that are not present in the input.
1001 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003
1004 DemandedMask.trunc(SrcBitWidth);
1005 RHSKnownZero.trunc(SrcBitWidth);
1006 RHSKnownOne.trunc(SrcBitWidth);
1007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1))
1009 return true;
1010 DemandedMask.zext(BitWidth);
1011 RHSKnownZero.zext(BitWidth);
1012 RHSKnownOne.zext(BitWidth);
1013 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1014 "Bits known to be one AND zero?");
1015 // The top bits are known to be zero.
1016 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017 break;
1018 }
1019 case Instruction::SExt: {
1020 // Compute the bits in the result that are not present in the input.
1021 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023
1024 APInt InputDemandedBits = DemandedMask &
1025 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028 // If any of the sign extended bits are demanded, we know that the sign
1029 // bit is demanded.
1030 if ((NewBits & DemandedMask) != 0)
1031 InputDemandedBits.set(SrcBitWidth-1);
1032
1033 InputDemandedBits.trunc(SrcBitWidth);
1034 RHSKnownZero.trunc(SrcBitWidth);
1035 RHSKnownOne.trunc(SrcBitWidth);
1036 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037 RHSKnownZero, RHSKnownOne, Depth+1))
1038 return true;
1039 InputDemandedBits.zext(BitWidth);
1040 RHSKnownZero.zext(BitWidth);
1041 RHSKnownOne.zext(BitWidth);
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044
1045 // If the sign bit of the input is known set or clear, then we know the
1046 // top bits of the result.
1047
1048 // If the input sign bit is known zero, or if the NewBits are not demanded
1049 // convert this into a zero extension.
1050 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051 {
1052 // Convert to ZExt cast
1053 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054 return UpdateValueUsesWith(I, NewCast);
1055 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1056 RHSKnownOne |= NewBits;
1057 }
1058 break;
1059 }
1060 case Instruction::Add: {
1061 // Figure out what the input bits are. If the top bits of the and result
1062 // are not demanded, then the add doesn't demand them from its input
1063 // either.
1064 uint32_t NLZ = DemandedMask.countLeadingZeros();
1065
1066 // If there is a constant on the RHS, there are a variety of xformations
1067 // we can do.
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069 // If null, this should be simplified elsewhere. Some of the xforms here
1070 // won't work if the RHS is zero.
1071 if (RHS->isZero())
1072 break;
1073
1074 // If the top bit of the output is demanded, demand everything from the
1075 // input. Otherwise, we demand all the input bits except NLZ top bits.
1076 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078 // Find information about known zero/one bits in the input.
1079 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1080 LHSKnownZero, LHSKnownOne, Depth+1))
1081 return true;
1082
1083 // If the RHS of the add has bits set that can't affect the input, reduce
1084 // the constant.
1085 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086 return UpdateValueUsesWith(I, I);
1087
1088 // Avoid excess work.
1089 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090 break;
1091
1092 // Turn it into OR if input bits are zero.
1093 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001095 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 I->getName());
1097 InsertNewInstBefore(Or, *I);
1098 return UpdateValueUsesWith(I, Or);
1099 }
1100
1101 // We can say something about the output known-zero and known-one bits,
1102 // depending on potential carries from the input constant and the
1103 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1104 // bits set and the RHS constant is 0x01001, then we know we have a known
1105 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106
1107 // To compute this, we first compute the potential carry bits. These are
1108 // the bits which may be modified. I'm not aware of a better way to do
1109 // this scan.
1110 const APInt& RHSVal = RHS->getValue();
1111 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112
1113 // Now that we know which bits have carries, compute the known-1/0 sets.
1114
1115 // Bits are known one if they are known zero in one operand and one in the
1116 // other, and there is no input carry.
1117 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1118 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119
1120 // Bits are known zero if they are known zero in both operands and there
1121 // is no input carry.
1122 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123 } else {
1124 // If the high-bits of this ADD are not demanded, then it does not demand
1125 // the high bits of its LHS or RHS.
1126 if (DemandedMask[BitWidth-1] == 0) {
1127 // Right fill the mask of bits for this ADD to demand the most
1128 // significant bit and all those below it.
1129 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131 LHSKnownZero, LHSKnownOne, Depth+1))
1132 return true;
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1135 return true;
1136 }
1137 }
1138 break;
1139 }
1140 case Instruction::Sub:
1141 // If the high-bits of this SUB are not demanded, then it does not demand
1142 // the high bits of its LHS or RHS.
1143 if (DemandedMask[BitWidth-1] == 0) {
1144 // Right fill the mask of bits for this SUB to demand the most
1145 // significant bit and all those below it.
1146 uint32_t NLZ = DemandedMask.countLeadingZeros();
1147 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1150 return true;
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1153 return true;
1154 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1164 RHSKnownZero, RHSKnownOne, Depth+1))
1165 return true;
1166 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1167 "Bits known to be one AND zero?");
1168 RHSKnownZero <<= ShiftAmt;
1169 RHSKnownOne <<= ShiftAmt;
1170 // low bits known zero.
1171 if (ShiftAmt)
1172 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173 }
1174 break;
1175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179
1180 // Unsigned shift right.
1181 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183 RHSKnownZero, RHSKnownOne, Depth+1))
1184 return true;
1185 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1186 "Bits known to be one AND zero?");
1187 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189 if (ShiftAmt) {
1190 // Compute the new bits that are at the top now.
1191 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192 RHSKnownZero |= HighBits; // high bits known zero.
1193 }
1194 }
1195 break;
1196 case Instruction::AShr:
1197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
1201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001203 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 I->getOperand(0), I->getOperand(1), I->getName());
1205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206 return UpdateValueUsesWith(I, NewVal);
1207 }
1208
1209 // If the sign bit is the only bit demanded by this ashr, then there is no
1210 // need to do it, the shift doesn't change the high bit.
1211 if (DemandedMask.isSignBit())
1212 return UpdateValueUsesWith(I, I->getOperand(0));
1213
1214 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216
1217 // Signed shift right.
1218 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219 // If any of the "high bits" are demanded, we should set the sign bit as
1220 // demanded.
1221 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222 DemandedMaskIn.set(BitWidth-1);
1223 if (SimplifyDemandedBits(I->getOperand(0),
1224 DemandedMaskIn,
1225 RHSKnownZero, RHSKnownOne, Depth+1))
1226 return true;
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // Compute the new bits that are at the top now.
1230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233
1234 // Handle the sign bits.
1235 APInt SignBit(APInt::getSignBit(BitWidth));
1236 // Adjust to where it is now in the mask.
1237 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1238
1239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001241 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 (HighBits & ~DemandedMask) == HighBits) {
1243 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001244 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 I->getOperand(0), SA, I->getName());
1246 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247 return UpdateValueUsesWith(I, NewVal);
1248 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249 RHSKnownOne |= HighBits;
1250 }
1251 }
1252 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001253 case Instruction::SRem:
1254 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 APInt RA = Rem->getValue();
1256 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001257 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001258 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260 LHSKnownZero, LHSKnownOne, Depth+1))
1261 return true;
1262
1263 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264 LHSKnownZero |= ~LowBits;
1265 else if (LHSKnownOne[BitWidth-1])
1266 LHSKnownOne |= ~LowBits;
1267
1268 KnownZero |= LHSKnownZero & DemandedMask;
1269 KnownOne |= LHSKnownOne & DemandedMask;
1270
1271 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1272 }
1273 }
1274 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001275 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001276 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001278 if (RA.isPowerOf2()) {
1279 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001280 APInt Mask2 = LowBits & DemandedMask;
1281 KnownZero |= ~LowBits & DemandedMask;
1282 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283 KnownZero, KnownOne, Depth+1))
1284 return true;
1285
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001287 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001288 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001289 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001290
1291 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001293 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294 KnownZero2, KnownOne2, Depth+1))
1295 return true;
1296
Dan Gohmanbec16052008-04-28 17:02:21 +00001297 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001298 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001299 KnownZero2, KnownOne2, Depth+1))
1300 return true;
1301
1302 Leaders = std::max(Leaders,
1303 KnownZero2.countLeadingOnes());
1304 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001305 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 }
Chris Lattner989ba312008-06-18 04:33:20 +00001307 case Instruction::Call:
1308 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309 switch (II->getIntrinsicID()) {
1310 default: break;
1311 case Intrinsic::bswap: {
1312 // If the only bits demanded come from one byte of the bswap result,
1313 // just shift the input byte into position to eliminate the bswap.
1314 unsigned NLZ = DemandedMask.countLeadingZeros();
1315 unsigned NTZ = DemandedMask.countTrailingZeros();
1316
1317 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1318 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1319 // have 14 leading zeros, round to 8.
1320 NLZ &= ~7;
1321 NTZ &= ~7;
1322 // If we need exactly one byte, we can do this transformation.
1323 if (BitWidth-NLZ-NTZ == 8) {
1324 unsigned ResultBit = NTZ;
1325 unsigned InputBit = BitWidth-NTZ-8;
1326
1327 // Replace this with either a left or right shift to get the byte into
1328 // the right place.
1329 Instruction *NewVal;
1330 if (InputBit > ResultBit)
1331 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332 ConstantInt::get(I->getType(), InputBit-ResultBit));
1333 else
1334 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335 ConstantInt::get(I->getType(), ResultBit-InputBit));
1336 NewVal->takeName(I);
1337 InsertNewInstBefore(NewVal, *I);
1338 return UpdateValueUsesWith(I, NewVal);
1339 }
1340
1341 // TODO: Could compute known zero/one bits based on the input.
1342 break;
1343 }
1344 }
1345 }
Chris Lattner4946e222008-06-18 18:11:55 +00001346 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001347 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001348 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 // If the client is only demanding bits that we know, return the known
1351 // constant.
1352 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1353 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1354 return false;
1355}
1356
1357
1358/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1359/// 64 or fewer elements. DemandedElts contains the set of elements that are
1360/// actually used by the caller. This method analyzes which elements of the
1361/// operand are undef and returns that information in UndefElts.
1362///
1363/// If the information about demanded elements can be used to simplify the
1364/// operation, the operation is simplified, then the resultant value is
1365/// returned. This returns null if no change was made.
1366Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1367 uint64_t &UndefElts,
1368 unsigned Depth) {
1369 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1370 assert(VWidth <= 64 && "Vector too wide to analyze!");
1371 uint64_t EltMask = ~0ULL >> (64-VWidth);
1372 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1373 "Invalid DemandedElts!");
1374
1375 if (isa<UndefValue>(V)) {
1376 // If the entire vector is undefined, just return this info.
1377 UndefElts = EltMask;
1378 return 0;
1379 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1380 UndefElts = EltMask;
1381 return UndefValue::get(V->getType());
1382 }
1383
1384 UndefElts = 0;
1385 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1386 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1387 Constant *Undef = UndefValue::get(EltTy);
1388
1389 std::vector<Constant*> Elts;
1390 for (unsigned i = 0; i != VWidth; ++i)
1391 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1392 Elts.push_back(Undef);
1393 UndefElts |= (1ULL << i);
1394 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1395 Elts.push_back(Undef);
1396 UndefElts |= (1ULL << i);
1397 } else { // Otherwise, defined.
1398 Elts.push_back(CP->getOperand(i));
1399 }
1400
1401 // If we changed the constant, return it.
1402 Constant *NewCP = ConstantVector::get(Elts);
1403 return NewCP != CP ? NewCP : 0;
1404 } else if (isa<ConstantAggregateZero>(V)) {
1405 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1406 // set to undef.
1407 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1408 Constant *Zero = Constant::getNullValue(EltTy);
1409 Constant *Undef = UndefValue::get(EltTy);
1410 std::vector<Constant*> Elts;
1411 for (unsigned i = 0; i != VWidth; ++i)
1412 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1413 UndefElts = DemandedElts ^ EltMask;
1414 return ConstantVector::get(Elts);
1415 }
1416
1417 if (!V->hasOneUse()) { // Other users may use these bits.
1418 if (Depth != 0) { // Not at the root.
1419 // TODO: Just compute the UndefElts information recursively.
1420 return false;
1421 }
1422 return false;
1423 } else if (Depth == 10) { // Limit search depth.
1424 return false;
1425 }
1426
1427 Instruction *I = dyn_cast<Instruction>(V);
1428 if (!I) return false; // Only analyze instructions.
1429
1430 bool MadeChange = false;
1431 uint64_t UndefElts2;
1432 Value *TmpV;
1433 switch (I->getOpcode()) {
1434 default: break;
1435
1436 case Instruction::InsertElement: {
1437 // If this is a variable index, we don't know which element it overwrites.
1438 // demand exactly the same input as we produce.
1439 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1440 if (Idx == 0) {
1441 // Note that we can't propagate undef elt info, because we don't know
1442 // which elt is getting updated.
1443 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1444 UndefElts2, Depth+1);
1445 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1446 break;
1447 }
1448
1449 // If this is inserting an element that isn't demanded, remove this
1450 // insertelement.
1451 unsigned IdxNo = Idx->getZExtValue();
1452 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1453 return AddSoonDeadInstToWorklist(*I, 0);
1454
1455 // Otherwise, the element inserted overwrites whatever was there, so the
1456 // input demanded set is simpler than the output set.
1457 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1458 DemandedElts & ~(1ULL << IdxNo),
1459 UndefElts, Depth+1);
1460 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1461
1462 // The inserted element is defined.
1463 UndefElts |= 1ULL << IdxNo;
1464 break;
1465 }
1466 case Instruction::BitCast: {
1467 // Vector->vector casts only.
1468 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1469 if (!VTy) break;
1470 unsigned InVWidth = VTy->getNumElements();
1471 uint64_t InputDemandedElts = 0;
1472 unsigned Ratio;
1473
1474 if (VWidth == InVWidth) {
1475 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1476 // elements as are demanded of us.
1477 Ratio = 1;
1478 InputDemandedElts = DemandedElts;
1479 } else if (VWidth > InVWidth) {
1480 // Untested so far.
1481 break;
1482
1483 // If there are more elements in the result than there are in the source,
1484 // then an input element is live if any of the corresponding output
1485 // elements are live.
1486 Ratio = VWidth/InVWidth;
1487 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1488 if (DemandedElts & (1ULL << OutIdx))
1489 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1490 }
1491 } else {
1492 // Untested so far.
1493 break;
1494
1495 // If there are more elements in the source than there are in the result,
1496 // then an input element is live if the corresponding output element is
1497 // live.
1498 Ratio = InVWidth/VWidth;
1499 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1500 if (DemandedElts & (1ULL << InIdx/Ratio))
1501 InputDemandedElts |= 1ULL << InIdx;
1502 }
1503
1504 // div/rem demand all inputs, because they don't want divide by zero.
1505 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1506 UndefElts2, Depth+1);
1507 if (TmpV) {
1508 I->setOperand(0, TmpV);
1509 MadeChange = true;
1510 }
1511
1512 UndefElts = UndefElts2;
1513 if (VWidth > InVWidth) {
1514 assert(0 && "Unimp");
1515 // If there are more elements in the result than there are in the source,
1516 // then an output element is undef if the corresponding input element is
1517 // undef.
1518 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1519 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1520 UndefElts |= 1ULL << OutIdx;
1521 } else if (VWidth < InVWidth) {
1522 assert(0 && "Unimp");
1523 // If there are more elements in the source than there are in the result,
1524 // then a result element is undef if all of the corresponding input
1525 // elements are undef.
1526 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1527 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1529 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1530 }
1531 break;
1532 }
1533 case Instruction::And:
1534 case Instruction::Or:
1535 case Instruction::Xor:
1536 case Instruction::Add:
1537 case Instruction::Sub:
1538 case Instruction::Mul:
1539 // div/rem demand all inputs, because they don't want divide by zero.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541 UndefElts, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1544 UndefElts2, Depth+1);
1545 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1546
1547 // Output elements are undefined if both are undefined. Consider things
1548 // like undef&0. The result is known zero, not undef.
1549 UndefElts &= UndefElts2;
1550 break;
1551
1552 case Instruction::Call: {
1553 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1554 if (!II) break;
1555 switch (II->getIntrinsicID()) {
1556 default: break;
1557
1558 // Binary vector operations that work column-wise. A dest element is a
1559 // function of the corresponding input elements from the two inputs.
1560 case Intrinsic::x86_sse_sub_ss:
1561 case Intrinsic::x86_sse_mul_ss:
1562 case Intrinsic::x86_sse_min_ss:
1563 case Intrinsic::x86_sse_max_ss:
1564 case Intrinsic::x86_sse2_sub_sd:
1565 case Intrinsic::x86_sse2_mul_sd:
1566 case Intrinsic::x86_sse2_min_sd:
1567 case Intrinsic::x86_sse2_max_sd:
1568 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1569 UndefElts, Depth+1);
1570 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1571 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1572 UndefElts2, Depth+1);
1573 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1574
1575 // If only the low elt is demanded and this is a scalarizable intrinsic,
1576 // scalarize it now.
1577 if (DemandedElts == 1) {
1578 switch (II->getIntrinsicID()) {
1579 default: break;
1580 case Intrinsic::x86_sse_sub_ss:
1581 case Intrinsic::x86_sse_mul_ss:
1582 case Intrinsic::x86_sse2_sub_sd:
1583 case Intrinsic::x86_sse2_mul_sd:
1584 // TODO: Lower MIN/MAX/ABS/etc
1585 Value *LHS = II->getOperand(1);
1586 Value *RHS = II->getOperand(2);
1587 // Extract the element as scalars.
1588 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1589 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1590
1591 switch (II->getIntrinsicID()) {
1592 default: assert(0 && "Case stmts out of sync!");
1593 case Intrinsic::x86_sse_sub_ss:
1594 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001595 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 II->getName()), *II);
1597 break;
1598 case Intrinsic::x86_sse_mul_ss:
1599 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001600 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601 II->getName()), *II);
1602 break;
1603 }
1604
1605 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001606 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1607 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 InsertNewInstBefore(New, *II);
1609 AddSoonDeadInstToWorklist(*II, 0);
1610 return New;
1611 }
1612 }
1613
1614 // Output elements are undefined if both are undefined. Consider things
1615 // like undef&0. The result is known zero, not undef.
1616 UndefElts &= UndefElts2;
1617 break;
1618 }
1619 break;
1620 }
1621 }
1622 return MadeChange ? I : 0;
1623}
1624
Dan Gohman5d56fd42008-05-19 22:14:15 +00001625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626/// AssociativeOpt - Perform an optimization on an associative operator. This
1627/// function is designed to check a chain of associative operators for a
1628/// potential to apply a certain optimization. Since the optimization may be
1629/// applicable if the expression was reassociated, this checks the chain, then
1630/// reassociates the expression as necessary to expose the optimization
1631/// opportunity. This makes use of a special Functor, which must define
1632/// 'shouldApply' and 'apply' methods.
1633///
1634template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001635static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 unsigned Opcode = Root.getOpcode();
1637 Value *LHS = Root.getOperand(0);
1638
1639 // Quick check, see if the immediate LHS matches...
1640 if (F.shouldApply(LHS))
1641 return F.apply(Root);
1642
1643 // Otherwise, if the LHS is not of the same opcode as the root, return.
1644 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1645 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1646 // Should we apply this transform to the RHS?
1647 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1648
1649 // If not to the RHS, check to see if we should apply to the LHS...
1650 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1651 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1652 ShouldApply = true;
1653 }
1654
1655 // If the functor wants to apply the optimization to the RHS of LHSI,
1656 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1657 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 // Now all of the instructions are in the current basic block, go ahead
1659 // and perform the reassociation.
1660 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1661
1662 // First move the selected RHS to the LHS of the root...
1663 Root.setOperand(0, LHSI->getOperand(1));
1664
1665 // Make what used to be the LHS of the root be the user of the root...
1666 Value *ExtraOperand = TmpLHSI->getOperand(1);
1667 if (&Root == TmpLHSI) {
1668 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1669 return 0;
1670 }
1671 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1672 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001674 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 ARI = Root;
1676
1677 // Now propagate the ExtraOperand down the chain of instructions until we
1678 // get to LHSI.
1679 while (TmpLHSI != LHSI) {
1680 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1681 // Move the instruction to immediately before the chain we are
1682 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001683 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684 ARI = NextLHSI;
1685
1686 Value *NextOp = NextLHSI->getOperand(1);
1687 NextLHSI->setOperand(1, ExtraOperand);
1688 TmpLHSI = NextLHSI;
1689 ExtraOperand = NextOp;
1690 }
1691
1692 // Now that the instructions are reassociated, have the functor perform
1693 // the transformation...
1694 return F.apply(Root);
1695 }
1696
1697 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1698 }
1699 return 0;
1700}
1701
Dan Gohman089efff2008-05-13 00:00:25 +00001702namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703
Nick Lewycky27f6c132008-05-23 04:34:58 +00001704// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705struct AddRHS {
1706 Value *RHS;
1707 AddRHS(Value *rhs) : RHS(rhs) {}
1708 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1709 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001710 return BinaryOperator::CreateShl(Add.getOperand(0),
1711 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 }
1713};
1714
1715// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1716// iff C1&C2 == 0
1717struct AddMaskingAnd {
1718 Constant *C2;
1719 AddMaskingAnd(Constant *c) : C2(c) {}
1720 bool shouldApply(Value *LHS) const {
1721 ConstantInt *C1;
1722 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1723 ConstantExpr::getAnd(C1, C2)->isNullValue();
1724 }
1725 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001726 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 }
1728};
1729
Dan Gohman089efff2008-05-13 00:00:25 +00001730}
1731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1733 InstCombiner *IC) {
1734 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1735 if (Constant *SOC = dyn_cast<Constant>(SO))
1736 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1737
Gabor Greifa645dd32008-05-16 19:29:10 +00001738 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1740 }
1741
1742 // Figure out if the constant is the left or the right argument.
1743 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1744 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1745
1746 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1747 if (ConstIsRHS)
1748 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1749 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1750 }
1751
1752 Value *Op0 = SO, *Op1 = ConstOperand;
1753 if (!ConstIsRHS)
1754 std::swap(Op0, Op1);
1755 Instruction *New;
1756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001757 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001759 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 SO->getName()+".cmp");
1761 else {
1762 assert(0 && "Unknown binary instruction type!");
1763 abort();
1764 }
1765 return IC->InsertNewInstBefore(New, I);
1766}
1767
1768// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1769// constant as the other operand, try to fold the binary operator into the
1770// select arguments. This also works for Cast instructions, which obviously do
1771// not have a second operand.
1772static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1773 InstCombiner *IC) {
1774 // Don't modify shared select instructions
1775 if (!SI->hasOneUse()) return 0;
1776 Value *TV = SI->getOperand(1);
1777 Value *FV = SI->getOperand(2);
1778
1779 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1780 // Bool selects with constant operands can be folded to logical ops.
1781 if (SI->getType() == Type::Int1Ty) return 0;
1782
1783 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1784 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1785
Gabor Greifd6da1d02008-04-06 20:25:17 +00001786 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1787 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001788 }
1789 return 0;
1790}
1791
1792
1793/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1794/// node as operand #0, see if we can fold the instruction into the PHI (which
1795/// is only possible if all operands to the PHI are constants).
1796Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1797 PHINode *PN = cast<PHINode>(I.getOperand(0));
1798 unsigned NumPHIValues = PN->getNumIncomingValues();
1799 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1800
1801 // Check to see if all of the operands of the PHI are constants. If there is
1802 // one non-constant value, remember the BB it is. If there is more than one
1803 // or if *it* is a PHI, bail out.
1804 BasicBlock *NonConstBB = 0;
1805 for (unsigned i = 0; i != NumPHIValues; ++i)
1806 if (!isa<Constant>(PN->getIncomingValue(i))) {
1807 if (NonConstBB) return 0; // More than one non-const value.
1808 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1809 NonConstBB = PN->getIncomingBlock(i);
1810
1811 // If the incoming non-constant value is in I's block, we have an infinite
1812 // loop.
1813 if (NonConstBB == I.getParent())
1814 return 0;
1815 }
1816
1817 // If there is exactly one non-constant value, we can insert a copy of the
1818 // operation in that block. However, if this is a critical edge, we would be
1819 // inserting the computation one some other paths (e.g. inside a loop). Only
1820 // do this if the pred block is unconditionally branching into the phi block.
1821 if (NonConstBB) {
1822 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1823 if (!BI || !BI->isUnconditional()) return 0;
1824 }
1825
1826 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001827 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1829 InsertNewInstBefore(NewPN, *PN);
1830 NewPN->takeName(PN);
1831
1832 // Next, add all of the operands to the PHI.
1833 if (I.getNumOperands() == 2) {
1834 Constant *C = cast<Constant>(I.getOperand(1));
1835 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001836 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1838 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1839 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1840 else
1841 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1842 } else {
1843 assert(PN->getIncomingBlock(i) == NonConstBB);
1844 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001845 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 PN->getIncomingValue(i), C, "phitmp",
1847 NonConstBB->getTerminator());
1848 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001849 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850 CI->getPredicate(),
1851 PN->getIncomingValue(i), C, "phitmp",
1852 NonConstBB->getTerminator());
1853 else
1854 assert(0 && "Unknown binop!");
1855
1856 AddToWorkList(cast<Instruction>(InV));
1857 }
1858 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1859 }
1860 } else {
1861 CastInst *CI = cast<CastInst>(&I);
1862 const Type *RetTy = CI->getType();
1863 for (unsigned i = 0; i != NumPHIValues; ++i) {
1864 Value *InV;
1865 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1866 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1867 } else {
1868 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001869 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 I.getType(), "phitmp",
1871 NonConstBB->getTerminator());
1872 AddToWorkList(cast<Instruction>(InV));
1873 }
1874 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1875 }
1876 }
1877 return ReplaceInstUsesWith(I, NewPN);
1878}
1879
Chris Lattner55476162008-01-29 06:52:45 +00001880
Chris Lattner3554f972008-05-20 05:46:13 +00001881/// WillNotOverflowSignedAdd - Return true if we can prove that:
1882/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1883/// This basically requires proving that the add in the original type would not
1884/// overflow to change the sign bit or have a carry out.
1885bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1886 // There are different heuristics we can use for this. Here are some simple
1887 // ones.
1888
1889 // Add has the property that adding any two 2's complement numbers can only
1890 // have one carry bit which can change a sign. As such, if LHS and RHS each
1891 // have at least two sign bits, we know that the addition of the two values will
1892 // sign extend fine.
1893 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1894 return true;
1895
1896
1897 // If one of the operands only has one non-zero bit, and if the other operand
1898 // has a known-zero bit in a more significant place than it (not including the
1899 // sign bit) the ripple may go up to and fill the zero, but won't change the
1900 // sign. For example, (X & ~4) + 1.
1901
1902 // TODO: Implement.
1903
1904 return false;
1905}
1906
Chris Lattner55476162008-01-29 06:52:45 +00001907
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001908Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1909 bool Changed = SimplifyCommutative(I);
1910 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1911
1912 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1913 // X + undef -> undef
1914 if (isa<UndefValue>(RHS))
1915 return ReplaceInstUsesWith(I, RHS);
1916
1917 // X + 0 --> X
1918 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1919 if (RHSC->isNullValue())
1920 return ReplaceInstUsesWith(I, LHS);
1921 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001922 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1923 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924 return ReplaceInstUsesWith(I, LHS);
1925 }
1926
1927 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1928 // X + (signbit) --> X ^ signbit
1929 const APInt& Val = CI->getValue();
1930 uint32_t BitWidth = Val.getBitWidth();
1931 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001932 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001933
1934 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1935 // (X & 254)+1 -> (X&254)|1
1936 if (!isa<VectorType>(I.getType())) {
1937 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1938 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1939 KnownZero, KnownOne))
1940 return &I;
1941 }
1942 }
1943
1944 if (isa<PHINode>(LHS))
1945 if (Instruction *NV = FoldOpIntoPhi(I))
1946 return NV;
1947
1948 ConstantInt *XorRHS = 0;
1949 Value *XorLHS = 0;
1950 if (isa<ConstantInt>(RHSC) &&
1951 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1952 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1953 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1954
1955 uint32_t Size = TySizeBits / 2;
1956 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1957 APInt CFF80Val(-C0080Val);
1958 do {
1959 if (TySizeBits > Size) {
1960 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1961 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1962 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1963 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1964 // This is a sign extend if the top bits are known zero.
1965 if (!MaskedValueIsZero(XorLHS,
1966 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1967 Size = 0; // Not a sign ext, but can't be any others either.
1968 break;
1969 }
1970 }
1971 Size >>= 1;
1972 C0080Val = APIntOps::lshr(C0080Val, Size);
1973 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1974 } while (Size >= 1);
1975
1976 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00001977 // with funny bit widths then this switch statement should be removed. It
1978 // is just here to get the size of the "middle" type back up to something
1979 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 const Type *MiddleType = 0;
1981 switch (Size) {
1982 default: break;
1983 case 32: MiddleType = Type::Int32Ty; break;
1984 case 16: MiddleType = Type::Int16Ty; break;
1985 case 8: MiddleType = Type::Int8Ty; break;
1986 }
1987 if (MiddleType) {
1988 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1989 InsertNewInstBefore(NewTrunc, I);
1990 return new SExtInst(NewTrunc, I.getType(), I.getName());
1991 }
1992 }
1993 }
1994
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001995 if (I.getType() == Type::Int1Ty)
1996 return BinaryOperator::CreateXor(LHS, RHS);
1997
Nick Lewycky4d474cd2008-05-23 04:39:38 +00001998 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001999 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002000 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2001
2002 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2003 if (RHSI->getOpcode() == Instruction::Sub)
2004 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2005 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2006 }
2007 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2008 if (LHSI->getOpcode() == Instruction::Sub)
2009 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2010 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2011 }
2012 }
2013
2014 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002015 // -A + -B --> -(A + B)
2016 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002017 if (LHS->getType()->isIntOrIntVector()) {
2018 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002019 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002020 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002021 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002022 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002023 }
2024
Gabor Greifa645dd32008-05-16 19:29:10 +00002025 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002026 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027
2028 // A + -B --> A - B
2029 if (!isa<Constant>(RHS))
2030 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002031 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032
2033
2034 ConstantInt *C2;
2035 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2036 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002037 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038
2039 // X*C1 + X*C2 --> X * (C1+C2)
2040 ConstantInt *C1;
2041 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002042 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 }
2044
2045 // X + X*C --> X * (C+1)
2046 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002047 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048
2049 // X + ~X --> -1 since ~X = -X-1
2050 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2051 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2052
2053
2054 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2055 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2056 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2057 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002058
2059 // A+B --> A|B iff A and B have no bits set in common.
2060 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2061 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2062 APInt LHSKnownOne(IT->getBitWidth(), 0);
2063 APInt LHSKnownZero(IT->getBitWidth(), 0);
2064 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2065 if (LHSKnownZero != 0) {
2066 APInt RHSKnownOne(IT->getBitWidth(), 0);
2067 APInt RHSKnownZero(IT->getBitWidth(), 0);
2068 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2069
2070 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002071 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002072 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002073 }
2074 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002075
Nick Lewycky83598a72008-02-03 07:42:09 +00002076 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002077 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002078 Value *W, *X, *Y, *Z;
2079 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2080 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2081 if (W != Y) {
2082 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002083 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002084 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002085 std::swap(W, X);
2086 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002087 std::swap(Y, Z);
2088 std::swap(W, X);
2089 }
2090 }
2091
2092 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002093 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002094 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002095 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002096 }
2097 }
2098 }
2099
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2101 Value *X = 0;
2102 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002103 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104
2105 // (X & FF00) + xx00 -> (X+xx00) & FF00
2106 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2107 Constant *Anded = And(CRHS, C2);
2108 if (Anded == CRHS) {
2109 // See if all bits from the first bit set in the Add RHS up are included
2110 // in the mask. First, get the rightmost bit.
2111 const APInt& AddRHSV = CRHS->getValue();
2112
2113 // Form a mask of all bits from the lowest bit added through the top.
2114 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2115
2116 // See if the and mask includes all of these bits.
2117 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2118
2119 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2120 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002121 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002123 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124 }
2125 }
2126 }
2127
2128 // Try to fold constant add into select arguments.
2129 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2130 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2131 return R;
2132 }
2133
2134 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002135 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002136 {
2137 CastInst *CI = dyn_cast<CastInst>(LHS);
2138 Value *Other = RHS;
2139 if (!CI) {
2140 CI = dyn_cast<CastInst>(RHS);
2141 Other = LHS;
2142 }
2143 if (CI && CI->getType()->isSized() &&
2144 (CI->getType()->getPrimitiveSizeInBits() ==
2145 TD->getIntPtrType()->getPrimitiveSizeInBits())
2146 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002147 unsigned AS =
2148 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002149 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2150 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002151 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 return new PtrToIntInst(I2, CI->getType());
2153 }
2154 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002155
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002156 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002157 {
2158 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2159 Value *Other = RHS;
2160 if (!SI) {
2161 SI = dyn_cast<SelectInst>(RHS);
2162 Other = LHS;
2163 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002164 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002165 Value *TV = SI->getTrueValue();
2166 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002167 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002168
2169 // Can we fold the add into the argument of the select?
2170 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002171 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2172 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002173 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002174 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2175 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002176 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002177 }
2178 }
Chris Lattner55476162008-01-29 06:52:45 +00002179
2180 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2181 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2182 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2183 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184
Chris Lattner3554f972008-05-20 05:46:13 +00002185 // Check for (add (sext x), y), see if we can merge this into an
2186 // integer add followed by a sext.
2187 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2188 // (add (sext x), cst) --> (sext (add x, cst'))
2189 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2190 Constant *CI =
2191 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2192 if (LHSConv->hasOneUse() &&
2193 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2194 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2195 // Insert the new, smaller add.
2196 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2197 CI, "addconv");
2198 InsertNewInstBefore(NewAdd, I);
2199 return new SExtInst(NewAdd, I.getType());
2200 }
2201 }
2202
2203 // (add (sext x), (sext y)) --> (sext (add int x, y))
2204 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2205 // Only do this if x/y have the same type, if at last one of them has a
2206 // single use (so we don't increase the number of sexts), and if the
2207 // integer add will not overflow.
2208 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2209 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2210 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2211 RHSConv->getOperand(0))) {
2212 // Insert the new integer add.
2213 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2214 RHSConv->getOperand(0),
2215 "addconv");
2216 InsertNewInstBefore(NewAdd, I);
2217 return new SExtInst(NewAdd, I.getType());
2218 }
2219 }
2220 }
2221
2222 // Check for (add double (sitofp x), y), see if we can merge this into an
2223 // integer add followed by a promotion.
2224 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2225 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2226 // ... if the constant fits in the integer value. This is useful for things
2227 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2228 // requires a constant pool load, and generally allows the add to be better
2229 // instcombined.
2230 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2231 Constant *CI =
2232 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2233 if (LHSConv->hasOneUse() &&
2234 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2235 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2236 // Insert the new integer add.
2237 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2238 CI, "addconv");
2239 InsertNewInstBefore(NewAdd, I);
2240 return new SIToFPInst(NewAdd, I.getType());
2241 }
2242 }
2243
2244 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2245 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2246 // Only do this if x/y have the same type, if at last one of them has a
2247 // single use (so we don't increase the number of int->fp conversions),
2248 // and if the integer add will not overflow.
2249 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2250 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2251 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2252 RHSConv->getOperand(0))) {
2253 // Insert the new integer add.
2254 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2255 RHSConv->getOperand(0),
2256 "addconv");
2257 InsertNewInstBefore(NewAdd, I);
2258 return new SIToFPInst(NewAdd, I.getType());
2259 }
2260 }
2261 }
2262
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 return Changed ? &I : 0;
2264}
2265
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002266Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2268
2269 if (Op0 == Op1) // sub X, X -> 0
2270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2271
2272 // If this is a 'B = x-(-A)', change to B = x+A...
2273 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002274 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002275
2276 if (isa<UndefValue>(Op0))
2277 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2278 if (isa<UndefValue>(Op1))
2279 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2280
2281 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2282 // Replace (-1 - A) with (~A)...
2283 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002284 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285
2286 // C - ~X == X + (1+C)
2287 Value *X = 0;
2288 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002289 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290
2291 // -(X >>u 31) -> (X >>s 31)
2292 // -(X >>s 31) -> (X >>u 31)
2293 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002294 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 if (SI->getOpcode() == Instruction::LShr) {
2296 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2297 // Check to see if we are shifting out everything but the sign bit.
2298 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2299 SI->getType()->getPrimitiveSizeInBits()-1) {
2300 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002301 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 SI->getOperand(0), CU, SI->getName());
2303 }
2304 }
2305 }
2306 else if (SI->getOpcode() == Instruction::AShr) {
2307 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2308 // Check to see if we are shifting out everything but the sign bit.
2309 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2310 SI->getType()->getPrimitiveSizeInBits()-1) {
2311 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002312 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 SI->getOperand(0), CU, SI->getName());
2314 }
2315 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002316 }
2317 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318 }
2319
2320 // Try to fold constant sub into select arguments.
2321 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2322 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2323 return R;
2324
2325 if (isa<PHINode>(Op0))
2326 if (Instruction *NV = FoldOpIntoPhi(I))
2327 return NV;
2328 }
2329
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002330 if (I.getType() == Type::Int1Ty)
2331 return BinaryOperator::CreateXor(Op0, Op1);
2332
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2334 if (Op1I->getOpcode() == Instruction::Add &&
2335 !Op0->getType()->isFPOrFPVector()) {
2336 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002337 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002339 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2341 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2342 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344 Op1I->getOperand(0));
2345 }
2346 }
2347
2348 if (Op1I->hasOneUse()) {
2349 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2350 // is not used by anyone else...
2351 //
2352 if (Op1I->getOpcode() == Instruction::Sub &&
2353 !Op1I->getType()->isFPOrFPVector()) {
2354 // Swap the two operands of the subexpr...
2355 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2356 Op1I->setOperand(0, IIOp1);
2357 Op1I->setOperand(1, IIOp0);
2358
2359 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002360 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 }
2362
2363 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2364 //
2365 if (Op1I->getOpcode() == Instruction::And &&
2366 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2367 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2368
2369 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002370 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2371 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372 }
2373
2374 // 0 - (X sdiv C) -> (X sdiv -C)
2375 if (Op1I->getOpcode() == Instruction::SDiv)
2376 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2377 if (CSI->isZero())
2378 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002379 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 ConstantExpr::getNeg(DivRHS));
2381
2382 // X - X*C --> X * (1-C)
2383 ConstantInt *C2 = 0;
2384 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2385 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002386 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002387 }
Dan Gohmanda338742007-09-17 17:31:57 +00002388
2389 // X - ((X / Y) * Y) --> X % Y
2390 if (Op1I->getOpcode() == Instruction::Mul)
2391 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2392 if (Op0 == I->getOperand(0) &&
2393 Op1I->getOperand(1) == I->getOperand(1)) {
2394 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002395 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002396 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002399 }
2400 }
2401
2402 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002403 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002404 if (Op0I->getOpcode() == Instruction::Add) {
2405 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2406 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2407 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2408 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2409 } else if (Op0I->getOpcode() == Instruction::Sub) {
2410 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002411 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002412 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002413 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414
2415 ConstantInt *C1;
2416 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2417 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419
2420 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2421 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002422 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423 }
2424 return 0;
2425}
2426
2427/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2428/// comparison only checks the sign bit. If it only checks the sign bit, set
2429/// TrueIfSigned if the result of the comparison is true when the input value is
2430/// signed.
2431static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2432 bool &TrueIfSigned) {
2433 switch (pred) {
2434 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2435 TrueIfSigned = true;
2436 return RHS->isZero();
2437 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2438 TrueIfSigned = true;
2439 return RHS->isAllOnesValue();
2440 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2441 TrueIfSigned = false;
2442 return RHS->isAllOnesValue();
2443 case ICmpInst::ICMP_UGT:
2444 // True if LHS u> RHS and RHS == high-bit-mask - 1
2445 TrueIfSigned = true;
2446 return RHS->getValue() ==
2447 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2448 case ICmpInst::ICMP_UGE:
2449 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2450 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002451 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 default:
2453 return false;
2454 }
2455}
2456
2457Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2458 bool Changed = SimplifyCommutative(I);
2459 Value *Op0 = I.getOperand(0);
2460
2461 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464 // Simplify mul instructions with a constant RHS...
2465 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2466 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2467
2468 // ((X << C1)*C2) == (X * (C2 << C1))
2469 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2470 if (SI->getOpcode() == Instruction::Shl)
2471 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 ConstantExpr::getShl(CI, ShOp));
2474
2475 if (CI->isZero())
2476 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2477 if (CI->equalsInt(1)) // X * 1 == X
2478 return ReplaceInstUsesWith(I, Op0);
2479 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002480 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002481
2482 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2483 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002484 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 ConstantInt::get(Op0->getType(), Val.logBase2()));
2486 }
2487 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2488 if (Op1F->isNullValue())
2489 return ReplaceInstUsesWith(I, Op1);
2490
2491 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2492 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002493 // We need a better interface for long double here.
2494 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2495 if (Op1F->isExactlyValue(1.0))
2496 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 }
2498
2499 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2500 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002501 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002503 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 Op1, "tmp");
2505 InsertNewInstBefore(Add, I);
2506 Value *C1C2 = ConstantExpr::getMul(Op1,
2507 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002508 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002509
2510 }
2511
2512 // Try to fold constant mul into select arguments.
2513 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2514 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2515 return R;
2516
2517 if (isa<PHINode>(Op0))
2518 if (Instruction *NV = FoldOpIntoPhi(I))
2519 return NV;
2520 }
2521
2522 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2523 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002526 if (I.getType() == Type::Int1Ty)
2527 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2528
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 // If one of the operands of the multiply is a cast from a boolean value, then
2530 // we know the bool is either zero or one, so this is a 'masking' multiply.
2531 // See if we can simplify things based on how the boolean was originally
2532 // formed.
2533 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002534 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2536 BoolCast = CI;
2537 if (!BoolCast)
2538 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2539 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2540 BoolCast = CI;
2541 if (BoolCast) {
2542 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2543 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2544 const Type *SCOpTy = SCIOp0->getType();
2545 bool TIS = false;
2546
2547 // If the icmp is true iff the sign bit of X is set, then convert this
2548 // multiply into a shift/and combination.
2549 if (isa<ConstantInt>(SCIOp1) &&
2550 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2551 TIS) {
2552 // Shift the X value right to turn it into "all signbits".
2553 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2554 SCOpTy->getPrimitiveSizeInBits()-1);
2555 Value *V =
2556 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002557 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 BoolCast->getOperand(0)->getName()+
2559 ".mask"), I);
2560
2561 // If the multiply type is not the same as the source type, sign extend
2562 // or truncate to the multiply type.
2563 if (I.getType() != V->getType()) {
2564 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2565 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2566 Instruction::CastOps opcode =
2567 (SrcBits == DstBits ? Instruction::BitCast :
2568 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2569 V = InsertCastBefore(opcode, V, I.getType(), I);
2570 }
2571
2572 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002573 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002574 }
2575 }
2576 }
2577
2578 return Changed ? &I : 0;
2579}
2580
2581/// This function implements the transforms on div instructions that work
2582/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2583/// used by the visitors to those instructions.
2584/// @brief Transforms common to all three div instructions
2585Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2586 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
Chris Lattner653ef3c2008-02-19 06:12:18 +00002588 // undef / X -> 0 for integer.
2589 // undef / X -> undef for FP (the undef could be a snan).
2590 if (isa<UndefValue>(Op0)) {
2591 if (Op0->getType()->isFPOrFPVector())
2592 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002593 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002594 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595
2596 // X / undef -> undef
2597 if (isa<UndefValue>(Op1))
2598 return ReplaceInstUsesWith(I, Op1);
2599
Chris Lattner5be238b2008-01-28 00:58:18 +00002600 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2601 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002603 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2604 // the same basic block, then we replace the select with Y, and the
2605 // condition of the select with false (if the cond value is in the same BB).
2606 // If the select has uses other than the div, this allows them to be
2607 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2608 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002609 if (ST->isNullValue()) {
2610 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2611 if (CondI && CondI->getParent() == I.getParent())
2612 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2613 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2614 I.setOperand(1, SI->getOperand(2));
2615 else
2616 UpdateValueUsesWith(SI, SI->getOperand(2));
2617 return &I;
2618 }
2619
Chris Lattner5be238b2008-01-28 00:58:18 +00002620 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2621 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
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::getTrue());
2626 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2627 I.setOperand(1, SI->getOperand(1));
2628 else
2629 UpdateValueUsesWith(SI, SI->getOperand(1));
2630 return &I;
2631 }
2632 }
2633
2634 return 0;
2635}
2636
2637/// This function implements the transforms common to both integer division
2638/// instructions (udiv and sdiv). It is called by the visitors to those integer
2639/// division instructions.
2640/// @brief Common integer divide transforms
2641Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2643
Chris Lattnercefb36c2008-05-16 02:59:42 +00002644 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002645 if (Op0 == Op1) {
2646 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2647 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2648 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2649 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2650 }
2651
2652 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2653 return ReplaceInstUsesWith(I, CI);
2654 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002655
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002656 if (Instruction *Common = commonDivTransforms(I))
2657 return Common;
2658
2659 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2660 // div X, 1 == X
2661 if (RHS->equalsInt(1))
2662 return ReplaceInstUsesWith(I, Op0);
2663
2664 // (X / C1) / C2 -> X / (C1*C2)
2665 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2666 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2667 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002668 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2669 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2670 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002671 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002672 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 }
2674
2675 if (!RHS->isZero()) { // avoid X udiv 0
2676 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2677 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2678 return R;
2679 if (isa<PHINode>(Op0))
2680 if (Instruction *NV = FoldOpIntoPhi(I))
2681 return NV;
2682 }
2683 }
2684
2685 // 0 / X == 0, we don't need to preserve faults!
2686 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2687 if (LHS->equalsInt(0))
2688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2689
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002690 // It can't be division by zero, hence it must be division by one.
2691 if (I.getType() == Type::Int1Ty)
2692 return ReplaceInstUsesWith(I, Op0);
2693
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002694 return 0;
2695}
2696
2697Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2699
2700 // Handle the integer div common cases
2701 if (Instruction *Common = commonIDivTransforms(I))
2702 return Common;
2703
2704 // X udiv C^2 -> X >> C
2705 // Check to see if this is an unsigned division with an exact power of 2,
2706 // if so, convert to a right shift.
2707 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2708 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002709 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002710 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2711 }
2712
2713 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2714 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2715 if (RHSI->getOpcode() == Instruction::Shl &&
2716 isa<ConstantInt>(RHSI->getOperand(0))) {
2717 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2718 if (C1.isPowerOf2()) {
2719 Value *N = RHSI->getOperand(1);
2720 const Type *NTy = N->getType();
2721 if (uint32_t C2 = C1.logBase2()) {
2722 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002723 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002724 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 }
2727 }
2728 }
2729
2730 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2731 // where C1&C2 are powers of two.
2732 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2733 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2734 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2735 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2736 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2737 // Compute the shift amounts
2738 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2739 // Construct the "on true" case of the select
2740 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002741 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742 Op0, TC, SI->getName()+".t");
2743 TSI = InsertNewInstBefore(TSI, I);
2744
2745 // Construct the "on false" case of the select
2746 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002747 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002748 Op0, FC, SI->getName()+".f");
2749 FSI = InsertNewInstBefore(FSI, I);
2750
2751 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002752 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 }
2754 }
2755 return 0;
2756}
2757
2758Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2759 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2760
2761 // Handle the integer div common cases
2762 if (Instruction *Common = commonIDivTransforms(I))
2763 return Common;
2764
2765 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2766 // sdiv X, -1 == -X
2767 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769
2770 // -X/C -> X/-C
2771 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 }
2774
2775 // If the sign bits of both operands are zero (i.e. we can prove they are
2776 // unsigned inputs), turn this into a udiv.
2777 if (I.getType()->isInteger()) {
2778 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2779 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002780 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 }
2783 }
2784
2785 return 0;
2786}
2787
2788Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2789 return commonDivTransforms(I);
2790}
2791
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002792/// This function implements the transforms on rem instructions that work
2793/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2794/// is used by the visitors to those instructions.
2795/// @brief Transforms common to all three rem instructions
2796Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
Chris Lattner653ef3c2008-02-19 06:12:18 +00002799 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 if (Constant *LHS = dyn_cast<Constant>(Op0))
2801 if (LHS->isNullValue())
2802 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
Chris Lattner653ef3c2008-02-19 06:12:18 +00002804 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2805 if (I.getType()->isFPOrFPVector())
2806 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002808 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002809 if (isa<UndefValue>(Op1))
2810 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2811
2812 // Handle cases involving: rem X, (select Cond, Y, Z)
2813 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2814 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2815 // the same basic block, then we replace the select with Y, and the
2816 // condition of the select with false (if the cond value is in the same
2817 // BB). If the select has uses other than the div, this allows them to be
2818 // simplified also.
2819 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2820 if (ST->isNullValue()) {
2821 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822 if (CondI && CondI->getParent() == I.getParent())
2823 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2824 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825 I.setOperand(1, SI->getOperand(2));
2826 else
2827 UpdateValueUsesWith(SI, SI->getOperand(2));
2828 return &I;
2829 }
2830 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2831 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2832 if (ST->isNullValue()) {
2833 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2834 if (CondI && CondI->getParent() == I.getParent())
2835 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2836 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2837 I.setOperand(1, SI->getOperand(1));
2838 else
2839 UpdateValueUsesWith(SI, SI->getOperand(1));
2840 return &I;
2841 }
2842 }
2843
2844 return 0;
2845}
2846
2847/// This function implements the transforms common to both integer remainder
2848/// instructions (urem and srem). It is called by the visitors to those integer
2849/// remainder instructions.
2850/// @brief Common integer remainder transforms
2851Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854 if (Instruction *common = commonRemTransforms(I))
2855 return common;
2856
2857 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2858 // X % 0 == undef, we don't need to preserve faults!
2859 if (RHS->equalsInt(0))
2860 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2861
2862 if (RHS->equalsInt(1)) // X % 1 == 0
2863 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2864
2865 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2866 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2867 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2868 return R;
2869 } else if (isa<PHINode>(Op0I)) {
2870 if (Instruction *NV = FoldOpIntoPhi(I))
2871 return NV;
2872 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002873
2874 // See if we can fold away this rem instruction.
2875 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2876 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2877 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2878 KnownZero, KnownOne))
2879 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880 }
2881 }
2882
2883 return 0;
2884}
2885
2886Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2888
2889 if (Instruction *common = commonIRemTransforms(I))
2890 return common;
2891
2892 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2893 // X urem C^2 -> X and C
2894 // Check to see if this is an unsigned remainder with an exact power of 2,
2895 // if so, convert to a bitwise and.
2896 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2897 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00002898 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899 }
2900
2901 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2902 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2903 if (RHSI->getOpcode() == Instruction::Shl &&
2904 isa<ConstantInt>(RHSI->getOperand(0))) {
2905 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2906 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00002907 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002909 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 }
2911 }
2912 }
2913
2914 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2915 // where C1&C2 are powers of two.
2916 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2917 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2918 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2919 // STO == 0 and SFO == 0 handled above.
2920 if ((STO->getValue().isPowerOf2()) &&
2921 (SFO->getValue().isPowerOf2())) {
2922 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002923 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002924 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002925 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002926 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002927 }
2928 }
2929 }
2930
2931 return 0;
2932}
2933
2934Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2936
Dan Gohmandb3dd962007-11-05 23:16:33 +00002937 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938 if (Instruction *common = commonIRemTransforms(I))
2939 return common;
2940
2941 if (Value *RHSNeg = dyn_castNegVal(Op1))
2942 if (!isa<ConstantInt>(RHSNeg) ||
2943 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2944 // X % -Y -> X % Y
2945 AddUsesToWorkList(I);
2946 I.setOperand(1, RHSNeg);
2947 return &I;
2948 }
2949
Dan Gohmandb3dd962007-11-05 23:16:33 +00002950 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002952 if (I.getType()->isInteger()) {
2953 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2954 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2955 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002956 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00002957 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002958 }
2959
2960 return 0;
2961}
2962
2963Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2964 return commonRemTransforms(I);
2965}
2966
2967// isMaxValueMinusOne - return true if this is Max-1
2968static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2969 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2970 if (!isSigned)
2971 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2972 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2973}
2974
2975// isMinValuePlusOne - return true if this is Min+1
2976static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2977 if (!isSigned)
2978 return C->getValue() == 1; // unsigned
2979
2980 // Calculate 1111111111000000000000
2981 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2982 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2983}
2984
2985// isOneBitSet - Return true if there is exactly one bit set in the specified
2986// constant.
2987static bool isOneBitSet(const ConstantInt *CI) {
2988 return CI->getValue().isPowerOf2();
2989}
2990
2991// isHighOnes - Return true if the constant is of the form 1+0+.
2992// This is the same as lowones(~X).
2993static bool isHighOnes(const ConstantInt *CI) {
2994 return (~CI->getValue() + 1).isPowerOf2();
2995}
2996
2997/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2998/// are carefully arranged to allow folding of expressions such as:
2999///
3000/// (A < B) | (A > B) --> (A != B)
3001///
3002/// Note that this is only valid if the first and second predicates have the
3003/// same sign. Is illegal to do: (A u< B) | (A s> B)
3004///
3005/// Three bits are used to represent the condition, as follows:
3006/// 0 A > B
3007/// 1 A == B
3008/// 2 A < B
3009///
3010/// <=> Value Definition
3011/// 000 0 Always false
3012/// 001 1 A > B
3013/// 010 2 A == B
3014/// 011 3 A >= B
3015/// 100 4 A < B
3016/// 101 5 A != B
3017/// 110 6 A <= B
3018/// 111 7 Always true
3019///
3020static unsigned getICmpCode(const ICmpInst *ICI) {
3021 switch (ICI->getPredicate()) {
3022 // False -> 0
3023 case ICmpInst::ICMP_UGT: return 1; // 001
3024 case ICmpInst::ICMP_SGT: return 1; // 001
3025 case ICmpInst::ICMP_EQ: return 2; // 010
3026 case ICmpInst::ICMP_UGE: return 3; // 011
3027 case ICmpInst::ICMP_SGE: return 3; // 011
3028 case ICmpInst::ICMP_ULT: return 4; // 100
3029 case ICmpInst::ICMP_SLT: return 4; // 100
3030 case ICmpInst::ICMP_NE: return 5; // 101
3031 case ICmpInst::ICMP_ULE: return 6; // 110
3032 case ICmpInst::ICMP_SLE: return 6; // 110
3033 // True -> 7
3034 default:
3035 assert(0 && "Invalid ICmp predicate!");
3036 return 0;
3037 }
3038}
3039
3040/// getICmpValue - This is the complement of getICmpCode, which turns an
3041/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003042/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043/// of predicate to use in new icmp instructions.
3044static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3045 switch (code) {
3046 default: assert(0 && "Illegal ICmp code!");
3047 case 0: return ConstantInt::getFalse();
3048 case 1:
3049 if (sign)
3050 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3051 else
3052 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3053 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3054 case 3:
3055 if (sign)
3056 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3057 else
3058 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3059 case 4:
3060 if (sign)
3061 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3062 else
3063 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3064 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3065 case 6:
3066 if (sign)
3067 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3068 else
3069 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3070 case 7: return ConstantInt::getTrue();
3071 }
3072}
3073
3074static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3075 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3076 (ICmpInst::isSignedPredicate(p1) &&
3077 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3078 (ICmpInst::isSignedPredicate(p2) &&
3079 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3080}
3081
3082namespace {
3083// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3084struct FoldICmpLogical {
3085 InstCombiner &IC;
3086 Value *LHS, *RHS;
3087 ICmpInst::Predicate pred;
3088 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3089 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3090 pred(ICI->getPredicate()) {}
3091 bool shouldApply(Value *V) const {
3092 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3093 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003094 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3095 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096 return false;
3097 }
3098 Instruction *apply(Instruction &Log) const {
3099 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3100 if (ICI->getOperand(0) != LHS) {
3101 assert(ICI->getOperand(1) == LHS);
3102 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3103 }
3104
3105 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3106 unsigned LHSCode = getICmpCode(ICI);
3107 unsigned RHSCode = getICmpCode(RHSICI);
3108 unsigned Code;
3109 switch (Log.getOpcode()) {
3110 case Instruction::And: Code = LHSCode & RHSCode; break;
3111 case Instruction::Or: Code = LHSCode | RHSCode; break;
3112 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3113 default: assert(0 && "Illegal logical opcode!"); return 0;
3114 }
3115
3116 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3117 ICmpInst::isSignedPredicate(ICI->getPredicate());
3118
3119 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3120 if (Instruction *I = dyn_cast<Instruction>(RV))
3121 return I;
3122 // Otherwise, it's a constant boolean value...
3123 return IC.ReplaceInstUsesWith(Log, RV);
3124 }
3125};
3126} // end anonymous namespace
3127
3128// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3129// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3130// guaranteed to be a binary operator.
3131Instruction *InstCombiner::OptAndOp(Instruction *Op,
3132 ConstantInt *OpRHS,
3133 ConstantInt *AndRHS,
3134 BinaryOperator &TheAnd) {
3135 Value *X = Op->getOperand(0);
3136 Constant *Together = 0;
3137 if (!Op->isShift())
3138 Together = And(AndRHS, OpRHS);
3139
3140 switch (Op->getOpcode()) {
3141 case Instruction::Xor:
3142 if (Op->hasOneUse()) {
3143 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003144 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 InsertNewInstBefore(And, TheAnd);
3146 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003147 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 }
3149 break;
3150 case Instruction::Or:
3151 if (Together == AndRHS) // (X | C) & C --> C
3152 return ReplaceInstUsesWith(TheAnd, AndRHS);
3153
3154 if (Op->hasOneUse() && Together != OpRHS) {
3155 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003156 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003157 InsertNewInstBefore(Or, TheAnd);
3158 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003159 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 }
3161 break;
3162 case Instruction::Add:
3163 if (Op->hasOneUse()) {
3164 // Adding a one to a single bit bit-field should be turned into an XOR
3165 // of the bit. First thing to check is to see if this AND is with a
3166 // single bit constant.
3167 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3168
3169 // If there is only one bit set...
3170 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3171 // Ok, at this point, we know that we are masking the result of the
3172 // ADD down to exactly one bit. If the constant we are adding has
3173 // no bits set below this bit, then we can eliminate the ADD.
3174 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3175
3176 // Check to see if any bits below the one bit set in AndRHSV are set.
3177 if ((AddRHS & (AndRHSV-1)) == 0) {
3178 // If not, the only thing that can effect the output of the AND is
3179 // the bit specified by AndRHSV. If that bit is set, the effect of
3180 // the XOR is to toggle the bit. If it is clear, then the ADD has
3181 // no effect.
3182 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3183 TheAnd.setOperand(0, X);
3184 return &TheAnd;
3185 } else {
3186 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003187 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 InsertNewInstBefore(NewAnd, TheAnd);
3189 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003190 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003191 }
3192 }
3193 }
3194 }
3195 break;
3196
3197 case Instruction::Shl: {
3198 // We know that the AND will not produce any of the bits shifted in, so if
3199 // the anded constant includes them, clear them now!
3200 //
3201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3203 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3204 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3205
3206 if (CI->getValue() == ShlMask) {
3207 // Masking out bits that the shift already masks
3208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3209 } else if (CI != AndRHS) { // Reducing bits set in and.
3210 TheAnd.setOperand(1, CI);
3211 return &TheAnd;
3212 }
3213 break;
3214 }
3215 case Instruction::LShr:
3216 {
3217 // We know that the AND will not produce any of the bits shifted in, so if
3218 // the anded constant includes them, clear them now! This only applies to
3219 // unsigned shifts, because a signed shr may bring in set bits!
3220 //
3221 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3222 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3223 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3224 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3225
3226 if (CI->getValue() == ShrMask) {
3227 // Masking out bits that the shift already masks.
3228 return ReplaceInstUsesWith(TheAnd, Op);
3229 } else if (CI != AndRHS) {
3230 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3231 return &TheAnd;
3232 }
3233 break;
3234 }
3235 case Instruction::AShr:
3236 // Signed shr.
3237 // See if this is shifting in some sign extension, then masking it out
3238 // with an and.
3239 if (Op->hasOneUse()) {
3240 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3241 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3242 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3243 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3244 if (C == AndRHS) { // Masking out bits shifted in.
3245 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3246 // Make the argument unsigned.
3247 Value *ShVal = Op->getOperand(0);
3248 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003249 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003251 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252 }
3253 }
3254 break;
3255 }
3256 return 0;
3257}
3258
3259
3260/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3261/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3262/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3263/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3264/// insert new instructions.
3265Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3266 bool isSigned, bool Inside,
3267 Instruction &IB) {
3268 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3269 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3270 "Lo is not <= Hi in range emission code!");
3271
3272 if (Inside) {
3273 if (Lo == Hi) // Trivially false.
3274 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3275
3276 // V >= Min && V < Hi --> V < Hi
3277 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3278 ICmpInst::Predicate pred = (isSigned ?
3279 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3280 return new ICmpInst(pred, V, Hi);
3281 }
3282
3283 // Emit V-Lo <u Hi-Lo
3284 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003285 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286 InsertNewInstBefore(Add, IB);
3287 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3288 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3289 }
3290
3291 if (Lo == Hi) // Trivially true.
3292 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3293
3294 // V < Min || V >= Hi -> V > Hi-1
3295 Hi = SubOne(cast<ConstantInt>(Hi));
3296 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3297 ICmpInst::Predicate pred = (isSigned ?
3298 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3299 return new ICmpInst(pred, V, Hi);
3300 }
3301
3302 // Emit V-Lo >u Hi-1-Lo
3303 // Note that Hi has already had one subtracted from it, above.
3304 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003305 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 InsertNewInstBefore(Add, IB);
3307 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3308 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3309}
3310
3311// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3312// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3313// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3314// not, since all 1s are not contiguous.
3315static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3316 const APInt& V = Val->getValue();
3317 uint32_t BitWidth = Val->getType()->getBitWidth();
3318 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3319
3320 // look for the first zero bit after the run of ones
3321 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3322 // look for the first non-zero bit
3323 ME = V.getActiveBits();
3324 return true;
3325}
3326
3327/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3328/// where isSub determines whether the operator is a sub. If we can fold one of
3329/// the following xforms:
3330///
3331/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3332/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3333/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3334///
3335/// return (A +/- B).
3336///
3337Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3338 ConstantInt *Mask, bool isSub,
3339 Instruction &I) {
3340 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3341 if (!LHSI || LHSI->getNumOperands() != 2 ||
3342 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3343
3344 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3345
3346 switch (LHSI->getOpcode()) {
3347 default: return 0;
3348 case Instruction::And:
3349 if (And(N, Mask) == Mask) {
3350 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3351 if ((Mask->getValue().countLeadingZeros() +
3352 Mask->getValue().countPopulation()) ==
3353 Mask->getValue().getBitWidth())
3354 break;
3355
3356 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3357 // part, we don't need any explicit masks to take them out of A. If that
3358 // is all N is, ignore it.
3359 uint32_t MB = 0, ME = 0;
3360 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3361 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3362 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3363 if (MaskedValueIsZero(RHS, Mask))
3364 break;
3365 }
3366 }
3367 return 0;
3368 case Instruction::Or:
3369 case Instruction::Xor:
3370 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3371 if ((Mask->getValue().countLeadingZeros() +
3372 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3373 && And(N, Mask)->isZero())
3374 break;
3375 return 0;
3376 }
3377
3378 Instruction *New;
3379 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003380 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003381 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003382 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 return InsertNewInstBefore(New, I);
3384}
3385
3386Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3387 bool Changed = SimplifyCommutative(I);
3388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3389
3390 if (isa<UndefValue>(Op1)) // X & undef -> 0
3391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3392
3393 // and X, X = X
3394 if (Op0 == Op1)
3395 return ReplaceInstUsesWith(I, Op1);
3396
3397 // See if we can simplify any instructions used by the instruction whose sole
3398 // purpose is to compute bits we don't care about.
3399 if (!isa<VectorType>(I.getType())) {
3400 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3401 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3402 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3403 KnownZero, KnownOne))
3404 return &I;
3405 } else {
3406 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3407 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3408 return ReplaceInstUsesWith(I, I.getOperand(0));
3409 } else if (isa<ConstantAggregateZero>(Op1)) {
3410 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3411 }
3412 }
3413
3414 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3415 const APInt& AndRHSMask = AndRHS->getValue();
3416 APInt NotAndRHS(~AndRHSMask);
3417
3418 // Optimize a variety of ((val OP C1) & C2) combinations...
3419 if (isa<BinaryOperator>(Op0)) {
3420 Instruction *Op0I = cast<Instruction>(Op0);
3421 Value *Op0LHS = Op0I->getOperand(0);
3422 Value *Op0RHS = Op0I->getOperand(1);
3423 switch (Op0I->getOpcode()) {
3424 case Instruction::Xor:
3425 case Instruction::Or:
3426 // If the mask is only needed on one incoming arm, push it up.
3427 if (Op0I->hasOneUse()) {
3428 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3429 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003430 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431 Op0RHS->getName()+".masked");
3432 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003433 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003434 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3435 }
3436 if (!isa<Constant>(Op0RHS) &&
3437 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3438 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003439 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440 Op0LHS->getName()+".masked");
3441 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003442 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003443 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3444 }
3445 }
3446
3447 break;
3448 case Instruction::Add:
3449 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3450 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3451 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3452 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003453 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003455 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 break;
3457
3458 case Instruction::Sub:
3459 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3460 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3461 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3462 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003463 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003464
3465 // (A - N) & AndRHS -> -N & AndRHS where A & AndRHS == 0
3466 if (Op0I->hasOneUse() && MaskedValueIsZero(Op0LHS, AndRHSMask)) {
3467 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3468 if (!A || !A->isZero()) {
3469 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3470 InsertNewInstBefore(NewNeg, I);
3471 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3472 }
3473 }
3474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003475 break;
3476 }
3477
3478 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3479 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3480 return Res;
3481 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3482 // If this is an integer truncation or change from signed-to-unsigned, and
3483 // if the source is an and/or with immediate, transform it. This
3484 // frequently occurs for bitfield accesses.
3485 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3486 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3487 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003488 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489 if (CastOp->getOpcode() == Instruction::And) {
3490 // Change: and (cast (and X, C1) to T), C2
3491 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3492 // This will fold the two constants together, which may allow
3493 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003494 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 CastOp->getOperand(0), I.getType(),
3496 CastOp->getName()+".shrunk");
3497 NewCast = InsertNewInstBefore(NewCast, I);
3498 // trunc_or_bitcast(C1)&C2
3499 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3500 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003501 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003502 } else if (CastOp->getOpcode() == Instruction::Or) {
3503 // Change: and (cast (or X, C1) to T), C2
3504 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3505 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3506 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3507 return ReplaceInstUsesWith(I, AndRHS);
3508 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003509 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003510 }
3511 }
3512
3513 // Try to fold constant and into select arguments.
3514 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3515 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3516 return R;
3517 if (isa<PHINode>(Op0))
3518 if (Instruction *NV = FoldOpIntoPhi(I))
3519 return NV;
3520 }
3521
3522 Value *Op0NotVal = dyn_castNotVal(Op0);
3523 Value *Op1NotVal = dyn_castNotVal(Op1);
3524
3525 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3527
3528 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3529 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003530 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003531 I.getName()+".demorgan");
3532 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 }
3535
3536 {
3537 Value *A = 0, *B = 0, *C = 0, *D = 0;
3538 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3539 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3540 return ReplaceInstUsesWith(I, Op1);
3541
3542 // (A|B) & ~(A&B) -> A^B
3543 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3544 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003545 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546 }
3547 }
3548
3549 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3550 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3551 return ReplaceInstUsesWith(I, Op0);
3552
3553 // ~(A&B) & (A|B) -> A^B
3554 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3555 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003556 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557 }
3558 }
3559
3560 if (Op0->hasOneUse() &&
3561 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3562 if (A == Op1) { // (A^B)&A -> A&(A^B)
3563 I.swapOperands(); // Simplify below
3564 std::swap(Op0, Op1);
3565 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3566 cast<BinaryOperator>(Op0)->swapOperands();
3567 I.swapOperands(); // Simplify below
3568 std::swap(Op0, Op1);
3569 }
3570 }
3571 if (Op1->hasOneUse() &&
3572 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3573 if (B == Op0) { // B&(A^B) -> B&(B^A)
3574 cast<BinaryOperator>(Op1)->swapOperands();
3575 std::swap(A, B);
3576 }
3577 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003578 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003580 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 }
3582 }
3583 }
3584
3585 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3586 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3587 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3588 return R;
3589
3590 Value *LHSVal, *RHSVal;
3591 ConstantInt *LHSCst, *RHSCst;
3592 ICmpInst::Predicate LHSCC, RHSCC;
3593 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3594 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3595 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3596 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3597 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3598 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3599 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003600 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3601
3602 // Don't try to fold ICMP_SLT + ICMP_ULT.
3603 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3604 ICmpInst::isSignedPredicate(LHSCC) ==
3605 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003607 ICmpInst::Predicate GT;
3608 if (ICmpInst::isSignedPredicate(LHSCC) ||
3609 (ICmpInst::isEquality(LHSCC) &&
3610 ICmpInst::isSignedPredicate(RHSCC)))
3611 GT = ICmpInst::ICMP_SGT;
3612 else
3613 GT = ICmpInst::ICMP_UGT;
3614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003615 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3616 ICmpInst *LHS = cast<ICmpInst>(Op0);
3617 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3618 std::swap(LHS, RHS);
3619 std::swap(LHSCst, RHSCst);
3620 std::swap(LHSCC, RHSCC);
3621 }
3622
3623 // At this point, we know we have have two icmp instructions
3624 // comparing a value against two constants and and'ing the result
3625 // together. Because of the above check, we know that we only have
3626 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3627 // (from the FoldICmpLogical check above), that the two constants
3628 // are not equal and that the larger constant is on the RHS
3629 assert(LHSCst != RHSCst && "Compares not folded above?");
3630
3631 switch (LHSCC) {
3632 default: assert(0 && "Unknown integer condition code!");
3633 case ICmpInst::ICMP_EQ:
3634 switch (RHSCC) {
3635 default: assert(0 && "Unknown integer condition code!");
3636 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3637 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3638 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3639 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3640 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3641 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3642 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3643 return ReplaceInstUsesWith(I, LHS);
3644 }
3645 case ICmpInst::ICMP_NE:
3646 switch (RHSCC) {
3647 default: assert(0 && "Unknown integer condition code!");
3648 case ICmpInst::ICMP_ULT:
3649 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3650 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3651 break; // (X != 13 & X u< 15) -> no change
3652 case ICmpInst::ICMP_SLT:
3653 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3654 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3655 break; // (X != 13 & X s< 15) -> no change
3656 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3657 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3658 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3659 return ReplaceInstUsesWith(I, RHS);
3660 case ICmpInst::ICMP_NE:
3661 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3662 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00003663 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 LHSVal->getName()+".off");
3665 InsertNewInstBefore(Add, I);
3666 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3667 ConstantInt::get(Add->getType(), 1));
3668 }
3669 break; // (X != 13 & X != 15) -> no change
3670 }
3671 break;
3672 case ICmpInst::ICMP_ULT:
3673 switch (RHSCC) {
3674 default: assert(0 && "Unknown integer condition code!");
3675 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3676 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3677 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3678 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3679 break;
3680 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3681 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3682 return ReplaceInstUsesWith(I, LHS);
3683 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3684 break;
3685 }
3686 break;
3687 case ICmpInst::ICMP_SLT:
3688 switch (RHSCC) {
3689 default: assert(0 && "Unknown integer condition code!");
3690 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3691 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3692 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3693 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3694 break;
3695 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3696 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3697 return ReplaceInstUsesWith(I, LHS);
3698 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3699 break;
3700 }
3701 break;
3702 case ICmpInst::ICMP_UGT:
3703 switch (RHSCC) {
3704 default: assert(0 && "Unknown integer condition code!");
Eli Friedman22b85622008-06-21 23:36:13 +00003705 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3707 return ReplaceInstUsesWith(I, RHS);
3708 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3709 break;
3710 case ICmpInst::ICMP_NE:
3711 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3712 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3713 break; // (X u> 13 & X != 15) -> no change
3714 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3715 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3716 true, I);
3717 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3718 break;
3719 }
3720 break;
3721 case ICmpInst::ICMP_SGT:
3722 switch (RHSCC) {
3723 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003724 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3726 return ReplaceInstUsesWith(I, RHS);
3727 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3728 break;
3729 case ICmpInst::ICMP_NE:
3730 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3731 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3732 break; // (X s> 13 & X != 15) -> no change
3733 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3734 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3735 true, I);
3736 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3737 break;
3738 }
3739 break;
3740 }
3741 }
3742 }
3743
3744 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3745 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3746 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3747 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3748 const Type *SrcTy = Op0C->getOperand(0)->getType();
3749 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3750 // Only do this if the casts both really cause code to be generated.
3751 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3752 I.getType(), TD) &&
3753 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3754 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003755 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756 Op1C->getOperand(0),
3757 I.getName());
3758 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003759 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 }
3761 }
3762
3763 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3764 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3765 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3766 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3767 SI0->getOperand(1) == SI1->getOperand(1) &&
3768 (SI0->hasOneUse() || SI1->hasOneUse())) {
3769 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00003770 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771 SI1->getOperand(0),
3772 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003773 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003774 SI1->getOperand(1));
3775 }
3776 }
3777
Chris Lattner91882432007-10-24 05:38:08 +00003778 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3779 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3780 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3781 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3782 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3783 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3784 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3785 // If either of the constants are nans, then the whole thing returns
3786 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003787 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003788 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3789 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3790 RHS->getOperand(0));
3791 }
3792 }
3793 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003794
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003795 return Changed ? &I : 0;
3796}
3797
3798/// CollectBSwapParts - Look to see if the specified value defines a single byte
3799/// in the result. If it does, and if the specified byte hasn't been filled in
3800/// yet, fill it in and return false.
3801static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3802 Instruction *I = dyn_cast<Instruction>(V);
3803 if (I == 0) return true;
3804
3805 // If this is an or instruction, it is an inner node of the bswap.
3806 if (I->getOpcode() == Instruction::Or)
3807 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3808 CollectBSwapParts(I->getOperand(1), ByteValues);
3809
3810 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3811 // If this is a shift by a constant int, and it is "24", then its operand
3812 // defines a byte. We only handle unsigned types here.
3813 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3814 // Not shifting the entire input by N-1 bytes?
3815 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3816 8*(ByteValues.size()-1))
3817 return true;
3818
3819 unsigned DestNo;
3820 if (I->getOpcode() == Instruction::Shl) {
3821 // X << 24 defines the top byte with the lowest of the input bytes.
3822 DestNo = ByteValues.size()-1;
3823 } else {
3824 // X >>u 24 defines the low byte with the highest of the input bytes.
3825 DestNo = 0;
3826 }
3827
3828 // If the destination byte value is already defined, the values are or'd
3829 // together, which isn't a bswap (unless it's an or of the same bits).
3830 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3831 return true;
3832 ByteValues[DestNo] = I->getOperand(0);
3833 return false;
3834 }
3835
3836 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3837 // don't have this.
3838 Value *Shift = 0, *ShiftLHS = 0;
3839 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3840 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3841 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3842 return true;
3843 Instruction *SI = cast<Instruction>(Shift);
3844
3845 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3846 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3847 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3848 return true;
3849
3850 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3851 unsigned DestByte;
3852 if (AndAmt->getValue().getActiveBits() > 64)
3853 return true;
3854 uint64_t AndAmtVal = AndAmt->getZExtValue();
3855 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3856 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3857 break;
3858 // Unknown mask for bswap.
3859 if (DestByte == ByteValues.size()) return true;
3860
3861 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3862 unsigned SrcByte;
3863 if (SI->getOpcode() == Instruction::Shl)
3864 SrcByte = DestByte - ShiftBytes;
3865 else
3866 SrcByte = DestByte + ShiftBytes;
3867
3868 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3869 if (SrcByte != ByteValues.size()-DestByte-1)
3870 return true;
3871
3872 // If the destination byte value is already defined, the values are or'd
3873 // together, which isn't a bswap (unless it's an or of the same bits).
3874 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3875 return true;
3876 ByteValues[DestByte] = SI->getOperand(0);
3877 return false;
3878}
3879
3880/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3881/// If so, insert the new bswap intrinsic and return it.
3882Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3883 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3884 if (!ITy || ITy->getBitWidth() % 16)
3885 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3886
3887 /// ByteValues - For each byte of the result, we keep track of which value
3888 /// defines each byte.
3889 SmallVector<Value*, 8> ByteValues;
3890 ByteValues.resize(ITy->getBitWidth()/8);
3891
3892 // Try to find all the pieces corresponding to the bswap.
3893 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3894 CollectBSwapParts(I.getOperand(1), ByteValues))
3895 return 0;
3896
3897 // Check to see if all of the bytes come from the same value.
3898 Value *V = ByteValues[0];
3899 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3900
3901 // Check to make sure that all of the bytes come from the same value.
3902 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3903 if (ByteValues[i] != V)
3904 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003905 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003906 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003907 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003908 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909}
3910
3911
3912Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3913 bool Changed = SimplifyCommutative(I);
3914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3915
3916 if (isa<UndefValue>(Op1)) // X | undef -> -1
3917 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3918
3919 // or X, X = X
3920 if (Op0 == Op1)
3921 return ReplaceInstUsesWith(I, Op0);
3922
3923 // See if we can simplify any instructions used by the instruction whose sole
3924 // purpose is to compute bits we don't care about.
3925 if (!isa<VectorType>(I.getType())) {
3926 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3927 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3928 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3929 KnownZero, KnownOne))
3930 return &I;
3931 } else if (isa<ConstantAggregateZero>(Op1)) {
3932 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3933 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3934 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3935 return ReplaceInstUsesWith(I, I.getOperand(1));
3936 }
3937
3938
3939
3940 // or X, -1 == -1
3941 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3942 ConstantInt *C1 = 0; Value *X = 0;
3943 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3944 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003945 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003946 InsertNewInstBefore(Or, I);
3947 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003948 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949 ConstantInt::get(RHS->getValue() | C1->getValue()));
3950 }
3951
3952 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3953 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003954 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003955 InsertNewInstBefore(Or, I);
3956 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003957 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003958 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3959 }
3960
3961 // Try to fold constant and into select arguments.
3962 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3963 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3964 return R;
3965 if (isa<PHINode>(Op0))
3966 if (Instruction *NV = FoldOpIntoPhi(I))
3967 return NV;
3968 }
3969
3970 Value *A = 0, *B = 0;
3971 ConstantInt *C1 = 0, *C2 = 0;
3972
3973 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3974 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3975 return ReplaceInstUsesWith(I, Op1);
3976 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3977 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3978 return ReplaceInstUsesWith(I, Op0);
3979
3980 // (A | B) | C and A | (B | C) -> bswap if possible.
3981 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3982 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3983 match(Op1, m_Or(m_Value(), m_Value())) ||
3984 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3985 match(Op1, m_Shift(m_Value(), m_Value())))) {
3986 if (Instruction *BSwap = MatchBSwap(I))
3987 return BSwap;
3988 }
3989
3990 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3991 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3992 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003993 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994 InsertNewInstBefore(NOr, I);
3995 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003996 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 }
3998
3999 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4000 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4001 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004002 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004003 InsertNewInstBefore(NOr, I);
4004 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004005 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004006 }
4007
4008 // (A & C)|(B & D)
4009 Value *C = 0, *D = 0;
4010 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4011 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4012 Value *V1 = 0, *V2 = 0, *V3 = 0;
4013 C1 = dyn_cast<ConstantInt>(C);
4014 C2 = dyn_cast<ConstantInt>(D);
4015 if (C1 && C2) { // (A & C1)|(B & C2)
4016 // If we have: ((V + N) & C1) | (V & C2)
4017 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4018 // replace with V+N.
4019 if (C1->getValue() == ~C2->getValue()) {
4020 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4021 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4022 // Add commutes, try both ways.
4023 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4024 return ReplaceInstUsesWith(I, A);
4025 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4026 return ReplaceInstUsesWith(I, A);
4027 }
4028 // Or commutes, try both ways.
4029 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4030 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4031 // Add commutes, try both ways.
4032 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4033 return ReplaceInstUsesWith(I, B);
4034 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4035 return ReplaceInstUsesWith(I, B);
4036 }
4037 }
4038 V1 = 0; V2 = 0; V3 = 0;
4039 }
4040
4041 // Check to see if we have any common things being and'ed. If so, find the
4042 // terms for V1 & (V2|V3).
4043 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4044 if (A == B) // (A & C)|(A & D) == A & (C|D)
4045 V1 = A, V2 = C, V3 = D;
4046 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4047 V1 = A, V2 = B, V3 = C;
4048 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4049 V1 = C, V2 = A, V3 = D;
4050 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4051 V1 = C, V2 = A, V3 = B;
4052
4053 if (V1) {
4054 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004055 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4056 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004058 }
4059 }
4060
4061 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4062 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4063 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4064 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4065 SI0->getOperand(1) == SI1->getOperand(1) &&
4066 (SI0->hasOneUse() || SI1->hasOneUse())) {
4067 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004068 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069 SI1->getOperand(0),
4070 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004071 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072 SI1->getOperand(1));
4073 }
4074 }
4075
4076 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4077 if (A == Op1) // ~A | A == -1
4078 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4079 } else {
4080 A = 0;
4081 }
4082 // Note, A is still live here!
4083 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4084 if (Op0 == B)
4085 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4086
4087 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4088 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004089 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 }
4093 }
4094
4095 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4096 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4097 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4098 return R;
4099
4100 Value *LHSVal, *RHSVal;
4101 ConstantInt *LHSCst, *RHSCst;
4102 ICmpInst::Predicate LHSCC, RHSCC;
4103 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4104 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4105 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4106 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4107 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4108 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4109 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4110 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4111 // We can't fold (ugt x, C) | (sgt x, C2).
4112 PredicatesFoldable(LHSCC, RHSCC)) {
4113 // Ensure that the larger constant is on the RHS.
4114 ICmpInst *LHS = cast<ICmpInst>(Op0);
4115 bool NeedsSwap;
4116 if (ICmpInst::isSignedPredicate(LHSCC))
4117 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4118 else
4119 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4120
4121 if (NeedsSwap) {
4122 std::swap(LHS, RHS);
4123 std::swap(LHSCst, RHSCst);
4124 std::swap(LHSCC, RHSCC);
4125 }
4126
4127 // At this point, we know we have have two icmp instructions
4128 // comparing a value against two constants and or'ing the result
4129 // together. Because of the above check, we know that we only have
4130 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4131 // FoldICmpLogical check above), that the two constants are not
4132 // equal.
4133 assert(LHSCst != RHSCst && "Compares not folded above?");
4134
4135 switch (LHSCC) {
4136 default: assert(0 && "Unknown integer condition code!");
4137 case ICmpInst::ICMP_EQ:
4138 switch (RHSCC) {
4139 default: assert(0 && "Unknown integer condition code!");
4140 case ICmpInst::ICMP_EQ:
4141 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4142 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004143 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004144 LHSVal->getName()+".off");
4145 InsertNewInstBefore(Add, I);
4146 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4147 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4148 }
4149 break; // (X == 13 | X == 15) -> no change
4150 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4151 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4152 break;
4153 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4154 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4155 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4156 return ReplaceInstUsesWith(I, RHS);
4157 }
4158 break;
4159 case ICmpInst::ICMP_NE:
4160 switch (RHSCC) {
4161 default: assert(0 && "Unknown integer condition code!");
4162 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4163 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4164 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4165 return ReplaceInstUsesWith(I, LHS);
4166 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4167 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4168 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4169 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4170 }
4171 break;
4172 case ICmpInst::ICMP_ULT:
4173 switch (RHSCC) {
4174 default: assert(0 && "Unknown integer condition code!");
4175 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4176 break;
4177 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004178 // If RHSCst is [us]MAXINT, it is always false. Not handling
4179 // this can cause overflow.
4180 if (RHSCst->isMaxValue(false))
4181 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4183 false, I);
4184 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4185 break;
4186 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4187 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4188 return ReplaceInstUsesWith(I, RHS);
4189 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4190 break;
4191 }
4192 break;
4193 case ICmpInst::ICMP_SLT:
4194 switch (RHSCC) {
4195 default: assert(0 && "Unknown integer condition code!");
4196 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4197 break;
4198 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004199 // If RHSCst is [us]MAXINT, it is always false. Not handling
4200 // this can cause overflow.
4201 if (RHSCst->isMaxValue(true))
4202 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4204 false, I);
4205 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4206 break;
4207 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4208 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4209 return ReplaceInstUsesWith(I, RHS);
4210 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4211 break;
4212 }
4213 break;
4214 case ICmpInst::ICMP_UGT:
4215 switch (RHSCC) {
4216 default: assert(0 && "Unknown integer condition code!");
4217 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4218 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4219 return ReplaceInstUsesWith(I, LHS);
4220 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4221 break;
4222 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4223 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4224 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4225 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4226 break;
4227 }
4228 break;
4229 case ICmpInst::ICMP_SGT:
4230 switch (RHSCC) {
4231 default: assert(0 && "Unknown integer condition code!");
4232 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4233 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4234 return ReplaceInstUsesWith(I, LHS);
4235 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4236 break;
4237 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4238 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4239 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4240 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4241 break;
4242 }
4243 break;
4244 }
4245 }
4246 }
4247
4248 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004249 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4251 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004252 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4253 !isa<ICmpInst>(Op1C->getOperand(0))) {
4254 const Type *SrcTy = Op0C->getOperand(0)->getType();
4255 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4256 // Only do this if the casts both really cause code to be
4257 // generated.
4258 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4259 I.getType(), TD) &&
4260 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4261 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004262 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004263 Op1C->getOperand(0),
4264 I.getName());
4265 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004266 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004267 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004268 }
4269 }
Chris Lattner91882432007-10-24 05:38:08 +00004270 }
4271
4272
4273 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4274 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4275 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4276 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004277 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4278 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004279 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4280 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4281 // If either of the constants are nans, then the whole thing returns
4282 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004283 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004284 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4285
4286 // Otherwise, no need to compare the two constants, compare the
4287 // rest.
4288 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4289 RHS->getOperand(0));
4290 }
4291 }
4292 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004293
4294 return Changed ? &I : 0;
4295}
4296
Dan Gohman089efff2008-05-13 00:00:25 +00004297namespace {
4298
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004299// XorSelf - Implements: X ^ X --> 0
4300struct XorSelf {
4301 Value *RHS;
4302 XorSelf(Value *rhs) : RHS(rhs) {}
4303 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4304 Instruction *apply(BinaryOperator &Xor) const {
4305 return &Xor;
4306 }
4307};
4308
Dan Gohman089efff2008-05-13 00:00:25 +00004309}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310
4311Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4312 bool Changed = SimplifyCommutative(I);
4313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4314
Evan Chenge5cd8032008-03-25 20:07:13 +00004315 if (isa<UndefValue>(Op1)) {
4316 if (isa<UndefValue>(Op0))
4317 // Handle undef ^ undef -> 0 special case. This is a common
4318 // idiom (misuse).
4319 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004321 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322
4323 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4324 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004325 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4327 }
4328
4329 // See if we can simplify any instructions used by the instruction whose sole
4330 // purpose is to compute bits we don't care about.
4331 if (!isa<VectorType>(I.getType())) {
4332 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4333 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4334 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4335 KnownZero, KnownOne))
4336 return &I;
4337 } else if (isa<ConstantAggregateZero>(Op1)) {
4338 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4339 }
4340
4341 // Is this a ~ operation?
4342 if (Value *NotOp = dyn_castNotVal(&I)) {
4343 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4344 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4345 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4346 if (Op0I->getOpcode() == Instruction::And ||
4347 Op0I->getOpcode() == Instruction::Or) {
4348 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4349 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4350 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004351 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004352 Op0I->getOperand(1)->getName()+".not");
4353 InsertNewInstBefore(NotY, I);
4354 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004355 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004356 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004357 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358 }
4359 }
4360 }
4361 }
4362
4363
4364 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004365 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4366 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4367 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368 return new ICmpInst(ICI->getInversePredicate(),
4369 ICI->getOperand(0), ICI->getOperand(1));
4370
Nick Lewycky1405e922007-08-06 20:04:16 +00004371 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4372 return new FCmpInst(FCI->getInversePredicate(),
4373 FCI->getOperand(0), FCI->getOperand(1));
4374 }
4375
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004376 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4377 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4378 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4379 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4380 Instruction::CastOps Opcode = Op0C->getOpcode();
4381 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4382 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4383 Op0C->getDestTy())) {
4384 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4385 CI->getOpcode(), CI->getInversePredicate(),
4386 CI->getOperand(0), CI->getOperand(1)), I);
4387 NewCI->takeName(CI);
4388 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4389 }
4390 }
4391 }
4392 }
4393 }
4394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4396 // ~(c-X) == X-c-1 == X+(-c-1)
4397 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4398 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4399 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4400 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4401 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004402 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403 }
4404
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004405 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406 if (Op0I->getOpcode() == Instruction::Add) {
4407 // ~(X-c) --> (-c-1)-X
4408 if (RHS->isAllOnesValue()) {
4409 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004410 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004411 ConstantExpr::getSub(NegOp0CI,
4412 ConstantInt::get(I.getType(), 1)),
4413 Op0I->getOperand(0));
4414 } else if (RHS->getValue().isSignBit()) {
4415 // (X + C) ^ signbit -> (X + C + signbit)
4416 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004417 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004418
4419 }
4420 } else if (Op0I->getOpcode() == Instruction::Or) {
4421 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4422 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4423 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4424 // Anything in both C1 and C2 is known to be zero, remove it from
4425 // NewRHS.
4426 Constant *CommonBits = And(Op0CI, RHS);
4427 NewRHS = ConstantExpr::getAnd(NewRHS,
4428 ConstantExpr::getNot(CommonBits));
4429 AddToWorkList(Op0I);
4430 I.setOperand(0, Op0I->getOperand(0));
4431 I.setOperand(1, NewRHS);
4432 return &I;
4433 }
4434 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 }
4437
4438 // Try to fold constant and into select arguments.
4439 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4440 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4441 return R;
4442 if (isa<PHINode>(Op0))
4443 if (Instruction *NV = FoldOpIntoPhi(I))
4444 return NV;
4445 }
4446
4447 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4448 if (X == Op1)
4449 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4450
4451 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4452 if (X == Op0)
4453 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4454
4455
4456 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4457 if (Op1I) {
4458 Value *A, *B;
4459 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4460 if (A == Op0) { // B^(B|A) == (A|B)^B
4461 Op1I->swapOperands();
4462 I.swapOperands();
4463 std::swap(Op0, Op1);
4464 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4465 I.swapOperands(); // Simplified below.
4466 std::swap(Op0, Op1);
4467 }
4468 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4469 if (Op0 == A) // A^(A^B) == B
4470 return ReplaceInstUsesWith(I, B);
4471 else if (Op0 == B) // A^(B^A) == B
4472 return ReplaceInstUsesWith(I, A);
4473 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4474 if (A == Op0) { // A^(A&B) -> A^(B&A)
4475 Op1I->swapOperands();
4476 std::swap(A, B);
4477 }
4478 if (B == Op0) { // A^(B&A) -> (B&A)^A
4479 I.swapOperands(); // Simplified below.
4480 std::swap(Op0, Op1);
4481 }
4482 }
4483 }
4484
4485 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4486 if (Op0I) {
4487 Value *A, *B;
4488 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4489 if (A == Op1) // (B|A)^B == (A|B)^B
4490 std::swap(A, B);
4491 if (B == Op1) { // (A|B)^B == A & ~B
4492 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004493 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4494 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004495 }
4496 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4497 if (Op1 == A) // (A^B)^A == B
4498 return ReplaceInstUsesWith(I, B);
4499 else if (Op1 == B) // (B^A)^A == B
4500 return ReplaceInstUsesWith(I, A);
4501 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4502 if (A == Op1) // (A&B)^A -> (B&A)^A
4503 std::swap(A, B);
4504 if (B == Op1 && // (B&A)^A == ~B & A
4505 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4506 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004507 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4508 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509 }
4510 }
4511 }
4512
4513 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4514 if (Op0I && Op1I && Op0I->isShift() &&
4515 Op0I->getOpcode() == Op1I->getOpcode() &&
4516 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4517 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4518 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004519 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004520 Op1I->getOperand(0),
4521 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004522 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 Op1I->getOperand(1));
4524 }
4525
4526 if (Op0I && Op1I) {
4527 Value *A, *B, *C, *D;
4528 // (A & B)^(A | B) -> A ^ B
4529 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4530 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4531 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004532 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004533 }
4534 // (A | B)^(A & B) -> A ^ B
4535 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4536 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4537 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004538 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004539 }
4540
4541 // (A & B)^(C & D)
4542 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4543 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4544 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4545 // (X & Y)^(X & Y) -> (Y^Z) & X
4546 Value *X = 0, *Y = 0, *Z = 0;
4547 if (A == C)
4548 X = A, Y = B, Z = D;
4549 else if (A == D)
4550 X = A, Y = B, Z = C;
4551 else if (B == C)
4552 X = B, Y = A, Z = D;
4553 else if (B == D)
4554 X = B, Y = A, Z = C;
4555
4556 if (X) {
4557 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004558 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4559 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004560 }
4561 }
4562 }
4563
4564 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4565 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4566 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4567 return R;
4568
4569 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004570 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004571 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4572 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4573 const Type *SrcTy = Op0C->getOperand(0)->getType();
4574 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4575 // Only do this if the casts both really cause code to be generated.
4576 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4577 I.getType(), TD) &&
4578 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4579 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004580 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004581 Op1C->getOperand(0),
4582 I.getName());
4583 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004584 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004585 }
4586 }
Chris Lattner91882432007-10-24 05:38:08 +00004587 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004588
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004589 return Changed ? &I : 0;
4590}
4591
4592/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4593/// overflowed for this type.
4594static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4595 ConstantInt *In2, bool IsSigned = false) {
4596 Result = cast<ConstantInt>(Add(In1, In2));
4597
4598 if (IsSigned)
4599 if (In2->getValue().isNegative())
4600 return Result->getValue().sgt(In1->getValue());
4601 else
4602 return Result->getValue().slt(In1->getValue());
4603 else
4604 return Result->getValue().ult(In1->getValue());
4605}
4606
4607/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4608/// code necessary to compute the offset from the base pointer (without adding
4609/// in the base pointer). Return the result as a signed integer of intptr size.
4610static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4611 TargetData &TD = IC.getTargetData();
4612 gep_type_iterator GTI = gep_type_begin(GEP);
4613 const Type *IntPtrTy = TD.getIntPtrType();
4614 Value *Result = Constant::getNullValue(IntPtrTy);
4615
4616 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004617 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004618 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4619
Gabor Greif17396002008-06-12 21:37:33 +00004620 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4621 ++i, ++GTI) {
4622 Value *Op = *i;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004623 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004624 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4625 if (OpC->isZero()) continue;
4626
4627 // Handle a struct index, which adds its field offset to the pointer.
4628 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4629 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4630
4631 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4632 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4633 else
4634 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004635 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004636 ConstantInt::get(IntPtrTy, Size),
4637 GEP->getName()+".offs"), I);
4638 continue;
4639 }
4640
4641 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4642 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4643 Scale = ConstantExpr::getMul(OC, Scale);
4644 if (Constant *RC = dyn_cast<Constant>(Result))
4645 Result = ConstantExpr::getAdd(RC, Scale);
4646 else {
4647 // Emit an add instruction.
4648 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004649 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004650 GEP->getName()+".offs"), I);
4651 }
4652 continue;
4653 }
4654 // Convert to correct type.
4655 if (Op->getType() != IntPtrTy) {
4656 if (Constant *OpC = dyn_cast<Constant>(Op))
4657 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4658 else
4659 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4660 Op->getName()+".c"), I);
4661 }
4662 if (Size != 1) {
4663 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4664 if (Constant *OpC = dyn_cast<Constant>(Op))
4665 Op = ConstantExpr::getMul(OpC, Scale);
4666 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004667 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004668 GEP->getName()+".idx"), I);
4669 }
4670
4671 // Emit an add instruction.
4672 if (isa<Constant>(Op) && isa<Constant>(Result))
4673 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4674 cast<Constant>(Result));
4675 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004676 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004677 GEP->getName()+".offs"), I);
4678 }
4679 return Result;
4680}
4681
Chris Lattnereba75862008-04-22 02:53:33 +00004682
4683/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4684/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4685/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4686/// complex, and scales are involved. The above expression would also be legal
4687/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4688/// later form is less amenable to optimization though, and we are allowed to
4689/// generate the first by knowing that pointer arithmetic doesn't overflow.
4690///
4691/// If we can't emit an optimized form for this expression, this returns null.
4692///
4693static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4694 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00004695 TargetData &TD = IC.getTargetData();
4696 gep_type_iterator GTI = gep_type_begin(GEP);
4697
4698 // Check to see if this gep only has a single variable index. If so, and if
4699 // any constant indices are a multiple of its scale, then we can compute this
4700 // in terms of the scale of the variable index. For example, if the GEP
4701 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4702 // because the expression will cross zero at the same point.
4703 unsigned i, e = GEP->getNumOperands();
4704 int64_t Offset = 0;
4705 for (i = 1; i != e; ++i, ++GTI) {
4706 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4707 // Compute the aggregate offset of constant indices.
4708 if (CI->isZero()) continue;
4709
4710 // Handle a struct index, which adds its field offset to the pointer.
4711 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4712 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4713 } else {
4714 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4715 Offset += Size*CI->getSExtValue();
4716 }
4717 } else {
4718 // Found our variable index.
4719 break;
4720 }
4721 }
4722
4723 // If there are no variable indices, we must have a constant offset, just
4724 // evaluate it the general way.
4725 if (i == e) return 0;
4726
4727 Value *VariableIdx = GEP->getOperand(i);
4728 // Determine the scale factor of the variable element. For example, this is
4729 // 4 if the variable index is into an array of i32.
4730 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4731
4732 // Verify that there are no other variable indices. If so, emit the hard way.
4733 for (++i, ++GTI; i != e; ++i, ++GTI) {
4734 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4735 if (!CI) return 0;
4736
4737 // Compute the aggregate offset of constant indices.
4738 if (CI->isZero()) continue;
4739
4740 // Handle a struct index, which adds its field offset to the pointer.
4741 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4742 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4743 } else {
4744 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4745 Offset += Size*CI->getSExtValue();
4746 }
4747 }
4748
4749 // Okay, we know we have a single variable index, which must be a
4750 // pointer/array/vector index. If there is no offset, life is simple, return
4751 // the index.
4752 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4753 if (Offset == 0) {
4754 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4755 // we don't need to bother extending: the extension won't affect where the
4756 // computation crosses zero.
4757 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4758 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4759 VariableIdx->getNameStart(), &I);
4760 return VariableIdx;
4761 }
4762
4763 // Otherwise, there is an index. The computation we will do will be modulo
4764 // the pointer size, so get it.
4765 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4766
4767 Offset &= PtrSizeMask;
4768 VariableScale &= PtrSizeMask;
4769
4770 // To do this transformation, any constant index must be a multiple of the
4771 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4772 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4773 // multiple of the variable scale.
4774 int64_t NewOffs = Offset / (int64_t)VariableScale;
4775 if (Offset != NewOffs*(int64_t)VariableScale)
4776 return 0;
4777
4778 // Okay, we can do this evaluation. Start by converting the index to intptr.
4779 const Type *IntPtrTy = TD.getIntPtrType();
4780 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00004781 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00004782 true /*SExt*/,
4783 VariableIdx->getNameStart(), &I);
4784 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00004785 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00004786}
4787
4788
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4790/// else. At this point we know that the GEP is on the LHS of the comparison.
4791Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4792 ICmpInst::Predicate Cond,
4793 Instruction &I) {
4794 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4795
Chris Lattnereba75862008-04-22 02:53:33 +00004796 // Look through bitcasts.
4797 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4798 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004799
4800 Value *PtrBase = GEPLHS->getOperand(0);
4801 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004802 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00004803 // This transformation (ignoring the base and scales) is valid because we
4804 // know pointers can't overflow. See if we can output an optimized form.
4805 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4806
4807 // If not, synthesize the offset the hard way.
4808 if (Offset == 0)
4809 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00004810 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4811 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004812 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4813 // If the base pointers are different, but the indices are the same, just
4814 // compare the base pointer.
4815 if (PtrBase != GEPRHS->getOperand(0)) {
4816 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4817 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4818 GEPRHS->getOperand(0)->getType();
4819 if (IndicesTheSame)
4820 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4821 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4822 IndicesTheSame = false;
4823 break;
4824 }
4825
4826 // If all indices are the same, just compare the base pointers.
4827 if (IndicesTheSame)
4828 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4829 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4830
4831 // Otherwise, the base pointers are different and the indices are
4832 // different, bail out.
4833 return 0;
4834 }
4835
4836 // If one of the GEPs has all zero indices, recurse.
4837 bool AllZeros = true;
4838 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4839 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4840 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4841 AllZeros = false;
4842 break;
4843 }
4844 if (AllZeros)
4845 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4846 ICmpInst::getSwappedPredicate(Cond), I);
4847
4848 // If the other GEP has all zero indices, recurse.
4849 AllZeros = true;
4850 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4851 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4852 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4853 AllZeros = false;
4854 break;
4855 }
4856 if (AllZeros)
4857 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4858
4859 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4860 // If the GEPs only differ by one index, compare it.
4861 unsigned NumDifferences = 0; // Keep track of # differences.
4862 unsigned DiffOperand = 0; // The operand that differs.
4863 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4864 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4865 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4866 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4867 // Irreconcilable differences.
4868 NumDifferences = 2;
4869 break;
4870 } else {
4871 if (NumDifferences++) break;
4872 DiffOperand = i;
4873 }
4874 }
4875
4876 if (NumDifferences == 0) // SAME GEP?
4877 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004878 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00004879 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00004880
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004881 else if (NumDifferences == 1) {
4882 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4883 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4884 // Make sure we do a signed comparison here.
4885 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4886 }
4887 }
4888
4889 // Only lower this if the icmp is the only user of the GEP or if we expect
4890 // the result to fold to a constant!
4891 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4892 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4893 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4894 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4895 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4896 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4897 }
4898 }
4899 return 0;
4900}
4901
Chris Lattnere6b62d92008-05-19 20:18:56 +00004902/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4903///
4904Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4905 Instruction *LHSI,
4906 Constant *RHSC) {
4907 if (!isa<ConstantFP>(RHSC)) return 0;
4908 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4909
4910 // Get the width of the mantissa. We don't want to hack on conversions that
4911 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00004912 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00004913 if (MantissaWidth == -1) return 0; // Unknown.
4914
4915 // Check to see that the input is converted from an integer type that is small
4916 // enough that preserves all bits. TODO: check here for "known" sign bits.
4917 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4918 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4919
4920 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4921 if (isa<UIToFPInst>(LHSI))
4922 ++InputSize;
4923
4924 // If the conversion would lose info, don't hack on this.
4925 if ((int)InputSize > MantissaWidth)
4926 return 0;
4927
4928 // Otherwise, we can potentially simplify the comparison. We know that it
4929 // will always come through as an integer value and we know the constant is
4930 // not a NAN (it would have been previously simplified).
4931 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4932
4933 ICmpInst::Predicate Pred;
4934 switch (I.getPredicate()) {
4935 default: assert(0 && "Unexpected predicate!");
4936 case FCmpInst::FCMP_UEQ:
4937 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4938 case FCmpInst::FCMP_UGT:
4939 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4940 case FCmpInst::FCMP_UGE:
4941 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4942 case FCmpInst::FCMP_ULT:
4943 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4944 case FCmpInst::FCMP_ULE:
4945 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4946 case FCmpInst::FCMP_UNE:
4947 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4948 case FCmpInst::FCMP_ORD:
4949 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4950 case FCmpInst::FCMP_UNO:
4951 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4952 }
4953
4954 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4955
4956 // Now we know that the APFloat is a normal number, zero or inf.
4957
Chris Lattnerf13ff492008-05-20 03:50:52 +00004958 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00004959 // comparing an i8 to 300.0.
4960 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4961
4962 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4963 // and large values.
4964 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4965 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4966 APFloat::rmNearestTiesToEven);
4967 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00004968 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4969 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004970 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4971 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4972 }
4973
4974 // See if the RHS value is < SignedMin.
4975 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4976 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4977 APFloat::rmNearestTiesToEven);
4978 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00004979 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4980 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004981 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4982 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4983 }
4984
4985 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4986 // it may still be fractional. See if it is fractional by casting the FP
4987 // value to the integer value and back, checking for equality. Don't do this
4988 // for zero, because -0.0 is not fractional.
4989 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4990 if (!RHS.isZero() &&
4991 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4992 // If we had a comparison against a fractional value, we have to adjust
4993 // the compare predicate and sometimes the value. RHSC is rounded towards
4994 // zero at this point.
4995 switch (Pred) {
4996 default: assert(0 && "Unexpected integer comparison!");
4997 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4998 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4999 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5000 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5001 case ICmpInst::ICMP_SLE:
5002 // (float)int <= 4.4 --> int <= 4
5003 // (float)int <= -4.4 --> int < -4
5004 if (RHS.isNegative())
5005 Pred = ICmpInst::ICMP_SLT;
5006 break;
5007 case ICmpInst::ICMP_SLT:
5008 // (float)int < -4.4 --> int < -4
5009 // (float)int < 4.4 --> int <= 4
5010 if (!RHS.isNegative())
5011 Pred = ICmpInst::ICMP_SLE;
5012 break;
5013 case ICmpInst::ICMP_SGT:
5014 // (float)int > 4.4 --> int > 4
5015 // (float)int > -4.4 --> int >= -4
5016 if (RHS.isNegative())
5017 Pred = ICmpInst::ICMP_SGE;
5018 break;
5019 case ICmpInst::ICMP_SGE:
5020 // (float)int >= -4.4 --> int >= -4
5021 // (float)int >= 4.4 --> int > 4
5022 if (!RHS.isNegative())
5023 Pred = ICmpInst::ICMP_SGT;
5024 break;
5025 }
5026 }
5027
5028 // Lower this FP comparison into an appropriate integer version of the
5029 // comparison.
5030 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5031}
5032
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005033Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5034 bool Changed = SimplifyCompare(I);
5035 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5036
5037 // Fold trivial predicates.
5038 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5039 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5040 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5041 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5042
5043 // Simplify 'fcmp pred X, X'
5044 if (Op0 == Op1) {
5045 switch (I.getPredicate()) {
5046 default: assert(0 && "Unknown predicate!");
5047 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5048 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5049 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5050 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5051 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5052 case FCmpInst::FCMP_OLT: // True if ordered and less than
5053 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5054 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5055
5056 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5057 case FCmpInst::FCMP_ULT: // True if unordered or less than
5058 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5059 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5060 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5061 I.setPredicate(FCmpInst::FCMP_UNO);
5062 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5063 return &I;
5064
5065 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5066 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5067 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5068 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5069 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5070 I.setPredicate(FCmpInst::FCMP_ORD);
5071 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5072 return &I;
5073 }
5074 }
5075
5076 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5077 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5078
5079 // Handle fcmp with constant RHS
5080 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005081 // If the constant is a nan, see if we can fold the comparison based on it.
5082 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5083 if (CFP->getValueAPF().isNaN()) {
5084 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5085 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005086 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5087 "Comparison must be either ordered or unordered!");
5088 // True if unordered.
5089 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005090 }
5091 }
5092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005093 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5094 switch (LHSI->getOpcode()) {
5095 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005096 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5097 // block. If in the same block, we're encouraging jump threading. If
5098 // not, we are just pessimizing the code by making an i1 phi.
5099 if (LHSI->getParent() == I.getParent())
5100 if (Instruction *NV = FoldOpIntoPhi(I))
5101 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005102 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005103 case Instruction::SIToFP:
5104 case Instruction::UIToFP:
5105 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5106 return NV;
5107 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005108 case Instruction::Select:
5109 // If either operand of the select is a constant, we can fold the
5110 // comparison into the select arms, which will cause one to be
5111 // constant folded and the select turned into a bitwise or.
5112 Value *Op1 = 0, *Op2 = 0;
5113 if (LHSI->hasOneUse()) {
5114 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5115 // Fold the known value into the constant operand.
5116 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5117 // Insert a new FCmp of the other select operand.
5118 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5119 LHSI->getOperand(2), RHSC,
5120 I.getName()), I);
5121 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5122 // Fold the known value into the constant operand.
5123 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5124 // Insert a new FCmp of the other select operand.
5125 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5126 LHSI->getOperand(1), RHSC,
5127 I.getName()), I);
5128 }
5129 }
5130
5131 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005132 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005133 break;
5134 }
5135 }
5136
5137 return Changed ? &I : 0;
5138}
5139
5140Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5141 bool Changed = SimplifyCompare(I);
5142 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5143 const Type *Ty = Op0->getType();
5144
5145 // icmp X, X
5146 if (Op0 == Op1)
5147 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005148 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005149
5150 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5151 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5154 // addresses never equal each other! We already know that Op0 != Op1.
5155 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5156 isa<ConstantPointerNull>(Op0)) &&
5157 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5158 isa<ConstantPointerNull>(Op1)))
5159 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005160 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005161
5162 // icmp's with boolean values can always be turned into bitwise operations
5163 if (Ty == Type::Int1Ty) {
5164 switch (I.getPredicate()) {
5165 default: assert(0 && "Invalid icmp instruction!");
5166 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005167 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005168 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005169 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005170 }
5171 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005172 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005173
5174 case ICmpInst::ICMP_UGT:
5175 case ICmpInst::ICMP_SGT:
5176 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5177 // FALL THROUGH
5178 case ICmpInst::ICMP_ULT:
5179 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005180 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005182 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005183 }
5184 case ICmpInst::ICMP_UGE:
5185 case ICmpInst::ICMP_SGE:
5186 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5187 // FALL THROUGH
5188 case ICmpInst::ICMP_ULE:
5189 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005190 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005192 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005193 }
5194 }
5195 }
5196
5197 // See if we are doing a comparison between a constant and an instruction that
5198 // can be folded into the comparison.
5199 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005200 Value *A, *B;
5201
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005202 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5203 if (I.isEquality() && CI->isNullValue() &&
5204 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5205 // (icmp cond A B) if cond is equality
5206 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005207 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 switch (I.getPredicate()) {
5210 default: break;
5211 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5212 if (CI->isMinValue(false))
5213 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5214 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5215 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5216 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5217 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5218 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5219 if (CI->isMinValue(true))
5220 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5221 ConstantInt::getAllOnesValue(Op0->getType()));
5222
5223 break;
5224
5225 case ICmpInst::ICMP_SLT:
5226 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5227 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5228 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5229 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5230 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5231 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5232 break;
5233
5234 case ICmpInst::ICMP_UGT:
5235 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5236 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5237 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5238 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5239 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5240 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5241
5242 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5243 if (CI->isMaxValue(true))
5244 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5245 ConstantInt::getNullValue(Op0->getType()));
5246 break;
5247
5248 case ICmpInst::ICMP_SGT:
5249 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5250 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5251 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5252 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5253 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5254 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5255 break;
5256
5257 case ICmpInst::ICMP_ULE:
5258 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5259 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5260 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5261 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5262 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5263 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5264 break;
5265
5266 case ICmpInst::ICMP_SLE:
5267 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5268 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5269 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5270 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5271 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5272 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5273 break;
5274
5275 case ICmpInst::ICMP_UGE:
5276 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5277 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5278 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5279 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5280 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5281 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5282 break;
5283
5284 case ICmpInst::ICMP_SGE:
5285 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5286 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5287 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5288 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5289 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5290 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5291 break;
5292 }
5293
5294 // If we still have a icmp le or icmp ge instruction, turn it into the
5295 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5296 // already been handled above, this requires little checking.
5297 //
5298 switch (I.getPredicate()) {
5299 default: break;
5300 case ICmpInst::ICMP_ULE:
5301 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5302 case ICmpInst::ICMP_SLE:
5303 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5304 case ICmpInst::ICMP_UGE:
5305 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5306 case ICmpInst::ICMP_SGE:
5307 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5308 }
5309
5310 // See if we can fold the comparison based on bits known to be zero or one
5311 // in the input. If this comparison is a normal comparison, it demands all
5312 // bits, if it is a sign bit comparison, it only demands the sign bit.
5313
5314 bool UnusedBit;
5315 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5316
5317 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5318 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5319 if (SimplifyDemandedBits(Op0,
5320 isSignBit ? APInt::getSignBit(BitWidth)
5321 : APInt::getAllOnesValue(BitWidth),
5322 KnownZero, KnownOne, 0))
5323 return &I;
5324
5325 // Given the known and unknown bits, compute a range that the LHS could be
5326 // in.
5327 if ((KnownOne | KnownZero) != 0) {
5328 // Compute the Min, Max and RHS values based on the known bits. For the
5329 // EQ and NE we use unsigned values.
5330 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5331 const APInt& RHSVal = CI->getValue();
5332 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5333 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5334 Max);
5335 } else {
5336 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5337 Max);
5338 }
5339 switch (I.getPredicate()) { // LE/GE have been folded already.
5340 default: assert(0 && "Unknown icmp opcode!");
5341 case ICmpInst::ICMP_EQ:
5342 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5343 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5344 break;
5345 case ICmpInst::ICMP_NE:
5346 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5347 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5348 break;
5349 case ICmpInst::ICMP_ULT:
5350 if (Max.ult(RHSVal))
5351 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5352 if (Min.uge(RHSVal))
5353 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5354 break;
5355 case ICmpInst::ICMP_UGT:
5356 if (Min.ugt(RHSVal))
5357 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5358 if (Max.ule(RHSVal))
5359 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5360 break;
5361 case ICmpInst::ICMP_SLT:
5362 if (Max.slt(RHSVal))
5363 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5364 if (Min.sgt(RHSVal))
5365 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5366 break;
5367 case ICmpInst::ICMP_SGT:
5368 if (Min.sgt(RHSVal))
5369 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5370 if (Max.sle(RHSVal))
5371 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5372 break;
5373 }
5374 }
5375
5376 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5377 // instruction, see if that instruction also has constants so that the
5378 // instruction can be folded into the icmp
5379 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5380 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5381 return Res;
5382 }
5383
5384 // Handle icmp with constant (but not simple integer constant) RHS
5385 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5386 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5387 switch (LHSI->getOpcode()) {
5388 case Instruction::GetElementPtr:
5389 if (RHSC->isNullValue()) {
5390 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5391 bool isAllZeros = true;
5392 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5393 if (!isa<Constant>(LHSI->getOperand(i)) ||
5394 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5395 isAllZeros = false;
5396 break;
5397 }
5398 if (isAllZeros)
5399 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5400 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5401 }
5402 break;
5403
5404 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005405 // Only fold icmp into the PHI if the phi and fcmp are in the same
5406 // block. If in the same block, we're encouraging jump threading. If
5407 // not, we are just pessimizing the code by making an i1 phi.
5408 if (LHSI->getParent() == I.getParent())
5409 if (Instruction *NV = FoldOpIntoPhi(I))
5410 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005411 break;
5412 case Instruction::Select: {
5413 // If either operand of the select is a constant, we can fold the
5414 // comparison into the select arms, which will cause one to be
5415 // constant folded and the select turned into a bitwise or.
5416 Value *Op1 = 0, *Op2 = 0;
5417 if (LHSI->hasOneUse()) {
5418 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5419 // Fold the known value into the constant operand.
5420 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5421 // Insert a new ICmp of the other select operand.
5422 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5423 LHSI->getOperand(2), RHSC,
5424 I.getName()), I);
5425 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5426 // Fold the known value into the constant operand.
5427 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5428 // Insert a new ICmp of the other select operand.
5429 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5430 LHSI->getOperand(1), RHSC,
5431 I.getName()), I);
5432 }
5433 }
5434
5435 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005436 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005437 break;
5438 }
5439 case Instruction::Malloc:
5440 // If we have (malloc != null), and if the malloc has a single use, we
5441 // can assume it is successful and remove the malloc.
5442 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5443 AddToWorkList(LHSI);
5444 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005445 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005446 }
5447 break;
5448 }
5449 }
5450
5451 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5452 if (User *GEP = dyn_castGetElementPtr(Op0))
5453 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5454 return NI;
5455 if (User *GEP = dyn_castGetElementPtr(Op1))
5456 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5457 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5458 return NI;
5459
5460 // Test to see if the operands of the icmp are casted versions of other
5461 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5462 // now.
5463 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5464 if (isa<PointerType>(Op0->getType()) &&
5465 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5466 // We keep moving the cast from the left operand over to the right
5467 // operand, where it can often be eliminated completely.
5468 Op0 = CI->getOperand(0);
5469
5470 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5471 // so eliminate it as well.
5472 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5473 Op1 = CI2->getOperand(0);
5474
5475 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005476 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005477 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5478 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5479 } else {
5480 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005481 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005482 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005483 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005484 return new ICmpInst(I.getPredicate(), Op0, Op1);
5485 }
5486 }
5487
5488 if (isa<CastInst>(Op0)) {
5489 // Handle the special case of: icmp (cast bool to X), <cst>
5490 // This comes up when you have code like
5491 // int X = A < B;
5492 // if (X) ...
5493 // For generality, we handle any zero-extension of any operand comparison
5494 // with a constant or another cast from the same type.
5495 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5496 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5497 return R;
5498 }
5499
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005500 // ~x < ~y --> y < x
5501 { Value *A, *B;
5502 if (match(Op0, m_Not(m_Value(A))) &&
5503 match(Op1, m_Not(m_Value(B))))
5504 return new ICmpInst(I.getPredicate(), B, A);
5505 }
5506
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005507 if (I.isEquality()) {
5508 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005509
5510 // -x == -y --> x == y
5511 if (match(Op0, m_Neg(m_Value(A))) &&
5512 match(Op1, m_Neg(m_Value(B))))
5513 return new ICmpInst(I.getPredicate(), A, B);
5514
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005515 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5516 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5517 Value *OtherVal = A == Op1 ? B : A;
5518 return new ICmpInst(I.getPredicate(), OtherVal,
5519 Constant::getNullValue(A->getType()));
5520 }
5521
5522 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5523 // A^c1 == C^c2 --> A == C^(c1^c2)
5524 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5525 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5526 if (Op1->hasOneUse()) {
5527 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005528 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005529 return new ICmpInst(I.getPredicate(), A,
5530 InsertNewInstBefore(Xor, I));
5531 }
5532
5533 // A^B == A^D -> B == D
5534 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5535 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5536 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5537 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5538 }
5539 }
5540
5541 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5542 (A == Op0 || B == Op0)) {
5543 // A == (A^B) -> B == 0
5544 Value *OtherVal = A == Op0 ? B : A;
5545 return new ICmpInst(I.getPredicate(), OtherVal,
5546 Constant::getNullValue(A->getType()));
5547 }
5548 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5549 // (A-B) == A -> B == 0
5550 return new ICmpInst(I.getPredicate(), B,
5551 Constant::getNullValue(B->getType()));
5552 }
5553 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5554 // A == (A-B) -> B == 0
5555 return new ICmpInst(I.getPredicate(), B,
5556 Constant::getNullValue(B->getType()));
5557 }
5558
5559 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5560 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5561 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5562 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5563 Value *X = 0, *Y = 0, *Z = 0;
5564
5565 if (A == C) {
5566 X = B; Y = D; Z = A;
5567 } else if (A == D) {
5568 X = B; Y = C; Z = A;
5569 } else if (B == C) {
5570 X = A; Y = D; Z = B;
5571 } else if (B == D) {
5572 X = A; Y = C; Z = B;
5573 }
5574
5575 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005576 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5577 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005578 I.setOperand(0, Op1);
5579 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5580 return &I;
5581 }
5582 }
5583 }
5584 return Changed ? &I : 0;
5585}
5586
5587
5588/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5589/// and CmpRHS are both known to be integer constants.
5590Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5591 ConstantInt *DivRHS) {
5592 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5593 const APInt &CmpRHSV = CmpRHS->getValue();
5594
5595 // FIXME: If the operand types don't match the type of the divide
5596 // then don't attempt this transform. The code below doesn't have the
5597 // logic to deal with a signed divide and an unsigned compare (and
5598 // vice versa). This is because (x /s C1) <s C2 produces different
5599 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5600 // (x /u C1) <u C2. Simply casting the operands and result won't
5601 // work. :( The if statement below tests that condition and bails
5602 // if it finds it.
5603 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5604 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5605 return 0;
5606 if (DivRHS->isZero())
5607 return 0; // The ProdOV computation fails on divide by zero.
5608
5609 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5610 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5611 // C2 (CI). By solving for X we can turn this into a range check
5612 // instead of computing a divide.
5613 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5614
5615 // Determine if the product overflows by seeing if the product is
5616 // not equal to the divide. Make sure we do the same kind of divide
5617 // as in the LHS instruction that we're folding.
5618 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5619 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5620
5621 // Get the ICmp opcode
5622 ICmpInst::Predicate Pred = ICI.getPredicate();
5623
5624 // Figure out the interval that is being checked. For example, a comparison
5625 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5626 // Compute this interval based on the constants involved and the signedness of
5627 // the compare/divide. This computes a half-open interval, keeping track of
5628 // whether either value in the interval overflows. After analysis each
5629 // overflow variable is set to 0 if it's corresponding bound variable is valid
5630 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5631 int LoOverflow = 0, HiOverflow = 0;
5632 ConstantInt *LoBound = 0, *HiBound = 0;
5633
5634
5635 if (!DivIsSigned) { // udiv
5636 // e.g. X/5 op 3 --> [15, 20)
5637 LoBound = Prod;
5638 HiOverflow = LoOverflow = ProdOV;
5639 if (!HiOverflow)
5640 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005641 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005642 if (CmpRHSV == 0) { // (X / pos) op 0
5643 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5644 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5645 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005646 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005647 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5648 HiOverflow = LoOverflow = ProdOV;
5649 if (!HiOverflow)
5650 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5651 } else { // (X / pos) op neg
5652 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5653 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5654 LoOverflow = AddWithOverflow(LoBound, Prod,
5655 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5656 HiBound = AddOne(Prod);
5657 HiOverflow = ProdOV ? -1 : 0;
5658 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005659 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005660 if (CmpRHSV == 0) { // (X / neg) op 0
5661 // e.g. X/-5 op 0 --> [-4, 5)
5662 LoBound = AddOne(DivRHS);
5663 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5664 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5665 HiOverflow = 1; // [INTMIN+1, overflow)
5666 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5667 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005668 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005669 // e.g. X/-5 op 3 --> [-19, -14)
5670 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5671 if (!LoOverflow)
5672 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5673 HiBound = AddOne(Prod);
5674 } else { // (X / neg) op neg
5675 // e.g. X/-5 op -3 --> [15, 20)
5676 LoBound = Prod;
5677 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5678 HiBound = Subtract(Prod, DivRHS);
5679 }
5680
5681 // Dividing by a negative swaps the condition. LT <-> GT
5682 Pred = ICmpInst::getSwappedPredicate(Pred);
5683 }
5684
5685 Value *X = DivI->getOperand(0);
5686 switch (Pred) {
5687 default: assert(0 && "Unhandled icmp opcode!");
5688 case ICmpInst::ICMP_EQ:
5689 if (LoOverflow && HiOverflow)
5690 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5691 else if (HiOverflow)
5692 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5693 ICmpInst::ICMP_UGE, X, LoBound);
5694 else if (LoOverflow)
5695 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5696 ICmpInst::ICMP_ULT, X, HiBound);
5697 else
5698 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5699 case ICmpInst::ICMP_NE:
5700 if (LoOverflow && HiOverflow)
5701 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5702 else if (HiOverflow)
5703 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5704 ICmpInst::ICMP_ULT, X, LoBound);
5705 else if (LoOverflow)
5706 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5707 ICmpInst::ICMP_UGE, X, HiBound);
5708 else
5709 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5710 case ICmpInst::ICMP_ULT:
5711 case ICmpInst::ICMP_SLT:
5712 if (LoOverflow == +1) // Low bound is greater than input range.
5713 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5714 if (LoOverflow == -1) // Low bound is less than input range.
5715 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5716 return new ICmpInst(Pred, X, LoBound);
5717 case ICmpInst::ICMP_UGT:
5718 case ICmpInst::ICMP_SGT:
5719 if (HiOverflow == +1) // High bound greater than input range.
5720 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5721 else if (HiOverflow == -1) // High bound less than input range.
5722 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5723 if (Pred == ICmpInst::ICMP_UGT)
5724 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5725 else
5726 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5727 }
5728}
5729
5730
5731/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5732///
5733Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5734 Instruction *LHSI,
5735 ConstantInt *RHS) {
5736 const APInt &RHSV = RHS->getValue();
5737
5738 switch (LHSI->getOpcode()) {
5739 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5740 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5741 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5742 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005743 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5744 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005745 Value *CompareVal = LHSI->getOperand(0);
5746
5747 // If the sign bit of the XorCST is not set, there is no change to
5748 // the operation, just stop using the Xor.
5749 if (!XorCST->getValue().isNegative()) {
5750 ICI.setOperand(0, CompareVal);
5751 AddToWorkList(LHSI);
5752 return &ICI;
5753 }
5754
5755 // Was the old condition true if the operand is positive?
5756 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5757
5758 // If so, the new one isn't.
5759 isTrueIfPositive ^= true;
5760
5761 if (isTrueIfPositive)
5762 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5763 else
5764 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5765 }
5766 }
5767 break;
5768 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5769 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5770 LHSI->getOperand(0)->hasOneUse()) {
5771 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5772
5773 // If the LHS is an AND of a truncating cast, we can widen the
5774 // and/compare to be the input width without changing the value
5775 // produced, eliminating a cast.
5776 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5777 // We can do this transformation if either the AND constant does not
5778 // have its sign bit set or if it is an equality comparison.
5779 // Extending a relational comparison when we're checking the sign
5780 // bit would not work.
5781 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005782 (ICI.isEquality() ||
5783 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005784 uint32_t BitWidth =
5785 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5786 APInt NewCST = AndCST->getValue();
5787 NewCST.zext(BitWidth);
5788 APInt NewCI = RHSV;
5789 NewCI.zext(BitWidth);
5790 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005791 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005792 ConstantInt::get(NewCST),LHSI->getName());
5793 InsertNewInstBefore(NewAnd, ICI);
5794 return new ICmpInst(ICI.getPredicate(), NewAnd,
5795 ConstantInt::get(NewCI));
5796 }
5797 }
5798
5799 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5800 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5801 // happens a LOT in code produced by the C front-end, for bitfield
5802 // access.
5803 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5804 if (Shift && !Shift->isShift())
5805 Shift = 0;
5806
5807 ConstantInt *ShAmt;
5808 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5809 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5810 const Type *AndTy = AndCST->getType(); // Type of the and.
5811
5812 // We can fold this as long as we can't shift unknown bits
5813 // into the mask. This can only happen with signed shift
5814 // rights, as they sign-extend.
5815 if (ShAmt) {
5816 bool CanFold = Shift->isLogicalShift();
5817 if (!CanFold) {
5818 // To test for the bad case of the signed shr, see if any
5819 // of the bits shifted in could be tested after the mask.
5820 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5821 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5822
5823 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5824 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5825 AndCST->getValue()) == 0)
5826 CanFold = true;
5827 }
5828
5829 if (CanFold) {
5830 Constant *NewCst;
5831 if (Shift->getOpcode() == Instruction::Shl)
5832 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5833 else
5834 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5835
5836 // Check to see if we are shifting out any of the bits being
5837 // compared.
5838 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5839 // If we shifted bits out, the fold is not going to work out.
5840 // As a special case, check to see if this means that the
5841 // result is always true or false now.
5842 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5843 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5844 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5845 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5846 } else {
5847 ICI.setOperand(1, NewCst);
5848 Constant *NewAndCST;
5849 if (Shift->getOpcode() == Instruction::Shl)
5850 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5851 else
5852 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5853 LHSI->setOperand(1, NewAndCST);
5854 LHSI->setOperand(0, Shift->getOperand(0));
5855 AddToWorkList(Shift); // Shift is dead.
5856 AddUsesToWorkList(ICI);
5857 return &ICI;
5858 }
5859 }
5860 }
5861
5862 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5863 // preferable because it allows the C<<Y expression to be hoisted out
5864 // of a loop if Y is invariant and X is not.
5865 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5866 ICI.isEquality() && !Shift->isArithmeticShift() &&
5867 isa<Instruction>(Shift->getOperand(0))) {
5868 // Compute C << Y.
5869 Value *NS;
5870 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005871 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005872 Shift->getOperand(1), "tmp");
5873 } else {
5874 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00005875 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005876 Shift->getOperand(1), "tmp");
5877 }
5878 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5879
5880 // Compute X & (C << Y).
5881 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005882 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005883 InsertNewInstBefore(NewAnd, ICI);
5884
5885 ICI.setOperand(0, NewAnd);
5886 return &ICI;
5887 }
5888 }
5889 break;
5890
5891 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5892 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5893 if (!ShAmt) break;
5894
5895 uint32_t TypeBits = RHSV.getBitWidth();
5896
5897 // Check that the shift amount is in range. If not, don't perform
5898 // undefined shifts. When the shift is visited it will be
5899 // simplified.
5900 if (ShAmt->uge(TypeBits))
5901 break;
5902
5903 if (ICI.isEquality()) {
5904 // If we are comparing against bits always shifted out, the
5905 // comparison cannot succeed.
5906 Constant *Comp =
5907 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5908 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5909 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5910 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5911 return ReplaceInstUsesWith(ICI, Cst);
5912 }
5913
5914 if (LHSI->hasOneUse()) {
5915 // Otherwise strength reduce the shift into an and.
5916 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5917 Constant *Mask =
5918 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5919
5920 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005921 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005922 Mask, LHSI->getName()+".mask");
5923 Value *And = InsertNewInstBefore(AndI, ICI);
5924 return new ICmpInst(ICI.getPredicate(), And,
5925 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5926 }
5927 }
5928
5929 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5930 bool TrueIfSigned = false;
5931 if (LHSI->hasOneUse() &&
5932 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5933 // (X << 31) <s 0 --> (X&1) != 0
5934 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5935 (TypeBits-ShAmt->getZExtValue()-1));
5936 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005937 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005938 Mask, LHSI->getName()+".mask");
5939 Value *And = InsertNewInstBefore(AndI, ICI);
5940
5941 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5942 And, Constant::getNullValue(And->getType()));
5943 }
5944 break;
5945 }
5946
5947 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5948 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005949 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005950 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00005951 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005952
Chris Lattner5ee84f82008-03-21 05:19:58 +00005953 // Check that the shift amount is in range. If not, don't perform
5954 // undefined shifts. When the shift is visited it will be
5955 // simplified.
5956 uint32_t TypeBits = RHSV.getBitWidth();
5957 if (ShAmt->uge(TypeBits))
5958 break;
5959
5960 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005961
Chris Lattner5ee84f82008-03-21 05:19:58 +00005962 // If we are comparing against bits always shifted out, the
5963 // comparison cannot succeed.
5964 APInt Comp = RHSV << ShAmtVal;
5965 if (LHSI->getOpcode() == Instruction::LShr)
5966 Comp = Comp.lshr(ShAmtVal);
5967 else
5968 Comp = Comp.ashr(ShAmtVal);
5969
5970 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5971 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5972 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5973 return ReplaceInstUsesWith(ICI, Cst);
5974 }
5975
5976 // Otherwise, check to see if the bits shifted out are known to be zero.
5977 // If so, we can compare against the unshifted value:
5978 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00005979 if (LHSI->hasOneUse() &&
5980 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005981 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5982 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5983 ConstantExpr::getShl(RHS, ShAmt));
5984 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985
Evan Chengfb9292a2008-04-23 00:38:06 +00005986 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005987 // Otherwise strength reduce the shift into an and.
5988 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5989 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005990
Chris Lattner5ee84f82008-03-21 05:19:58 +00005991 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005992 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005993 Mask, LHSI->getName()+".mask");
5994 Value *And = InsertNewInstBefore(AndI, ICI);
5995 return new ICmpInst(ICI.getPredicate(), And,
5996 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005997 }
5998 break;
5999 }
6000
6001 case Instruction::SDiv:
6002 case Instruction::UDiv:
6003 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6004 // Fold this div into the comparison, producing a range check.
6005 // Determine, based on the divide type, what the range is being
6006 // checked. If there is an overflow on the low or high side, remember
6007 // it, otherwise compute the range [low, hi) bounding the new value.
6008 // See: InsertRangeTest above for the kinds of replacements possible.
6009 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6010 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6011 DivRHS))
6012 return R;
6013 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006014
6015 case Instruction::Add:
6016 // Fold: icmp pred (add, X, C1), C2
6017
6018 if (!ICI.isEquality()) {
6019 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6020 if (!LHSC) break;
6021 const APInt &LHSV = LHSC->getValue();
6022
6023 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6024 .subtract(LHSV);
6025
6026 if (ICI.isSignedPredicate()) {
6027 if (CR.getLower().isSignBit()) {
6028 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6029 ConstantInt::get(CR.getUpper()));
6030 } else if (CR.getUpper().isSignBit()) {
6031 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6032 ConstantInt::get(CR.getLower()));
6033 }
6034 } else {
6035 if (CR.getLower().isMinValue()) {
6036 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6037 ConstantInt::get(CR.getUpper()));
6038 } else if (CR.getUpper().isMinValue()) {
6039 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6040 ConstantInt::get(CR.getLower()));
6041 }
6042 }
6043 }
6044 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006045 }
6046
6047 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6048 if (ICI.isEquality()) {
6049 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6050
6051 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6052 // the second operand is a constant, simplify a bit.
6053 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6054 switch (BO->getOpcode()) {
6055 case Instruction::SRem:
6056 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6057 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6058 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6059 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6060 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006061 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006062 BO->getName());
6063 InsertNewInstBefore(NewRem, ICI);
6064 return new ICmpInst(ICI.getPredicate(), NewRem,
6065 Constant::getNullValue(BO->getType()));
6066 }
6067 }
6068 break;
6069 case Instruction::Add:
6070 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6071 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6072 if (BO->hasOneUse())
6073 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6074 Subtract(RHS, BOp1C));
6075 } else if (RHSV == 0) {
6076 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6077 // efficiently invertible, or if the add has just this one use.
6078 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6079
6080 if (Value *NegVal = dyn_castNegVal(BOp1))
6081 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6082 else if (Value *NegVal = dyn_castNegVal(BOp0))
6083 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6084 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006085 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006086 InsertNewInstBefore(Neg, ICI);
6087 Neg->takeName(BO);
6088 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6089 }
6090 }
6091 break;
6092 case Instruction::Xor:
6093 // For the xor case, we can xor two constants together, eliminating
6094 // the explicit xor.
6095 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6097 ConstantExpr::getXor(RHS, BOC));
6098
6099 // FALLTHROUGH
6100 case Instruction::Sub:
6101 // Replace (([sub|xor] A, B) != 0) with (A != B)
6102 if (RHSV == 0)
6103 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6104 BO->getOperand(1));
6105 break;
6106
6107 case Instruction::Or:
6108 // If bits are being or'd in that are not present in the constant we
6109 // are comparing against, then the comparison could never succeed!
6110 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6111 Constant *NotCI = ConstantExpr::getNot(RHS);
6112 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6113 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6114 isICMP_NE));
6115 }
6116 break;
6117
6118 case Instruction::And:
6119 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6120 // If bits are being compared against that are and'd out, then the
6121 // comparison can never succeed!
6122 if ((RHSV & ~BOC->getValue()) != 0)
6123 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6124 isICMP_NE));
6125
6126 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6127 if (RHS == BOC && RHSV.isPowerOf2())
6128 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6129 ICmpInst::ICMP_NE, LHSI,
6130 Constant::getNullValue(RHS->getType()));
6131
6132 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006133 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006134 Value *X = BO->getOperand(0);
6135 Constant *Zero = Constant::getNullValue(X->getType());
6136 ICmpInst::Predicate pred = isICMP_NE ?
6137 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6138 return new ICmpInst(pred, X, Zero);
6139 }
6140
6141 // ((X & ~7) == 0) --> X < 8
6142 if (RHSV == 0 && isHighOnes(BOC)) {
6143 Value *X = BO->getOperand(0);
6144 Constant *NegX = ConstantExpr::getNeg(BOC);
6145 ICmpInst::Predicate pred = isICMP_NE ?
6146 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6147 return new ICmpInst(pred, X, NegX);
6148 }
6149 }
6150 default: break;
6151 }
6152 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6153 // Handle icmp {eq|ne} <intrinsic>, intcst.
6154 if (II->getIntrinsicID() == Intrinsic::bswap) {
6155 AddToWorkList(II);
6156 ICI.setOperand(0, II->getOperand(1));
6157 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6158 return &ICI;
6159 }
6160 }
6161 } else { // Not a ICMP_EQ/ICMP_NE
6162 // If the LHS is a cast from an integral value of the same size,
6163 // then since we know the RHS is a constant, try to simlify.
6164 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6165 Value *CastOp = Cast->getOperand(0);
6166 const Type *SrcTy = CastOp->getType();
6167 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6168 if (SrcTy->isInteger() &&
6169 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6170 // If this is an unsigned comparison, try to make the comparison use
6171 // smaller constant values.
6172 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6173 // X u< 128 => X s> -1
6174 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6175 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6176 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6177 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6178 // X u> 127 => X s< 0
6179 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6180 Constant::getNullValue(SrcTy));
6181 }
6182 }
6183 }
6184 }
6185 return 0;
6186}
6187
6188/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6189/// We only handle extending casts so far.
6190///
6191Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6192 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6193 Value *LHSCIOp = LHSCI->getOperand(0);
6194 const Type *SrcTy = LHSCIOp->getType();
6195 const Type *DestTy = LHSCI->getType();
6196 Value *RHSCIOp;
6197
6198 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6199 // integer type is the same size as the pointer type.
6200 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6201 getTargetData().getPointerSizeInBits() ==
6202 cast<IntegerType>(DestTy)->getBitWidth()) {
6203 Value *RHSOp = 0;
6204 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6205 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6206 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6207 RHSOp = RHSC->getOperand(0);
6208 // If the pointer types don't match, insert a bitcast.
6209 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006210 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006211 }
6212
6213 if (RHSOp)
6214 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6215 }
6216
6217 // The code below only handles extension cast instructions, so far.
6218 // Enforce this.
6219 if (LHSCI->getOpcode() != Instruction::ZExt &&
6220 LHSCI->getOpcode() != Instruction::SExt)
6221 return 0;
6222
6223 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6224 bool isSignedCmp = ICI.isSignedPredicate();
6225
6226 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6227 // Not an extension from the same type?
6228 RHSCIOp = CI->getOperand(0);
6229 if (RHSCIOp->getType() != LHSCIOp->getType())
6230 return 0;
6231
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006232 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006233 // and the other is a zext), then we can't handle this.
6234 if (CI->getOpcode() != LHSCI->getOpcode())
6235 return 0;
6236
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006237 // Deal with equality cases early.
6238 if (ICI.isEquality())
6239 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6240
6241 // A signed comparison of sign extended values simplifies into a
6242 // signed comparison.
6243 if (isSignedCmp && isSignedExt)
6244 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6245
6246 // The other three cases all fold into an unsigned comparison.
6247 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006248 }
6249
6250 // If we aren't dealing with a constant on the RHS, exit early
6251 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6252 if (!CI)
6253 return 0;
6254
6255 // Compute the constant that would happen if we truncated to SrcTy then
6256 // reextended to DestTy.
6257 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6258 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6259
6260 // If the re-extended constant didn't change...
6261 if (Res2 == CI) {
6262 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6263 // For example, we might have:
6264 // %A = sext short %X to uint
6265 // %B = icmp ugt uint %A, 1330
6266 // It is incorrect to transform this into
6267 // %B = icmp ugt short %X, 1330
6268 // because %A may have negative value.
6269 //
6270 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6271 // OR operation is EQ/NE.
6272 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6273 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6274 else
6275 return 0;
6276 }
6277
6278 // The re-extended constant changed so the constant cannot be represented
6279 // in the shorter type. Consequently, we cannot emit a simple comparison.
6280
6281 // First, handle some easy cases. We know the result cannot be equal at this
6282 // point so handle the ICI.isEquality() cases
6283 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6284 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6285 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6286 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6287
6288 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6289 // should have been folded away previously and not enter in here.
6290 Value *Result;
6291 if (isSignedCmp) {
6292 // We're performing a signed comparison.
6293 if (cast<ConstantInt>(CI)->getValue().isNegative())
6294 Result = ConstantInt::getFalse(); // X < (small) --> false
6295 else
6296 Result = ConstantInt::getTrue(); // X < (large) --> true
6297 } else {
6298 // We're performing an unsigned comparison.
6299 if (isSignedExt) {
6300 // We're performing an unsigned comp with a sign extended value.
6301 // This is true if the input is >= 0. [aka >s -1]
6302 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6303 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6304 NegOne, ICI.getName()), ICI);
6305 } else {
6306 // Unsigned extend & unsigned compare -> always true.
6307 Result = ConstantInt::getTrue();
6308 }
6309 }
6310
6311 // Finally, return the value computed.
6312 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6313 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6314 return ReplaceInstUsesWith(ICI, Result);
6315 } else {
6316 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6317 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6318 "ICmp should be folded!");
6319 if (Constant *CI = dyn_cast<Constant>(Result))
6320 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6321 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006322 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323 }
6324}
6325
6326Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6327 return commonShiftTransforms(I);
6328}
6329
6330Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6331 return commonShiftTransforms(I);
6332}
6333
6334Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006335 if (Instruction *R = commonShiftTransforms(I))
6336 return R;
6337
6338 Value *Op0 = I.getOperand(0);
6339
6340 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6341 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6342 if (CSI->isAllOnesValue())
6343 return ReplaceInstUsesWith(I, CSI);
6344
6345 // See if we can turn a signed shr into an unsigned shr.
6346 if (MaskedValueIsZero(Op0,
6347 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006348 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006349
6350 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006351}
6352
6353Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6354 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6356
6357 // shl X, 0 == X and shr X, 0 == X
6358 // shl 0, X == 0 and shr 0, X == 0
6359 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6360 Op0 == Constant::getNullValue(Op0->getType()))
6361 return ReplaceInstUsesWith(I, Op0);
6362
6363 if (isa<UndefValue>(Op0)) {
6364 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6365 return ReplaceInstUsesWith(I, Op0);
6366 else // undef << X -> 0, undef >>u X -> 0
6367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6368 }
6369 if (isa<UndefValue>(Op1)) {
6370 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6371 return ReplaceInstUsesWith(I, Op0);
6372 else // X << undef, X >>u undef -> 0
6373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6374 }
6375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006376 // Try to fold constant and into select arguments.
6377 if (isa<Constant>(Op0))
6378 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6379 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6380 return R;
6381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006382 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6383 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6384 return Res;
6385 return 0;
6386}
6387
6388Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6389 BinaryOperator &I) {
6390 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6391
6392 // See if we can simplify any instructions used by the instruction whose sole
6393 // purpose is to compute bits we don't care about.
6394 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6395 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6396 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6397 KnownZero, KnownOne))
6398 return &I;
6399
6400 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6401 // of a signed value.
6402 //
6403 if (Op1->uge(TypeBits)) {
6404 if (I.getOpcode() != Instruction::AShr)
6405 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6406 else {
6407 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6408 return &I;
6409 }
6410 }
6411
6412 // ((X*C1) << C2) == (X * (C1 << C2))
6413 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6414 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6415 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006416 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006417 ConstantExpr::getShl(BOOp, Op1));
6418
6419 // Try to fold constant and into select arguments.
6420 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6421 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6422 return R;
6423 if (isa<PHINode>(Op0))
6424 if (Instruction *NV = FoldOpIntoPhi(I))
6425 return NV;
6426
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006427 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6428 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6429 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6430 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6431 // place. Don't try to do this transformation in this case. Also, we
6432 // require that the input operand is a shift-by-constant so that we have
6433 // confidence that the shifts will get folded together. We could do this
6434 // xform in more cases, but it is unlikely to be profitable.
6435 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6436 isa<ConstantInt>(TrOp->getOperand(1))) {
6437 // Okay, we'll do this xform. Make the shift of shift.
6438 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006439 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006440 I.getName());
6441 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6442
6443 // For logical shifts, the truncation has the effect of making the high
6444 // part of the register be zeros. Emulate this by inserting an AND to
6445 // clear the top bits as needed. This 'and' will usually be zapped by
6446 // other xforms later if dead.
6447 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6448 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6449 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6450
6451 // The mask we constructed says what the trunc would do if occurring
6452 // between the shifts. We want to know the effect *after* the second
6453 // shift. We know that it is a logical shift by a constant, so adjust the
6454 // mask as appropriate.
6455 if (I.getOpcode() == Instruction::Shl)
6456 MaskV <<= Op1->getZExtValue();
6457 else {
6458 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6459 MaskV = MaskV.lshr(Op1->getZExtValue());
6460 }
6461
Gabor Greifa645dd32008-05-16 19:29:10 +00006462 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006463 TI->getName());
6464 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6465
6466 // Return the value truncated to the interesting size.
6467 return new TruncInst(And, I.getType());
6468 }
6469 }
6470
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006471 if (Op0->hasOneUse()) {
6472 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6473 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6474 Value *V1, *V2;
6475 ConstantInt *CC;
6476 switch (Op0BO->getOpcode()) {
6477 default: break;
6478 case Instruction::Add:
6479 case Instruction::And:
6480 case Instruction::Or:
6481 case Instruction::Xor: {
6482 // These operators commute.
6483 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6484 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6485 match(Op0BO->getOperand(1),
6486 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006487 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006488 Op0BO->getOperand(0), Op1,
6489 Op0BO->getName());
6490 InsertNewInstBefore(YS, I); // (Y << C)
6491 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006492 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006493 Op0BO->getOperand(1)->getName());
6494 InsertNewInstBefore(X, I); // (X + (Y << C))
6495 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006496 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006497 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6498 }
6499
6500 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6501 Value *Op0BOOp1 = Op0BO->getOperand(1);
6502 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6503 match(Op0BOOp1,
6504 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6505 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6506 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006507 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006508 Op0BO->getOperand(0), Op1,
6509 Op0BO->getName());
6510 InsertNewInstBefore(YS, I); // (Y << C)
6511 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006512 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006513 V1->getName()+".mask");
6514 InsertNewInstBefore(XM, I); // X & (CC << C)
6515
Gabor Greifa645dd32008-05-16 19:29:10 +00006516 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006517 }
6518 }
6519
6520 // FALL THROUGH.
6521 case Instruction::Sub: {
6522 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6523 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6524 match(Op0BO->getOperand(0),
6525 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006526 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006527 Op0BO->getOperand(1), Op1,
6528 Op0BO->getName());
6529 InsertNewInstBefore(YS, I); // (Y << C)
6530 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006531 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 Op0BO->getOperand(0)->getName());
6533 InsertNewInstBefore(X, I); // (X + (Y << C))
6534 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006535 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006536 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6537 }
6538
6539 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6540 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6541 match(Op0BO->getOperand(0),
6542 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6543 m_ConstantInt(CC))) && V2 == Op1 &&
6544 cast<BinaryOperator>(Op0BO->getOperand(0))
6545 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006546 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006547 Op0BO->getOperand(1), Op1,
6548 Op0BO->getName());
6549 InsertNewInstBefore(YS, I); // (Y << C)
6550 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006551 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006552 V1->getName()+".mask");
6553 InsertNewInstBefore(XM, I); // X & (CC << C)
6554
Gabor Greifa645dd32008-05-16 19:29:10 +00006555 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006556 }
6557
6558 break;
6559 }
6560 }
6561
6562
6563 // If the operand is an bitwise operator with a constant RHS, and the
6564 // shift is the only use, we can pull it out of the shift.
6565 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6566 bool isValid = true; // Valid only for And, Or, Xor
6567 bool highBitSet = false; // Transform if high bit of constant set?
6568
6569 switch (Op0BO->getOpcode()) {
6570 default: isValid = false; break; // Do not perform transform!
6571 case Instruction::Add:
6572 isValid = isLeftShift;
6573 break;
6574 case Instruction::Or:
6575 case Instruction::Xor:
6576 highBitSet = false;
6577 break;
6578 case Instruction::And:
6579 highBitSet = true;
6580 break;
6581 }
6582
6583 // If this is a signed shift right, and the high bit is modified
6584 // by the logical operation, do not perform the transformation.
6585 // The highBitSet boolean indicates the value of the high bit of
6586 // the constant which would cause it to be modified for this
6587 // operation.
6588 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006589 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591
6592 if (isValid) {
6593 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6594
6595 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006596 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006597 InsertNewInstBefore(NewShift, I);
6598 NewShift->takeName(Op0BO);
6599
Gabor Greifa645dd32008-05-16 19:29:10 +00006600 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 NewRHS);
6602 }
6603 }
6604 }
6605 }
6606
6607 // Find out if this is a shift of a shift by a constant.
6608 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6609 if (ShiftOp && !ShiftOp->isShift())
6610 ShiftOp = 0;
6611
6612 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6613 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6614 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6615 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6616 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6617 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6618 Value *X = ShiftOp->getOperand(0);
6619
6620 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6621 if (AmtSum > TypeBits)
6622 AmtSum = TypeBits;
6623
6624 const IntegerType *Ty = cast<IntegerType>(I.getType());
6625
6626 // Check for (X << c1) << c2 and (X >> c1) >> c2
6627 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006628 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 ConstantInt::get(Ty, AmtSum));
6630 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6631 I.getOpcode() == Instruction::AShr) {
6632 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006633 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6635 I.getOpcode() == Instruction::LShr) {
6636 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6637 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006638 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006639 InsertNewInstBefore(Shift, I);
6640
6641 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006642 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006643 }
6644
6645 // Okay, if we get here, one shift must be left, and the other shift must be
6646 // right. See if the amounts are equal.
6647 if (ShiftAmt1 == ShiftAmt2) {
6648 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6649 if (I.getOpcode() == Instruction::Shl) {
6650 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006651 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006652 }
6653 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6654 if (I.getOpcode() == Instruction::LShr) {
6655 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006656 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006657 }
6658 // We can simplify ((X << C) >>s C) into a trunc + sext.
6659 // NOTE: we could do this for any C, but that would make 'unusual' integer
6660 // types. For now, just stick to ones well-supported by the code
6661 // generators.
6662 const Type *SExtType = 0;
6663 switch (Ty->getBitWidth() - ShiftAmt1) {
6664 case 1 :
6665 case 8 :
6666 case 16 :
6667 case 32 :
6668 case 64 :
6669 case 128:
6670 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6671 break;
6672 default: break;
6673 }
6674 if (SExtType) {
6675 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6676 InsertNewInstBefore(NewTrunc, I);
6677 return new SExtInst(NewTrunc, Ty);
6678 }
6679 // Otherwise, we can't handle it yet.
6680 } else if (ShiftAmt1 < ShiftAmt2) {
6681 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6682
6683 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6684 if (I.getOpcode() == Instruction::Shl) {
6685 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6686 ShiftOp->getOpcode() == Instruction::AShr);
6687 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006688 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006689 InsertNewInstBefore(Shift, I);
6690
6691 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006692 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006693 }
6694
6695 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6696 if (I.getOpcode() == Instruction::LShr) {
6697 assert(ShiftOp->getOpcode() == Instruction::Shl);
6698 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006699 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006700 InsertNewInstBefore(Shift, I);
6701
6702 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006703 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704 }
6705
6706 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6707 } else {
6708 assert(ShiftAmt2 < ShiftAmt1);
6709 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6710
6711 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6712 if (I.getOpcode() == Instruction::Shl) {
6713 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6714 ShiftOp->getOpcode() == Instruction::AShr);
6715 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006716 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006717 ConstantInt::get(Ty, ShiftDiff));
6718 InsertNewInstBefore(Shift, I);
6719
6720 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006721 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006722 }
6723
6724 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6725 if (I.getOpcode() == Instruction::LShr) {
6726 assert(ShiftOp->getOpcode() == Instruction::Shl);
6727 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006728 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006729 InsertNewInstBefore(Shift, I);
6730
6731 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006732 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006733 }
6734
6735 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6736 }
6737 }
6738 return 0;
6739}
6740
6741
6742/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6743/// expression. If so, decompose it, returning some value X, such that Val is
6744/// X*Scale+Offset.
6745///
6746static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6747 int &Offset) {
6748 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6749 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6750 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006751 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006752 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006753 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6754 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6755 if (I->getOpcode() == Instruction::Shl) {
6756 // This is a value scaled by '1 << the shift amt'.
6757 Scale = 1U << RHS->getZExtValue();
6758 Offset = 0;
6759 return I->getOperand(0);
6760 } else if (I->getOpcode() == Instruction::Mul) {
6761 // This value is scaled by 'RHS'.
6762 Scale = RHS->getZExtValue();
6763 Offset = 0;
6764 return I->getOperand(0);
6765 } else if (I->getOpcode() == Instruction::Add) {
6766 // We have X+C. Check to see if we really have (X*C2)+C1,
6767 // where C1 is divisible by C2.
6768 unsigned SubScale;
6769 Value *SubVal =
6770 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6771 Offset += RHS->getZExtValue();
6772 Scale = SubScale;
6773 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006774 }
6775 }
6776 }
6777
6778 // Otherwise, we can't look past this.
6779 Scale = 1;
6780 Offset = 0;
6781 return Val;
6782}
6783
6784
6785/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6786/// try to eliminate the cast by moving the type information into the alloc.
6787Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6788 AllocationInst &AI) {
6789 const PointerType *PTy = cast<PointerType>(CI.getType());
6790
6791 // Remove any uses of AI that are dead.
6792 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6793
6794 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6795 Instruction *User = cast<Instruction>(*UI++);
6796 if (isInstructionTriviallyDead(User)) {
6797 while (UI != E && *UI == User)
6798 ++UI; // If this instruction uses AI more than once, don't break UI.
6799
6800 ++NumDeadInst;
6801 DOUT << "IC: DCE: " << *User;
6802 EraseInstFromFunction(*User);
6803 }
6804 }
6805
6806 // Get the type really allocated and the type casted to.
6807 const Type *AllocElTy = AI.getAllocatedType();
6808 const Type *CastElTy = PTy->getElementType();
6809 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6810
6811 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6812 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6813 if (CastElTyAlign < AllocElTyAlign) return 0;
6814
6815 // If the allocation has multiple uses, only promote it if we are strictly
6816 // increasing the alignment of the resultant allocation. If we keep it the
6817 // same, we open the door to infinite loops of various kinds.
6818 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6819
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006820 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6821 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006822 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6823
6824 // See if we can satisfy the modulus by pulling a scale out of the array
6825 // size argument.
6826 unsigned ArraySizeScale;
6827 int ArrayOffset;
6828 Value *NumElements = // See if the array size is a decomposable linear expr.
6829 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6830
6831 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6832 // do the xform.
6833 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6834 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6835
6836 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6837 Value *Amt = 0;
6838 if (Scale == 1) {
6839 Amt = NumElements;
6840 } else {
6841 // If the allocation size is constant, form a constant mul expression
6842 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6843 if (isa<ConstantInt>(NumElements))
6844 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6845 // otherwise multiply the amount and the number of elements
6846 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006847 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006848 Amt = InsertNewInstBefore(Tmp, AI);
6849 }
6850 }
6851
6852 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6853 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00006854 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006855 Amt = InsertNewInstBefore(Tmp, AI);
6856 }
6857
6858 AllocationInst *New;
6859 if (isa<MallocInst>(AI))
6860 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6861 else
6862 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6863 InsertNewInstBefore(New, AI);
6864 New->takeName(&AI);
6865
6866 // If the allocation has multiple uses, insert a cast and change all things
6867 // that used it to use the new cast. This will also hack on CI, but it will
6868 // die soon.
6869 if (!AI.hasOneUse()) {
6870 AddUsesToWorkList(AI);
6871 // New is the allocation instruction, pointer typed. AI is the original
6872 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6873 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6874 InsertNewInstBefore(NewCast, AI);
6875 AI.replaceAllUsesWith(NewCast);
6876 }
6877 return ReplaceInstUsesWith(CI, New);
6878}
6879
6880/// CanEvaluateInDifferentType - Return true if we can take the specified value
6881/// and return it as type Ty without inserting any new casts and without
6882/// changing the computed value. This is used by code that tries to decide
6883/// whether promoting or shrinking integer operations to wider or smaller types
6884/// will allow us to eliminate a truncate or extend.
6885///
6886/// This is a truncation operation if Ty is smaller than V->getType(), or an
6887/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00006888///
6889/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6890/// should return true if trunc(V) can be computed by computing V in the smaller
6891/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6892/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6893/// efficiently truncated.
6894///
6895/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6896/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6897/// the final result.
Dan Gohman2d648bb2008-04-10 18:43:06 +00006898bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6899 unsigned CastOpc,
6900 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006901 // We can always evaluate constants in another type.
6902 if (isa<ConstantInt>(V))
6903 return true;
6904
6905 Instruction *I = dyn_cast<Instruction>(V);
6906 if (!I) return false;
6907
6908 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6909
Chris Lattneref70bb82007-08-02 06:11:14 +00006910 // If this is an extension or truncate, we can often eliminate it.
6911 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6912 // If this is a cast from the destination type, we can trivially eliminate
6913 // it, and this will remove a cast overall.
6914 if (I->getOperand(0)->getType() == Ty) {
6915 // If the first operand is itself a cast, and is eliminable, do not count
6916 // this as an eliminable cast. We would prefer to eliminate those two
6917 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00006918 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00006919 ++NumCastsRemoved;
6920 return true;
6921 }
6922 }
6923
6924 // We can't extend or shrink something that has multiple uses: doing so would
6925 // require duplicating the instruction in general, which isn't profitable.
6926 if (!I->hasOneUse()) return false;
6927
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006928 switch (I->getOpcode()) {
6929 case Instruction::Add:
6930 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00006931 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006932 case Instruction::And:
6933 case Instruction::Or:
6934 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006935 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6937 NumCastsRemoved) &&
6938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6939 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006940
6941 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006942 // If we are truncating the result of this SHL, and if it's a shift of a
6943 // constant amount, we can always perform a SHL in a smaller type.
6944 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6945 uint32_t BitWidth = Ty->getBitWidth();
6946 if (BitWidth < OrigTy->getBitWidth() &&
6947 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006948 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6949 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006950 }
6951 break;
6952 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006953 // If this is a truncate of a logical shr, we can truncate it to a smaller
6954 // lshr iff we know that the bits we would otherwise be shifting in are
6955 // already zeros.
6956 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6957 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6958 uint32_t BitWidth = Ty->getBitWidth();
6959 if (BitWidth < OrigBitWidth &&
6960 MaskedValueIsZero(I->getOperand(0),
6961 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6962 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006963 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6964 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965 }
6966 }
6967 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006968 case Instruction::ZExt:
6969 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006970 case Instruction::Trunc:
6971 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006972 // can safely replace it. Note that replacing it does not reduce the number
6973 // of casts in the input.
6974 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006975 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006976 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00006977 case Instruction::Select: {
6978 SelectInst *SI = cast<SelectInst>(I);
6979 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
6980 NumCastsRemoved) &&
6981 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
6982 NumCastsRemoved);
6983 }
Chris Lattner4200c2062008-06-18 04:00:49 +00006984 case Instruction::PHI: {
6985 // We can change a phi if we can change all operands.
6986 PHINode *PN = cast<PHINode>(I);
6987 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6988 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6989 NumCastsRemoved))
6990 return false;
6991 return true;
6992 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006993 default:
6994 // TODO: Can handle more cases here.
6995 break;
6996 }
6997
6998 return false;
6999}
7000
7001/// EvaluateInDifferentType - Given an expression that
7002/// CanEvaluateInDifferentType returns true for, actually insert the code to
7003/// evaluate the expression.
7004Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7005 bool isSigned) {
7006 if (Constant *C = dyn_cast<Constant>(V))
7007 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7008
7009 // Otherwise, it must be an instruction.
7010 Instruction *I = cast<Instruction>(V);
7011 Instruction *Res = 0;
7012 switch (I->getOpcode()) {
7013 case Instruction::Add:
7014 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007015 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007016 case Instruction::And:
7017 case Instruction::Or:
7018 case Instruction::Xor:
7019 case Instruction::AShr:
7020 case Instruction::LShr:
7021 case Instruction::Shl: {
7022 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7023 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007024 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner4200c2062008-06-18 04:00:49 +00007025 LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007026 break;
7027 }
7028 case Instruction::Trunc:
7029 case Instruction::ZExt:
7030 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007031 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007032 // just return the source. There's no need to insert it because it is not
7033 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007034 if (I->getOperand(0)->getType() == Ty)
7035 return I->getOperand(0);
7036
Chris Lattner4200c2062008-06-18 04:00:49 +00007037 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007038 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007039 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007040 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007041 case Instruction::Select: {
7042 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7043 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7044 Res = SelectInst::Create(I->getOperand(0), True, False);
7045 break;
7046 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007047 case Instruction::PHI: {
7048 PHINode *OPN = cast<PHINode>(I);
7049 PHINode *NPN = PHINode::Create(Ty);
7050 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7051 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7052 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7053 }
7054 Res = NPN;
7055 break;
7056 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007057 default:
7058 // TODO: Can handle more cases here.
7059 assert(0 && "Unreachable!");
7060 break;
7061 }
7062
Chris Lattner4200c2062008-06-18 04:00:49 +00007063 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007064 return InsertNewInstBefore(Res, *I);
7065}
7066
7067/// @brief Implement the transforms common to all CastInst visitors.
7068Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7069 Value *Src = CI.getOperand(0);
7070
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007071 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7072 // eliminate it now.
7073 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7074 if (Instruction::CastOps opc =
7075 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7076 // The first cast (CSrc) is eliminable so we need to fix up or replace
7077 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007078 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007079 }
7080 }
7081
7082 // If we are casting a select then fold the cast into the select
7083 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7084 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7085 return NV;
7086
7087 // If we are casting a PHI then fold the cast into the PHI
7088 if (isa<PHINode>(Src))
7089 if (Instruction *NV = FoldOpIntoPhi(CI))
7090 return NV;
7091
7092 return 0;
7093}
7094
7095/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7096Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7097 Value *Src = CI.getOperand(0);
7098
7099 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7100 // If casting the result of a getelementptr instruction with no offset, turn
7101 // this into a cast of the original pointer!
7102 if (GEP->hasAllZeroIndices()) {
7103 // Changing the cast operand is usually not a good idea but it is safe
7104 // here because the pointer operand is being replaced with another
7105 // pointer operand so the opcode doesn't need to change.
7106 AddToWorkList(GEP);
7107 CI.setOperand(0, GEP->getOperand(0));
7108 return &CI;
7109 }
7110
7111 // If the GEP has a single use, and the base pointer is a bitcast, and the
7112 // GEP computes a constant offset, see if we can convert these three
7113 // instructions into fewer. This typically happens with unions and other
7114 // non-type-safe code.
7115 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7116 if (GEP->hasAllConstantIndices()) {
7117 // We are guaranteed to get a constant from EmitGEPOffset.
7118 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7119 int64_t Offset = OffsetV->getSExtValue();
7120
7121 // Get the base pointer input of the bitcast, and the type it points to.
7122 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7123 const Type *GEPIdxTy =
7124 cast<PointerType>(OrigBase->getType())->getElementType();
7125 if (GEPIdxTy->isSized()) {
7126 SmallVector<Value*, 8> NewIndices;
7127
7128 // Start with the index over the outer type. Note that the type size
7129 // might be zero (even if the offset isn't zero) if the indexed type
7130 // is something like [0 x {int, int}]
7131 const Type *IntPtrTy = TD->getIntPtrType();
7132 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007133 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007134 FirstIdx = Offset/TySize;
7135 Offset %= TySize;
7136
7137 // Handle silly modulus not returning values values [0..TySize).
7138 if (Offset < 0) {
7139 --FirstIdx;
7140 Offset += TySize;
7141 assert(Offset >= 0);
7142 }
7143 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7144 }
7145
7146 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7147
7148 // Index into the types. If we fail, set OrigBase to null.
7149 while (Offset) {
7150 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7151 const StructLayout *SL = TD->getStructLayout(STy);
7152 if (Offset < (int64_t)SL->getSizeInBytes()) {
7153 unsigned Elt = SL->getElementContainingOffset(Offset);
7154 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7155
7156 Offset -= SL->getElementOffset(Elt);
7157 GEPIdxTy = STy->getElementType(Elt);
7158 } else {
7159 // Otherwise, we can't index into this, bail out.
7160 Offset = 0;
7161 OrigBase = 0;
7162 }
7163 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7164 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007165 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007166 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7167 Offset %= EltSize;
7168 } else {
7169 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7170 }
7171 GEPIdxTy = STy->getElementType();
7172 } else {
7173 // Otherwise, we can't index into this, bail out.
7174 Offset = 0;
7175 OrigBase = 0;
7176 }
7177 }
7178 if (OrigBase) {
7179 // If we were able to index down into an element, create the GEP
7180 // and bitcast the result. This eliminates one bitcast, potentially
7181 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007182 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7183 NewIndices.begin(),
7184 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007185 InsertNewInstBefore(NGEP, CI);
7186 NGEP->takeName(GEP);
7187
7188 if (isa<BitCastInst>(CI))
7189 return new BitCastInst(NGEP, CI.getType());
7190 assert(isa<PtrToIntInst>(CI));
7191 return new PtrToIntInst(NGEP, CI.getType());
7192 }
7193 }
7194 }
7195 }
7196 }
7197
7198 return commonCastTransforms(CI);
7199}
7200
7201
7202
7203/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7204/// integer types. This function implements the common transforms for all those
7205/// cases.
7206/// @brief Implement the transforms common to CastInst with integer operands
7207Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7208 if (Instruction *Result = commonCastTransforms(CI))
7209 return Result;
7210
7211 Value *Src = CI.getOperand(0);
7212 const Type *SrcTy = Src->getType();
7213 const Type *DestTy = CI.getType();
7214 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7215 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7216
7217 // See if we can simplify any instructions used by the LHS whose sole
7218 // purpose is to compute bits we don't care about.
7219 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7220 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7221 KnownZero, KnownOne))
7222 return &CI;
7223
7224 // If the source isn't an instruction or has more than one use then we
7225 // can't do anything more.
7226 Instruction *SrcI = dyn_cast<Instruction>(Src);
7227 if (!SrcI || !Src->hasOneUse())
7228 return 0;
7229
7230 // Attempt to propagate the cast into the instruction for int->int casts.
7231 int NumCastsRemoved = 0;
7232 if (!isa<BitCastInst>(CI) &&
7233 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007234 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007235 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007236 // eliminates the cast, so it is always a win. If this is a zero-extension,
7237 // we need to do an AND to maintain the clear top-part of the computation,
7238 // so we require that the input have eliminated at least one cast. If this
7239 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007240 // require that two casts have been eliminated.
7241 bool DoXForm;
7242 switch (CI.getOpcode()) {
7243 default:
7244 // All the others use floating point so we shouldn't actually
7245 // get here because of the check above.
7246 assert(0 && "Unknown cast type");
7247 case Instruction::Trunc:
7248 DoXForm = true;
7249 break;
7250 case Instruction::ZExt:
7251 DoXForm = NumCastsRemoved >= 1;
7252 break;
7253 case Instruction::SExt:
7254 DoXForm = NumCastsRemoved >= 2;
7255 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007256 }
7257
7258 if (DoXForm) {
7259 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7260 CI.getOpcode() == Instruction::SExt);
7261 assert(Res->getType() == DestTy);
7262 switch (CI.getOpcode()) {
7263 default: assert(0 && "Unknown cast type!");
7264 case Instruction::Trunc:
7265 case Instruction::BitCast:
7266 // Just replace this cast with the result.
7267 return ReplaceInstUsesWith(CI, Res);
7268 case Instruction::ZExt: {
7269 // We need to emit an AND to clear the high bits.
7270 assert(SrcBitSize < DestBitSize && "Not a zext?");
7271 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7272 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007273 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007274 }
7275 case Instruction::SExt:
7276 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007277 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007278 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7279 CI), DestTy);
7280 }
7281 }
7282 }
7283
7284 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7285 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7286
7287 switch (SrcI->getOpcode()) {
7288 case Instruction::Add:
7289 case Instruction::Mul:
7290 case Instruction::And:
7291 case Instruction::Or:
7292 case Instruction::Xor:
7293 // If we are discarding information, rewrite.
7294 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7295 // Don't insert two casts if they cannot be eliminated. We allow
7296 // two casts to be inserted if the sizes are the same. This could
7297 // only be converting signedness, which is a noop.
7298 if (DestBitSize == SrcBitSize ||
7299 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7300 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7301 Instruction::CastOps opcode = CI.getOpcode();
7302 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7303 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007304 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7306 }
7307 }
7308
7309 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7310 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7311 SrcI->getOpcode() == Instruction::Xor &&
7312 Op1 == ConstantInt::getTrue() &&
7313 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7314 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007315 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007316 }
7317 break;
7318 case Instruction::SDiv:
7319 case Instruction::UDiv:
7320 case Instruction::SRem:
7321 case Instruction::URem:
7322 // If we are just changing the sign, rewrite.
7323 if (DestBitSize == SrcBitSize) {
7324 // Don't insert two casts if they cannot be eliminated. We allow
7325 // two casts to be inserted if the sizes are the same. This could
7326 // only be converting signedness, which is a noop.
7327 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7328 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7329 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7330 Op0, DestTy, SrcI);
7331 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7332 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007333 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007334 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7335 }
7336 }
7337 break;
7338
7339 case Instruction::Shl:
7340 // Allow changing the sign of the source operand. Do not allow
7341 // changing the size of the shift, UNLESS the shift amount is a
7342 // constant. We must not change variable sized shifts to a smaller
7343 // size, because it is undefined to shift more bits out than exist
7344 // in the value.
7345 if (DestBitSize == SrcBitSize ||
7346 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7347 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7348 Instruction::BitCast : Instruction::Trunc);
7349 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7350 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007351 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007352 }
7353 break;
7354 case Instruction::AShr:
7355 // If this is a signed shr, and if all bits shifted in are about to be
7356 // truncated off, turn it into an unsigned shr to allow greater
7357 // simplifications.
7358 if (DestBitSize < SrcBitSize &&
7359 isa<ConstantInt>(Op1)) {
7360 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7361 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7362 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007363 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007364 }
7365 }
7366 break;
7367 }
7368 return 0;
7369}
7370
7371Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7372 if (Instruction *Result = commonIntCastTransforms(CI))
7373 return Result;
7374
7375 Value *Src = CI.getOperand(0);
7376 const Type *Ty = CI.getType();
7377 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7378 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7379
7380 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7381 switch (SrcI->getOpcode()) {
7382 default: break;
7383 case Instruction::LShr:
7384 // We can shrink lshr to something smaller if we know the bits shifted in
7385 // are already zeros.
7386 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7387 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7388
7389 // Get a mask for the bits shifting in.
7390 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7391 Value* SrcIOp0 = SrcI->getOperand(0);
7392 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7393 if (ShAmt >= DestBitWidth) // All zeros.
7394 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7395
7396 // Okay, we can shrink this. Truncate the input, then return a new
7397 // shift.
7398 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7399 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7400 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007401 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007402 }
7403 } else { // This is a variable shr.
7404
7405 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7406 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7407 // loop-invariant and CSE'd.
7408 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7409 Value *One = ConstantInt::get(SrcI->getType(), 1);
7410
7411 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007412 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007413 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007414 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007415 SrcI->getOperand(0),
7416 "tmp"), CI);
7417 Value *Zero = Constant::getNullValue(V->getType());
7418 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7419 }
7420 }
7421 break;
7422 }
7423 }
7424
7425 return 0;
7426}
7427
Evan Chenge3779cf2008-03-24 00:21:34 +00007428/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7429/// in order to eliminate the icmp.
7430Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7431 bool DoXform) {
7432 // If we are just checking for a icmp eq of a single bit and zext'ing it
7433 // to an integer, then shift the bit to the appropriate place and then
7434 // cast to integer to avoid the comparison.
7435 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7436 const APInt &Op1CV = Op1C->getValue();
7437
7438 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7439 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7440 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7441 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7442 if (!DoXform) return ICI;
7443
7444 Value *In = ICI->getOperand(0);
7445 Value *Sh = ConstantInt::get(In->getType(),
7446 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007447 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007448 In->getName()+".lobit"),
7449 CI);
7450 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007451 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007452 false/*ZExt*/, "tmp", &CI);
7453
7454 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7455 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007456 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007457 In->getName()+".not"),
7458 CI);
7459 }
7460
7461 return ReplaceInstUsesWith(CI, In);
7462 }
7463
7464
7465
7466 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7467 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7468 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7469 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7470 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7471 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7472 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7473 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7474 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7475 // This only works for EQ and NE
7476 ICI->isEquality()) {
7477 // If Op1C some other power of two, convert:
7478 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7479 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7480 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7481 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7482
7483 APInt KnownZeroMask(~KnownZero);
7484 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7485 if (!DoXform) return ICI;
7486
7487 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7488 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7489 // (X&4) == 2 --> false
7490 // (X&4) != 2 --> true
7491 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7492 Res = ConstantExpr::getZExt(Res, CI.getType());
7493 return ReplaceInstUsesWith(CI, Res);
7494 }
7495
7496 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7497 Value *In = ICI->getOperand(0);
7498 if (ShiftAmt) {
7499 // Perform a logical shr by shiftamt.
7500 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007501 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007502 ConstantInt::get(In->getType(), ShiftAmt),
7503 In->getName()+".lobit"), CI);
7504 }
7505
7506 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7507 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007508 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007509 InsertNewInstBefore(cast<Instruction>(In), CI);
7510 }
7511
7512 if (CI.getType() == In->getType())
7513 return ReplaceInstUsesWith(CI, In);
7514 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007515 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007516 }
7517 }
7518 }
7519
7520 return 0;
7521}
7522
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7524 // If one of the common conversion will work ..
7525 if (Instruction *Result = commonIntCastTransforms(CI))
7526 return Result;
7527
7528 Value *Src = CI.getOperand(0);
7529
7530 // If this is a cast of a cast
7531 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7532 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7533 // types and if the sizes are just right we can convert this into a logical
7534 // 'and' which will be much cheaper than the pair of casts.
7535 if (isa<TruncInst>(CSrc)) {
7536 // Get the sizes of the types involved
7537 Value *A = CSrc->getOperand(0);
7538 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7539 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7540 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7541 // If we're actually extending zero bits and the trunc is a no-op
7542 if (MidSize < DstSize && SrcSize == DstSize) {
7543 // Replace both of the casts with an And of the type mask.
7544 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7545 Constant *AndConst = ConstantInt::get(AndValue);
7546 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007547 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007548 // Unfortunately, if the type changed, we need to cast it back.
7549 if (And->getType() != CI.getType()) {
7550 And->setName(CSrc->getName()+".mask");
7551 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007552 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 }
7554 return And;
7555 }
7556 }
7557 }
7558
Evan Chenge3779cf2008-03-24 00:21:34 +00007559 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7560 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007561
Evan Chenge3779cf2008-03-24 00:21:34 +00007562 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7563 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7564 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7565 // of the (zext icmp) will be transformed.
7566 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7567 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7568 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7569 (transformZExtICmp(LHS, CI, false) ||
7570 transformZExtICmp(RHS, CI, false))) {
7571 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7572 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007573 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007575 }
7576
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007577 return 0;
7578}
7579
7580Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7581 if (Instruction *I = commonIntCastTransforms(CI))
7582 return I;
7583
7584 Value *Src = CI.getOperand(0);
7585
7586 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7587 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7588 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7589 // If we are just checking for a icmp eq of a single bit and zext'ing it
7590 // to an integer, then shift the bit to the appropriate place and then
7591 // cast to integer to avoid the comparison.
7592 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7593 const APInt &Op1CV = Op1C->getValue();
7594
7595 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7596 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7597 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7598 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7599 Value *In = ICI->getOperand(0);
7600 Value *Sh = ConstantInt::get(In->getType(),
7601 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007602 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 In->getName()+".lobit"),
7604 CI);
7605 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007606 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007607 true/*SExt*/, "tmp", &CI);
7608
7609 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007610 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007611 In->getName()+".not"), CI);
7612
7613 return ReplaceInstUsesWith(CI, In);
7614 }
7615 }
7616 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00007617
7618 // See if the value being truncated is already sign extended. If so, just
7619 // eliminate the trunc/sext pair.
7620 if (getOpcode(Src) == Instruction::Trunc) {
7621 Value *Op = cast<User>(Src)->getOperand(0);
7622 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7623 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7624 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7625 unsigned NumSignBits = ComputeNumSignBits(Op);
7626
7627 if (OpBits == DestBits) {
7628 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7629 // bits, it is already ready.
7630 if (NumSignBits > DestBits-MidBits)
7631 return ReplaceInstUsesWith(CI, Op);
7632 } else if (OpBits < DestBits) {
7633 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7634 // bits, just sext from i32.
7635 if (NumSignBits > OpBits-MidBits)
7636 return new SExtInst(Op, CI.getType(), "tmp");
7637 } else {
7638 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7639 // bits, just truncate to i32.
7640 if (NumSignBits > OpBits-MidBits)
7641 return new TruncInst(Op, CI.getType(), "tmp");
7642 }
7643 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007644
7645 return 0;
7646}
7647
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007648/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7649/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007650static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007651 APFloat F = CFP->getValueAPF();
7652 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007653 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007654 return 0;
7655}
7656
7657/// LookThroughFPExtensions - If this is an fp extension instruction, look
7658/// through it until we get the source value.
7659static Value *LookThroughFPExtensions(Value *V) {
7660 if (Instruction *I = dyn_cast<Instruction>(V))
7661 if (I->getOpcode() == Instruction::FPExt)
7662 return LookThroughFPExtensions(I->getOperand(0));
7663
7664 // If this value is a constant, return the constant in the smallest FP type
7665 // that can accurately represent it. This allows us to turn
7666 // (float)((double)X+2.0) into x+2.0f.
7667 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7668 if (CFP->getType() == Type::PPC_FP128Ty)
7669 return V; // No constant folding of this.
7670 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007671 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007672 return V;
7673 if (CFP->getType() == Type::DoubleTy)
7674 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007675 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007676 return V;
7677 // Don't try to shrink to various long double types.
7678 }
7679
7680 return V;
7681}
7682
7683Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7684 if (Instruction *I = commonCastTransforms(CI))
7685 return I;
7686
7687 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7688 // smaller than the destination type, we can eliminate the truncate by doing
7689 // the add as the smaller type. This applies to add/sub/mul/div as well as
7690 // many builtins (sqrt, etc).
7691 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7692 if (OpI && OpI->hasOneUse()) {
7693 switch (OpI->getOpcode()) {
7694 default: break;
7695 case Instruction::Add:
7696 case Instruction::Sub:
7697 case Instruction::Mul:
7698 case Instruction::FDiv:
7699 case Instruction::FRem:
7700 const Type *SrcTy = OpI->getType();
7701 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7702 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7703 if (LHSTrunc->getType() != SrcTy &&
7704 RHSTrunc->getType() != SrcTy) {
7705 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7706 // If the source types were both smaller than the destination type of
7707 // the cast, do this xform.
7708 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7709 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7710 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7711 CI.getType(), CI);
7712 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7713 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007714 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007715 }
7716 }
7717 break;
7718 }
7719 }
7720 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007721}
7722
7723Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7724 return commonCastTransforms(CI);
7725}
7726
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007727Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7728 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7729 // mantissa to accurately represent all values of X. For example, do not
7730 // do this with i64->float->i64.
7731 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7732 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7733 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner9ce836b2008-05-19 21:17:23 +00007734 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007735 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7736
7737 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007738}
7739
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007740Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7741 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7742 // mantissa to accurately represent all values of X. For example, do not
7743 // do this with i64->float->i64.
7744 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7745 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7746 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner9ce836b2008-05-19 21:17:23 +00007747 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007748 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7749
7750 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007751}
7752
7753Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7754 return commonCastTransforms(CI);
7755}
7756
7757Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7758 return commonCastTransforms(CI);
7759}
7760
7761Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7762 return commonPointerCastTransforms(CI);
7763}
7764
Chris Lattner7c1626482008-01-08 07:23:51 +00007765Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7766 if (Instruction *I = commonCastTransforms(CI))
7767 return I;
7768
7769 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7770 if (!DestPointee->isSized()) return 0;
7771
7772 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7773 ConstantInt *Cst;
7774 Value *X;
7775 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7776 m_ConstantInt(Cst)))) {
7777 // If the source and destination operands have the same type, see if this
7778 // is a single-index GEP.
7779 if (X->getType() == CI.getType()) {
7780 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007781 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007782
7783 // Convert the constant to intptr type.
7784 APInt Offset = Cst->getValue();
7785 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7786
7787 // If Offset is evenly divisible by Size, we can do this xform.
7788 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7789 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007790 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007791 }
7792 }
7793 // TODO: Could handle other cases, e.g. where add is indexing into field of
7794 // struct etc.
7795 } else if (CI.getOperand(0)->hasOneUse() &&
7796 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7797 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7798 // "inttoptr+GEP" instead of "add+intptr".
7799
7800 // Get the size of the pointee type.
7801 uint64_t Size = TD->getABITypeSize(DestPointee);
7802
7803 // Convert the constant to intptr type.
7804 APInt Offset = Cst->getValue();
7805 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7806
7807 // If Offset is evenly divisible by Size, we can do this xform.
7808 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7809 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7810
7811 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7812 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007813 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007814 }
7815 }
7816 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007817}
7818
7819Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7820 // If the operands are integer typed then apply the integer transforms,
7821 // otherwise just apply the common ones.
7822 Value *Src = CI.getOperand(0);
7823 const Type *SrcTy = Src->getType();
7824 const Type *DestTy = CI.getType();
7825
7826 if (SrcTy->isInteger() && DestTy->isInteger()) {
7827 if (Instruction *Result = commonIntCastTransforms(CI))
7828 return Result;
7829 } else if (isa<PointerType>(SrcTy)) {
7830 if (Instruction *I = commonPointerCastTransforms(CI))
7831 return I;
7832 } else {
7833 if (Instruction *Result = commonCastTransforms(CI))
7834 return Result;
7835 }
7836
7837
7838 // Get rid of casts from one type to the same type. These are useless and can
7839 // be replaced by the operand.
7840 if (DestTy == Src->getType())
7841 return ReplaceInstUsesWith(CI, Src);
7842
7843 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7844 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7845 const Type *DstElTy = DstPTy->getElementType();
7846 const Type *SrcElTy = SrcPTy->getElementType();
7847
Nate Begemandf5b3612008-03-31 00:22:16 +00007848 // If the address spaces don't match, don't eliminate the bitcast, which is
7849 // required for changing types.
7850 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7851 return 0;
7852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007853 // If we are casting a malloc or alloca to a pointer to a type of the same
7854 // size, rewrite the allocation instruction to allocate the "right" type.
7855 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7856 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7857 return V;
7858
7859 // If the source and destination are pointers, and this cast is equivalent
7860 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7861 // This can enhance SROA and other transforms that want type-safe pointers.
7862 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7863 unsigned NumZeros = 0;
7864 while (SrcElTy != DstElTy &&
7865 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7866 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7867 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7868 ++NumZeros;
7869 }
7870
7871 // If we found a path from the src to dest, create the getelementptr now.
7872 if (SrcElTy == DstElTy) {
7873 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007874 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7875 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007876 }
7877 }
7878
7879 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7880 if (SVI->hasOneUse()) {
7881 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7882 // a bitconvert to a vector with the same # elts.
7883 if (isa<VectorType>(DestTy) &&
7884 cast<VectorType>(DestTy)->getNumElements() ==
7885 SVI->getType()->getNumElements()) {
7886 CastInst *Tmp;
7887 // If either of the operands is a cast from CI.getType(), then
7888 // evaluating the shuffle in the casted destination's type will allow
7889 // us to eliminate at least one cast.
7890 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7891 Tmp->getOperand(0)->getType() == DestTy) ||
7892 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7893 Tmp->getOperand(0)->getType() == DestTy)) {
7894 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7895 SVI->getOperand(0), DestTy, &CI);
7896 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7897 SVI->getOperand(1), DestTy, &CI);
7898 // Return a new shuffle vector. Use the same element ID's, as we
7899 // know the vector types match #elts.
7900 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7901 }
7902 }
7903 }
7904 }
7905 return 0;
7906}
7907
7908/// GetSelectFoldableOperands - We want to turn code that looks like this:
7909/// %C = or %A, %B
7910/// %D = select %cond, %C, %A
7911/// into:
7912/// %C = select %cond, %B, 0
7913/// %D = or %A, %C
7914///
7915/// Assuming that the specified instruction is an operand to the select, return
7916/// a bitmask indicating which operands of this instruction are foldable if they
7917/// equal the other incoming value of the select.
7918///
7919static unsigned GetSelectFoldableOperands(Instruction *I) {
7920 switch (I->getOpcode()) {
7921 case Instruction::Add:
7922 case Instruction::Mul:
7923 case Instruction::And:
7924 case Instruction::Or:
7925 case Instruction::Xor:
7926 return 3; // Can fold through either operand.
7927 case Instruction::Sub: // Can only fold on the amount subtracted.
7928 case Instruction::Shl: // Can only fold on the shift amount.
7929 case Instruction::LShr:
7930 case Instruction::AShr:
7931 return 1;
7932 default:
7933 return 0; // Cannot fold
7934 }
7935}
7936
7937/// GetSelectFoldableConstant - For the same transformation as the previous
7938/// function, return the identity constant that goes into the select.
7939static Constant *GetSelectFoldableConstant(Instruction *I) {
7940 switch (I->getOpcode()) {
7941 default: assert(0 && "This cannot happen!"); abort();
7942 case Instruction::Add:
7943 case Instruction::Sub:
7944 case Instruction::Or:
7945 case Instruction::Xor:
7946 case Instruction::Shl:
7947 case Instruction::LShr:
7948 case Instruction::AShr:
7949 return Constant::getNullValue(I->getType());
7950 case Instruction::And:
7951 return Constant::getAllOnesValue(I->getType());
7952 case Instruction::Mul:
7953 return ConstantInt::get(I->getType(), 1);
7954 }
7955}
7956
7957/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7958/// have the same opcode and only one use each. Try to simplify this.
7959Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7960 Instruction *FI) {
7961 if (TI->getNumOperands() == 1) {
7962 // If this is a non-volatile load or a cast from the same type,
7963 // merge.
7964 if (TI->isCast()) {
7965 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7966 return 0;
7967 } else {
7968 return 0; // unknown unary op.
7969 }
7970
7971 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007972 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7973 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007974 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007975 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007976 TI->getType());
7977 }
7978
7979 // Only handle binary operators here.
7980 if (!isa<BinaryOperator>(TI))
7981 return 0;
7982
7983 // Figure out if the operations have any operands in common.
7984 Value *MatchOp, *OtherOpT, *OtherOpF;
7985 bool MatchIsOpZero;
7986 if (TI->getOperand(0) == FI->getOperand(0)) {
7987 MatchOp = TI->getOperand(0);
7988 OtherOpT = TI->getOperand(1);
7989 OtherOpF = FI->getOperand(1);
7990 MatchIsOpZero = true;
7991 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7992 MatchOp = TI->getOperand(1);
7993 OtherOpT = TI->getOperand(0);
7994 OtherOpF = FI->getOperand(0);
7995 MatchIsOpZero = false;
7996 } else if (!TI->isCommutative()) {
7997 return 0;
7998 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7999 MatchOp = TI->getOperand(0);
8000 OtherOpT = TI->getOperand(1);
8001 OtherOpF = FI->getOperand(0);
8002 MatchIsOpZero = true;
8003 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8004 MatchOp = TI->getOperand(1);
8005 OtherOpT = TI->getOperand(0);
8006 OtherOpF = FI->getOperand(1);
8007 MatchIsOpZero = true;
8008 } else {
8009 return 0;
8010 }
8011
8012 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008013 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8014 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008015 InsertNewInstBefore(NewSI, SI);
8016
8017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8018 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008019 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008020 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008021 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008022 }
8023 assert(0 && "Shouldn't get here");
8024 return 0;
8025}
8026
8027Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8028 Value *CondVal = SI.getCondition();
8029 Value *TrueVal = SI.getTrueValue();
8030 Value *FalseVal = SI.getFalseValue();
8031
8032 // select true, X, Y -> X
8033 // select false, X, Y -> Y
8034 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8035 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8036
8037 // select C, X, X -> X
8038 if (TrueVal == FalseVal)
8039 return ReplaceInstUsesWith(SI, TrueVal);
8040
8041 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8042 return ReplaceInstUsesWith(SI, FalseVal);
8043 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8044 return ReplaceInstUsesWith(SI, TrueVal);
8045 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8046 if (isa<Constant>(TrueVal))
8047 return ReplaceInstUsesWith(SI, TrueVal);
8048 else
8049 return ReplaceInstUsesWith(SI, FalseVal);
8050 }
8051
8052 if (SI.getType() == Type::Int1Ty) {
8053 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8054 if (C->getZExtValue()) {
8055 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008056 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008057 } else {
8058 // Change: A = select B, false, C --> A = and !B, C
8059 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008060 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008061 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008062 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008063 }
8064 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8065 if (C->getZExtValue() == false) {
8066 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008067 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008068 } else {
8069 // Change: A = select B, C, true --> A = or !B, C
8070 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008071 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008072 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008073 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008074 }
8075 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008076
8077 // select a, b, a -> a&b
8078 // select a, a, b -> a|b
8079 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008080 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008081 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008082 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008083 }
8084
8085 // Selecting between two integer constants?
8086 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8087 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8088 // select C, 1, 0 -> zext C to int
8089 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008090 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008091 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8092 // select C, 0, 1 -> zext !C to int
8093 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008094 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008095 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008096 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008097 }
8098
8099 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8100
8101 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8102
8103 // (x <s 0) ? -1 : 0 -> ashr x, 31
8104 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8105 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8106 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8107 // The comparison constant and the result are not neccessarily the
8108 // same width. Make an all-ones value by inserting a AShr.
8109 Value *X = IC->getOperand(0);
8110 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8111 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008112 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008113 ShAmt, "ones");
8114 InsertNewInstBefore(SRA, SI);
8115
8116 // Finally, convert to the type of the select RHS. We figure out
8117 // if this requires a SExt, Trunc or BitCast based on the sizes.
8118 Instruction::CastOps opc = Instruction::BitCast;
8119 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8120 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8121 if (SRASize < SISize)
8122 opc = Instruction::SExt;
8123 else if (SRASize > SISize)
8124 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008125 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008126 }
8127 }
8128
8129
8130 // If one of the constants is zero (we know they can't both be) and we
8131 // have an icmp instruction with zero, and we have an 'and' with the
8132 // non-constant value, eliminate this whole mess. This corresponds to
8133 // cases like this: ((X & 27) ? 27 : 0)
8134 if (TrueValC->isZero() || FalseValC->isZero())
8135 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8136 cast<Constant>(IC->getOperand(1))->isNullValue())
8137 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8138 if (ICA->getOpcode() == Instruction::And &&
8139 isa<ConstantInt>(ICA->getOperand(1)) &&
8140 (ICA->getOperand(1) == TrueValC ||
8141 ICA->getOperand(1) == FalseValC) &&
8142 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8143 // Okay, now we know that everything is set up, we just don't
8144 // know whether we have a icmp_ne or icmp_eq and whether the
8145 // true or false val is the zero.
8146 bool ShouldNotVal = !TrueValC->isZero();
8147 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8148 Value *V = ICA;
8149 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008150 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008151 Instruction::Xor, V, ICA->getOperand(1)), SI);
8152 return ReplaceInstUsesWith(SI, V);
8153 }
8154 }
8155 }
8156
8157 // See if we are selecting two values based on a comparison of the two values.
8158 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8159 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8160 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008161 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8162 // This is not safe in general for floating point:
8163 // consider X== -0, Y== +0.
8164 // It becomes safe if either operand is a nonzero constant.
8165 ConstantFP *CFPt, *CFPf;
8166 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8167 !CFPt->getValueAPF().isZero()) ||
8168 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8169 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008170 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008171 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008172 // Transform (X != Y) ? X : Y -> X
8173 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8174 return ReplaceInstUsesWith(SI, TrueVal);
8175 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8176
8177 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8178 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008179 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8180 // This is not safe in general for floating point:
8181 // consider X== -0, Y== +0.
8182 // It becomes safe if either operand is a nonzero constant.
8183 ConstantFP *CFPt, *CFPf;
8184 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8185 !CFPt->getValueAPF().isZero()) ||
8186 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8187 !CFPf->getValueAPF().isZero()))
8188 return ReplaceInstUsesWith(SI, FalseVal);
8189 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008190 // Transform (X != Y) ? Y : X -> Y
8191 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8192 return ReplaceInstUsesWith(SI, TrueVal);
8193 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8194 }
8195 }
8196
8197 // See if we are selecting two values based on a comparison of the two values.
8198 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8199 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8200 // Transform (X == Y) ? X : Y -> Y
8201 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8202 return ReplaceInstUsesWith(SI, FalseVal);
8203 // Transform (X != Y) ? X : Y -> X
8204 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8205 return ReplaceInstUsesWith(SI, TrueVal);
8206 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8207
8208 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8209 // Transform (X == Y) ? Y : X -> X
8210 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8211 return ReplaceInstUsesWith(SI, FalseVal);
8212 // Transform (X != Y) ? Y : X -> Y
8213 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8214 return ReplaceInstUsesWith(SI, TrueVal);
8215 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8216 }
8217 }
8218
8219 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8220 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8221 if (TI->hasOneUse() && FI->hasOneUse()) {
8222 Instruction *AddOp = 0, *SubOp = 0;
8223
8224 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8225 if (TI->getOpcode() == FI->getOpcode())
8226 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8227 return IV;
8228
8229 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8230 // even legal for FP.
8231 if (TI->getOpcode() == Instruction::Sub &&
8232 FI->getOpcode() == Instruction::Add) {
8233 AddOp = FI; SubOp = TI;
8234 } else if (FI->getOpcode() == Instruction::Sub &&
8235 TI->getOpcode() == Instruction::Add) {
8236 AddOp = TI; SubOp = FI;
8237 }
8238
8239 if (AddOp) {
8240 Value *OtherAddOp = 0;
8241 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8242 OtherAddOp = AddOp->getOperand(1);
8243 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8244 OtherAddOp = AddOp->getOperand(0);
8245 }
8246
8247 if (OtherAddOp) {
8248 // So at this point we know we have (Y -> OtherAddOp):
8249 // select C, (add X, Y), (sub X, Z)
8250 Value *NegVal; // Compute -Z
8251 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8252 NegVal = ConstantExpr::getNeg(C);
8253 } else {
8254 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008255 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008256 }
8257
8258 Value *NewTrueOp = OtherAddOp;
8259 Value *NewFalseOp = NegVal;
8260 if (AddOp != TI)
8261 std::swap(NewTrueOp, NewFalseOp);
8262 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008263 SelectInst::Create(CondVal, NewTrueOp,
8264 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008265
8266 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008267 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008268 }
8269 }
8270 }
8271
8272 // See if we can fold the select into one of our operands.
8273 if (SI.getType()->isInteger()) {
8274 // See the comment above GetSelectFoldableOperands for a description of the
8275 // transformation we are doing here.
8276 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8277 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8278 !isa<Constant>(FalseVal))
8279 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8280 unsigned OpToFold = 0;
8281 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8282 OpToFold = 1;
8283 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8284 OpToFold = 2;
8285 }
8286
8287 if (OpToFold) {
8288 Constant *C = GetSelectFoldableConstant(TVI);
8289 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008290 SelectInst::Create(SI.getCondition(),
8291 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008292 InsertNewInstBefore(NewSel, SI);
8293 NewSel->takeName(TVI);
8294 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296 else {
8297 assert(0 && "Unknown instruction!!");
8298 }
8299 }
8300 }
8301
8302 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8303 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8304 !isa<Constant>(TrueVal))
8305 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8306 unsigned OpToFold = 0;
8307 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8308 OpToFold = 1;
8309 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8310 OpToFold = 2;
8311 }
8312
8313 if (OpToFold) {
8314 Constant *C = GetSelectFoldableConstant(FVI);
8315 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008316 SelectInst::Create(SI.getCondition(), C,
8317 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 InsertNewInstBefore(NewSel, SI);
8319 NewSel->takeName(FVI);
8320 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008321 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008322 else
8323 assert(0 && "Unknown instruction!!");
8324 }
8325 }
8326 }
8327
8328 if (BinaryOperator::isNot(CondVal)) {
8329 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8330 SI.setOperand(1, FalseVal);
8331 SI.setOperand(2, TrueVal);
8332 return &SI;
8333 }
8334
8335 return 0;
8336}
8337
Dan Gohman2d648bb2008-04-10 18:43:06 +00008338/// EnforceKnownAlignment - If the specified pointer points to an object that
8339/// we control, modify the object's alignment to PrefAlign. This isn't
8340/// often possible though. If alignment is important, a more reliable approach
8341/// is to simply align all global variables and allocation instructions to
8342/// their preferred alignment from the beginning.
8343///
8344static unsigned EnforceKnownAlignment(Value *V,
8345 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008346
Dan Gohman2d648bb2008-04-10 18:43:06 +00008347 User *U = dyn_cast<User>(V);
8348 if (!U) return Align;
8349
8350 switch (getOpcode(U)) {
8351 default: break;
8352 case Instruction::BitCast:
8353 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8354 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008355 // If all indexes are zero, it is just the alignment of the base pointer.
8356 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00008357 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00008358 if (!isa<Constant>(*i) ||
8359 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008360 AllZeroOperands = false;
8361 break;
8362 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008363
8364 if (AllZeroOperands) {
8365 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008366 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008367 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008368 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008369 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008370 }
8371
8372 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8373 // If there is a large requested alignment and we can, bump up the alignment
8374 // of the global.
8375 if (!GV->isDeclaration()) {
8376 GV->setAlignment(PrefAlign);
8377 Align = PrefAlign;
8378 }
8379 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8380 // If there is a requested alignment and if this is an alloca, round up. We
8381 // don't do this for malloc, because some systems can't respect the request.
8382 if (isa<AllocaInst>(AI)) {
8383 AI->setAlignment(PrefAlign);
8384 Align = PrefAlign;
8385 }
8386 }
8387
8388 return Align;
8389}
8390
8391/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8392/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8393/// and it is more than the alignment of the ultimate object, see if we can
8394/// increase the alignment of the ultimate object, making this check succeed.
8395unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8396 unsigned PrefAlign) {
8397 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8398 sizeof(PrefAlign) * CHAR_BIT;
8399 APInt Mask = APInt::getAllOnesValue(BitWidth);
8400 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8401 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8402 unsigned TrailZ = KnownZero.countTrailingOnes();
8403 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8404
8405 if (PrefAlign > Align)
8406 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8407
8408 // We don't need to make any adjustment.
8409 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008410}
8411
Chris Lattner00ae5132008-01-13 23:50:23 +00008412Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008413 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8414 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008415 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8416 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8417
8418 if (CopyAlign < MinAlign) {
8419 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8420 return MI;
8421 }
8422
8423 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8424 // load/store.
8425 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8426 if (MemOpLength == 0) return 0;
8427
Chris Lattnerc669fb62008-01-14 00:28:35 +00008428 // Source and destination pointer types are always "i8*" for intrinsic. See
8429 // if the size is something we can handle with a single primitive load/store.
8430 // A single load+store correctly handles overlapping memory in the memmove
8431 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008432 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008433 if (Size == 0) return MI; // Delete this mem transfer.
8434
8435 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008436 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008437
Chris Lattnerc669fb62008-01-14 00:28:35 +00008438 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008439 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008440
8441 // Memcpy forces the use of i8* for the source and destination. That means
8442 // that if you're using memcpy to move one double around, you'll get a cast
8443 // from double* to i8*. We'd much rather use a double load+store rather than
8444 // an i64 load+store, here because this improves the odds that the source or
8445 // dest address will be promotable. See if we can find a better type than the
8446 // integer datatype.
8447 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8448 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8449 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8450 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8451 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008452 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00008453 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8454 if (STy->getNumElements() == 1)
8455 SrcETy = STy->getElementType(0);
8456 else
8457 break;
8458 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8459 if (ATy->getNumElements() == 1)
8460 SrcETy = ATy->getElementType();
8461 else
8462 break;
8463 } else
8464 break;
8465 }
8466
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008467 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00008468 NewPtrTy = PointerType::getUnqual(SrcETy);
8469 }
8470 }
8471
8472
Chris Lattner00ae5132008-01-13 23:50:23 +00008473 // If the memcpy/memmove provides better alignment info than we can
8474 // infer, use it.
8475 SrcAlign = std::max(SrcAlign, CopyAlign);
8476 DstAlign = std::max(DstAlign, CopyAlign);
8477
8478 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8479 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008480 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8481 InsertNewInstBefore(L, *MI);
8482 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8483
8484 // Set the size of the copy to 0, it will be deleted on the next iteration.
8485 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8486 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008487}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008488
Chris Lattner5af8a912008-04-30 06:39:11 +00008489Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8490 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8491 if (MI->getAlignment()->getZExtValue() < Alignment) {
8492 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8493 return MI;
8494 }
8495
8496 // Extract the length and alignment and fill if they are constant.
8497 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8498 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8499 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8500 return 0;
8501 uint64_t Len = LenC->getZExtValue();
8502 Alignment = MI->getAlignment()->getZExtValue();
8503
8504 // If the length is zero, this is a no-op
8505 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8506
8507 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8508 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8509 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8510
8511 Value *Dest = MI->getDest();
8512 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8513
8514 // Alignment 0 is identity for alignment 1 for memset, but not store.
8515 if (Alignment == 0) Alignment = 1;
8516
8517 // Extract the fill value and store.
8518 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8519 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8520 Alignment), *MI);
8521
8522 // Set the size of the copy to 0, it will be deleted on the next iteration.
8523 MI->setLength(Constant::getNullValue(LenC->getType()));
8524 return MI;
8525 }
8526
8527 return 0;
8528}
8529
8530
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008531/// visitCallInst - CallInst simplification. This mostly only handles folding
8532/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8533/// the heavy lifting.
8534///
8535Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8536 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8537 if (!II) return visitCallSite(&CI);
8538
8539 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8540 // visitCallSite.
8541 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8542 bool Changed = false;
8543
8544 // memmove/cpy/set of zero bytes is a noop.
8545 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8546 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8547
8548 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8549 if (CI->getZExtValue() == 1) {
8550 // Replace the instruction with just byte operations. We would
8551 // transform other cases to loads/stores, but we don't know if
8552 // alignment is sufficient.
8553 }
8554 }
8555
8556 // If we have a memmove and the source operation is a constant global,
8557 // then the source and dest pointers can't alias, so we can change this
8558 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008559 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008560 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8561 if (GVSrc->isConstant()) {
8562 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008563 Intrinsic::ID MemCpyID;
8564 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8565 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008566 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008567 MemCpyID = Intrinsic::memcpy_i64;
8568 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008569 Changed = true;
8570 }
Chris Lattner59b27d92008-05-28 05:30:41 +00008571
8572 // memmove(x,x,size) -> noop.
8573 if (MMI->getSource() == MMI->getDest())
8574 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008575 }
8576
8577 // If we can determine a pointer alignment that is bigger than currently
8578 // set, update the alignment.
8579 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008580 if (Instruction *I = SimplifyMemTransfer(MI))
8581 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008582 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8583 if (Instruction *I = SimplifyMemSet(MSI))
8584 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008585 }
8586
8587 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00008588 }
8589
8590 switch (II->getIntrinsicID()) {
8591 default: break;
8592 case Intrinsic::bswap:
8593 // bswap(bswap(x)) -> x
8594 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8595 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8596 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8597 break;
8598 case Intrinsic::ppc_altivec_lvx:
8599 case Intrinsic::ppc_altivec_lvxl:
8600 case Intrinsic::x86_sse_loadu_ps:
8601 case Intrinsic::x86_sse2_loadu_pd:
8602 case Intrinsic::x86_sse2_loadu_dq:
8603 // Turn PPC lvx -> load if the pointer is known aligned.
8604 // Turn X86 loadups -> load if the pointer is known aligned.
8605 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8606 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8607 PointerType::getUnqual(II->getType()),
8608 CI);
8609 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008610 }
Chris Lattner989ba312008-06-18 04:33:20 +00008611 break;
8612 case Intrinsic::ppc_altivec_stvx:
8613 case Intrinsic::ppc_altivec_stvxl:
8614 // Turn stvx -> store if the pointer is known aligned.
8615 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8616 const Type *OpPtrTy =
8617 PointerType::getUnqual(II->getOperand(1)->getType());
8618 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8619 return new StoreInst(II->getOperand(1), Ptr);
8620 }
8621 break;
8622 case Intrinsic::x86_sse_storeu_ps:
8623 case Intrinsic::x86_sse2_storeu_pd:
8624 case Intrinsic::x86_sse2_storeu_dq:
8625 case Intrinsic::x86_sse2_storel_dq:
8626 // Turn X86 storeu -> store if the pointer is known aligned.
8627 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8628 const Type *OpPtrTy =
8629 PointerType::getUnqual(II->getOperand(2)->getType());
8630 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8631 return new StoreInst(II->getOperand(2), Ptr);
8632 }
8633 break;
8634
8635 case Intrinsic::x86_sse_cvttss2si: {
8636 // These intrinsics only demands the 0th element of its input vector. If
8637 // we can simplify the input based on that, do so now.
8638 uint64_t UndefElts;
8639 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8640 UndefElts)) {
8641 II->setOperand(1, V);
8642 return II;
8643 }
8644 break;
8645 }
8646
8647 case Intrinsic::ppc_altivec_vperm:
8648 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8649 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8650 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008651
Chris Lattner989ba312008-06-18 04:33:20 +00008652 // Check that all of the elements are integer constants or undefs.
8653 bool AllEltsOk = true;
8654 for (unsigned i = 0; i != 16; ++i) {
8655 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8656 !isa<UndefValue>(Mask->getOperand(i))) {
8657 AllEltsOk = false;
8658 break;
8659 }
8660 }
8661
8662 if (AllEltsOk) {
8663 // Cast the input vectors to byte vectors.
8664 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8665 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8666 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008667
Chris Lattner989ba312008-06-18 04:33:20 +00008668 // Only extract each element once.
8669 Value *ExtractedElts[32];
8670 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008672 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00008673 if (isa<UndefValue>(Mask->getOperand(i)))
8674 continue;
8675 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8676 Idx &= 31; // Match the hardware behavior.
8677
8678 if (ExtractedElts[Idx] == 0) {
8679 Instruction *Elt =
8680 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8681 InsertNewInstBefore(Elt, CI);
8682 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008683 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008684
Chris Lattner989ba312008-06-18 04:33:20 +00008685 // Insert this value into the result vector.
8686 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8687 i, "tmp");
8688 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008689 }
Chris Lattner989ba312008-06-18 04:33:20 +00008690 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008691 }
Chris Lattner989ba312008-06-18 04:33:20 +00008692 }
8693 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008694
Chris Lattner989ba312008-06-18 04:33:20 +00008695 case Intrinsic::stackrestore: {
8696 // If the save is right next to the restore, remove the restore. This can
8697 // happen when variable allocas are DCE'd.
8698 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8699 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8700 BasicBlock::iterator BI = SS;
8701 if (&*++BI == II)
8702 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008703 }
Chris Lattner989ba312008-06-18 04:33:20 +00008704 }
8705
8706 // Scan down this block to see if there is another stack restore in the
8707 // same block without an intervening call/alloca.
8708 BasicBlock::iterator BI = II;
8709 TerminatorInst *TI = II->getParent()->getTerminator();
8710 bool CannotRemove = false;
8711 for (++BI; &*BI != TI; ++BI) {
8712 if (isa<AllocaInst>(BI)) {
8713 CannotRemove = true;
8714 break;
8715 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00008716 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8717 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8718 // If there is a stackrestore below this one, remove this one.
8719 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8720 return EraseInstFromFunction(CI);
8721 // Otherwise, ignore the intrinsic.
8722 } else {
8723 // If we found a non-intrinsic call, we can't remove the stack
8724 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00008725 CannotRemove = true;
8726 break;
8727 }
Chris Lattner989ba312008-06-18 04:33:20 +00008728 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008729 }
Chris Lattner989ba312008-06-18 04:33:20 +00008730
8731 // If the stack restore is in a return/unwind block and if there are no
8732 // allocas or calls between the restore and the return, nuke the restore.
8733 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8734 return EraseInstFromFunction(CI);
8735 break;
8736 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008737 }
8738
8739 return visitCallSite(II);
8740}
8741
8742// InvokeInst simplification
8743//
8744Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8745 return visitCallSite(&II);
8746}
8747
Dale Johannesen96021832008-04-25 21:16:07 +00008748/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8749/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008750static bool isSafeToEliminateVarargsCast(const CallSite CS,
8751 const CastInst * const CI,
8752 const TargetData * const TD,
8753 const int ix) {
8754 if (!CI->isLosslessCast())
8755 return false;
8756
8757 // The size of ByVal arguments is derived from the type, so we
8758 // can't change to a type with a different size. If the size were
8759 // passed explicitly we could avoid this check.
8760 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8761 return true;
8762
8763 const Type* SrcTy =
8764 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8765 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8766 if (!SrcTy->isSized() || !DstTy->isSized())
8767 return false;
8768 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8769 return false;
8770 return true;
8771}
8772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008773// visitCallSite - Improvements for call and invoke instructions.
8774//
8775Instruction *InstCombiner::visitCallSite(CallSite CS) {
8776 bool Changed = false;
8777
8778 // If the callee is a constexpr cast of a function, attempt to move the cast
8779 // to the arguments of the call/invoke.
8780 if (transformConstExprCastCall(CS)) return 0;
8781
8782 Value *Callee = CS.getCalledValue();
8783
8784 if (Function *CalleeF = dyn_cast<Function>(Callee))
8785 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8786 Instruction *OldCall = CS.getInstruction();
8787 // If the call and callee calling conventions don't match, this call must
8788 // be unreachable, as the call is undefined.
8789 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008790 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8791 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008792 if (!OldCall->use_empty())
8793 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8794 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8795 return EraseInstFromFunction(*OldCall);
8796 return 0;
8797 }
8798
8799 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8800 // This instruction is not reachable, just remove it. We insert a store to
8801 // undef so that we know that this code is not reachable, despite the fact
8802 // that we can't modify the CFG here.
8803 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008804 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008805 CS.getInstruction());
8806
8807 if (!CS.getInstruction()->use_empty())
8808 CS.getInstruction()->
8809 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8810
8811 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8812 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008813 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8814 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008815 }
8816 return EraseInstFromFunction(*CS.getInstruction());
8817 }
8818
Duncan Sands74833f22007-09-17 10:26:40 +00008819 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8820 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8821 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8822 return transformCallThroughTrampoline(CS);
8823
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008824 const PointerType *PTy = cast<PointerType>(Callee->getType());
8825 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8826 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00008827 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008828 // See if we can optimize any arguments passed through the varargs area of
8829 // the call.
8830 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00008831 E = CS.arg_end(); I != E; ++I, ++ix) {
8832 CastInst *CI = dyn_cast<CastInst>(*I);
8833 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8834 *I = CI->getOperand(0);
8835 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008836 }
Dale Johannesen35615462008-04-23 18:34:37 +00008837 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008838 }
8839
Duncan Sands2937e352007-12-19 21:13:37 +00008840 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008841 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008842 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008843 Changed = true;
8844 }
8845
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008846 return Changed ? CS.getInstruction() : 0;
8847}
8848
8849// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8850// attempt to move the cast to the arguments of the call/invoke.
8851//
8852bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8853 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8854 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8855 if (CE->getOpcode() != Instruction::BitCast ||
8856 !isa<Function>(CE->getOperand(0)))
8857 return false;
8858 Function *Callee = cast<Function>(CE->getOperand(0));
8859 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008860 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008861
8862 // Okay, this is a cast from a function to a different type. Unless doing so
8863 // would cause a type conversion of one of our arguments, change this call to
8864 // be a direct call with arguments casted to the appropriate types.
8865 //
8866 const FunctionType *FT = Callee->getFunctionType();
8867 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00008868 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008869
Duncan Sands7901ce12008-06-01 07:38:42 +00008870 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00008871 return false; // TODO: Handle multiple return values.
8872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008873 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00008874 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00008875 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00008876 // Conversion is ok if changing from one pointer type to another or from
8877 // a pointer to an integer of the same size.
8878 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00008879 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008880 return false; // Cannot transform this return value.
8881
Duncan Sands5c489582008-01-06 10:12:28 +00008882 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008883 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00008884 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008885 return false; // Cannot transform this return value.
8886
Chris Lattner1c8733e2008-03-12 17:45:29 +00008887 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8888 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands7901ce12008-06-01 07:38:42 +00008889 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008890 return false; // Attribute not compatible with transformed value.
8891 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008892
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893 // If the callsite is an invoke instruction, and the return value is used by
8894 // a PHI node in a successor, we cannot change the return type of the call
8895 // because there is no place to put the cast instruction (without breaking
8896 // the critical edge). Bail out in this case.
8897 if (!Caller->use_empty())
8898 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8899 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8900 UI != E; ++UI)
8901 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8902 if (PN->getParent() == II->getNormalDest() ||
8903 PN->getParent() == II->getUnwindDest())
8904 return false;
8905 }
8906
8907 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8908 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8909
8910 CallSite::arg_iterator AI = CS.arg_begin();
8911 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8912 const Type *ParamTy = FT->getParamType(i);
8913 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008914
8915 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008916 return false; // Cannot transform this parameter value.
8917
Chris Lattner1c8733e2008-03-12 17:45:29 +00008918 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8919 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008920
Duncan Sands7901ce12008-06-01 07:38:42 +00008921 // Converting from one pointer type to another or between a pointer and an
8922 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008923 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00008924 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8925 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008926 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927 }
8928
8929 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8930 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00008931 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008932
Chris Lattner1c8733e2008-03-12 17:45:29 +00008933 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8934 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00008935 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008936 // won't be dropping them. Check that these extra arguments have attributes
8937 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008938 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8939 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00008940 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008941 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00008942 if (PAttrs & ParamAttr::VarArgsIncompatible)
8943 return false;
8944 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008945
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008946 // Okay, we decided that this is a safe thing to do: go ahead and start
8947 // inserting cast instructions as necessary...
8948 std::vector<Value*> Args;
8949 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008950 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00008951 attrVec.reserve(NumCommonArgs);
8952
8953 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008954 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00008955
8956 // If the return value is not being used, the type may not be compatible
8957 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands7901ce12008-06-01 07:38:42 +00008958 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00008959
8960 // Add the new return attributes.
8961 if (RAttrs)
8962 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008963
8964 AI = CS.arg_begin();
8965 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8966 const Type *ParamTy = FT->getParamType(i);
8967 if ((*AI)->getType() == ParamTy) {
8968 Args.push_back(*AI);
8969 } else {
8970 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8971 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008972 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008973 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8974 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008975
8976 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008977 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00008978 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008979 }
8980
8981 // If the function takes more arguments than the call was taking, add them
8982 // now...
8983 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8984 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8985
8986 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008987 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008988 if (!FT->isVarArg()) {
8989 cerr << "WARNING: While resolving call to function '"
8990 << Callee->getName() << "' arguments were dropped!\n";
8991 } else {
8992 // Add all of the arguments in their promoted form to the arg list...
8993 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8994 const Type *PTy = getPromotedType((*AI)->getType());
8995 if (PTy != (*AI)->getType()) {
8996 // Must promote to pass through va_arg area!
8997 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8998 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008999 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009000 InsertNewInstBefore(Cast, *Caller);
9001 Args.push_back(Cast);
9002 } else {
9003 Args.push_back(*AI);
9004 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009005
Duncan Sands4ced1f82008-01-13 08:02:44 +00009006 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009007 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009008 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9009 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009010 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009011 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009012
Duncan Sands7901ce12008-06-01 07:38:42 +00009013 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009014 Caller->setName(""); // Void type should not have a name.
9015
Chris Lattner1c8733e2008-03-12 17:45:29 +00009016 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009017
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009018 Instruction *NC;
9019 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009020 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009021 Args.begin(), Args.end(),
9022 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009023 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009024 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009025 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009026 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9027 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009028 CallInst *CI = cast<CallInst>(Caller);
9029 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009030 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009031 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009032 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009033 }
9034
9035 // Insert a cast of the return type as necessary.
9036 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009037 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009038 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009039 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009040 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009041 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009042
9043 // If this is an invoke instruction, we should insert it after the first
9044 // non-phi, instruction in the normal successor block.
9045 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009046 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009047 InsertNewInstBefore(NC, *I);
9048 } else {
9049 // Otherwise, it's a call, just insert cast right after the call instr
9050 InsertNewInstBefore(NC, *Caller);
9051 }
9052 AddUsersToWorkList(*Caller);
9053 } else {
9054 NV = UndefValue::get(Caller->getType());
9055 }
9056 }
9057
9058 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9059 Caller->replaceAllUsesWith(NV);
9060 Caller->eraseFromParent();
9061 RemoveFromWorkList(Caller);
9062 return true;
9063}
9064
Duncan Sands74833f22007-09-17 10:26:40 +00009065// transformCallThroughTrampoline - Turn a call to a function created by the
9066// init_trampoline intrinsic into a direct call to the underlying function.
9067//
9068Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9069 Value *Callee = CS.getCalledValue();
9070 const PointerType *PTy = cast<PointerType>(Callee->getType());
9071 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009072 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009073
9074 // If the call already has the 'nest' attribute somewhere then give up -
9075 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009076 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009077 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009078
9079 IntrinsicInst *Tramp =
9080 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9081
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009082 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009083 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9084 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9085
Chris Lattner1c8733e2008-03-12 17:45:29 +00009086 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9087 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009088 unsigned NestIdx = 1;
9089 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009090 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009091
9092 // Look for a parameter marked with the 'nest' attribute.
9093 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9094 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009095 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009096 // Record the parameter type and any other attributes.
9097 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009098 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009099 break;
9100 }
9101
9102 if (NestTy) {
9103 Instruction *Caller = CS.getInstruction();
9104 std::vector<Value*> NewArgs;
9105 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9106
Chris Lattner1c8733e2008-03-12 17:45:29 +00009107 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9108 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009109
Duncan Sands74833f22007-09-17 10:26:40 +00009110 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009111 // mean appending it. Likewise for attributes.
9112
9113 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009114 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9115 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009116
Duncan Sands74833f22007-09-17 10:26:40 +00009117 {
9118 unsigned Idx = 1;
9119 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9120 do {
9121 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009122 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009123 Value *NestVal = Tramp->getOperand(3);
9124 if (NestVal->getType() != NestTy)
9125 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9126 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009127 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009128 }
9129
9130 if (I == E)
9131 break;
9132
Duncan Sands48b81112008-01-14 19:52:09 +00009133 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009134 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009135 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009136 NewAttrs.push_back
9137 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009138
9139 ++Idx, ++I;
9140 } while (1);
9141 }
9142
9143 // The trampoline may have been bitcast to a bogus type (FTy).
9144 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009145 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009146
Duncan Sands74833f22007-09-17 10:26:40 +00009147 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009148 NewTypes.reserve(FTy->getNumParams()+1);
9149
Duncan Sands74833f22007-09-17 10:26:40 +00009150 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009151 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009152 {
9153 unsigned Idx = 1;
9154 FunctionType::param_iterator I = FTy->param_begin(),
9155 E = FTy->param_end();
9156
9157 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009158 if (Idx == NestIdx)
9159 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009160 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009161
9162 if (I == E)
9163 break;
9164
Duncan Sands48b81112008-01-14 19:52:09 +00009165 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009166 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009167
9168 ++Idx, ++I;
9169 } while (1);
9170 }
9171
9172 // Replace the trampoline call with a direct call. Let the generic
9173 // code sort out any function type mismatches.
9174 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009175 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009176 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9177 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009178 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009179
9180 Instruction *NewCaller;
9181 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009182 NewCaller = InvokeInst::Create(NewCallee,
9183 II->getNormalDest(), II->getUnwindDest(),
9184 NewArgs.begin(), NewArgs.end(),
9185 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009186 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009187 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009188 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009189 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9190 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009191 if (cast<CallInst>(Caller)->isTailCall())
9192 cast<CallInst>(NewCaller)->setTailCall();
9193 cast<CallInst>(NewCaller)->
9194 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009195 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009196 }
9197 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9198 Caller->replaceAllUsesWith(NewCaller);
9199 Caller->eraseFromParent();
9200 RemoveFromWorkList(Caller);
9201 return 0;
9202 }
9203 }
9204
9205 // Replace the trampoline call with a direct call. Since there is no 'nest'
9206 // parameter, there is no need to adjust the argument list. Let the generic
9207 // code sort out any function type mismatches.
9208 Constant *NewCallee =
9209 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9210 CS.setCalledFunction(NewCallee);
9211 return CS.getInstruction();
9212}
9213
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009214/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9215/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9216/// and a single binop.
9217Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9218 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9219 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9220 isa<CmpInst>(FirstInst));
9221 unsigned Opc = FirstInst->getOpcode();
9222 Value *LHSVal = FirstInst->getOperand(0);
9223 Value *RHSVal = FirstInst->getOperand(1);
9224
9225 const Type *LHSType = LHSVal->getType();
9226 const Type *RHSType = RHSVal->getType();
9227
9228 // Scan to see if all operands are the same opcode, all have one use, and all
9229 // kill their operands (i.e. the operands have one use).
9230 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9231 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9232 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9233 // Verify type of the LHS matches so we don't fold cmp's of different
9234 // types or GEP's with different index types.
9235 I->getOperand(0)->getType() != LHSType ||
9236 I->getOperand(1)->getType() != RHSType)
9237 return 0;
9238
9239 // If they are CmpInst instructions, check their predicates
9240 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9241 if (cast<CmpInst>(I)->getPredicate() !=
9242 cast<CmpInst>(FirstInst)->getPredicate())
9243 return 0;
9244
9245 // Keep track of which operand needs a phi node.
9246 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9247 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9248 }
9249
9250 // Otherwise, this is safe to transform, determine if it is profitable.
9251
9252 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9253 // Indexes are often folded into load/store instructions, so we don't want to
9254 // hide them behind a phi.
9255 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9256 return 0;
9257
9258 Value *InLHS = FirstInst->getOperand(0);
9259 Value *InRHS = FirstInst->getOperand(1);
9260 PHINode *NewLHS = 0, *NewRHS = 0;
9261 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009262 NewLHS = PHINode::Create(LHSType,
9263 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009264 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9265 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9266 InsertNewInstBefore(NewLHS, PN);
9267 LHSVal = NewLHS;
9268 }
9269
9270 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009271 NewRHS = PHINode::Create(RHSType,
9272 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009273 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9274 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9275 InsertNewInstBefore(NewRHS, PN);
9276 RHSVal = NewRHS;
9277 }
9278
9279 // Add all operands to the new PHIs.
9280 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9281 if (NewLHS) {
9282 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9283 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9284 }
9285 if (NewRHS) {
9286 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9287 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9288 }
9289 }
9290
9291 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009292 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009293 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009294 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009295 RHSVal);
9296 else {
9297 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009298 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009299 }
9300}
9301
9302/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9303/// of the block that defines it. This means that it must be obvious the value
9304/// of the load is not changed from the point of the load to the end of the
9305/// block it is in.
9306///
9307/// Finally, it is safe, but not profitable, to sink a load targetting a
9308/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9309/// to a register.
9310static bool isSafeToSinkLoad(LoadInst *L) {
9311 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9312
9313 for (++BBI; BBI != E; ++BBI)
9314 if (BBI->mayWriteToMemory())
9315 return false;
9316
9317 // Check for non-address taken alloca. If not address-taken already, it isn't
9318 // profitable to do this xform.
9319 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9320 bool isAddressTaken = false;
9321 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9322 UI != E; ++UI) {
9323 if (isa<LoadInst>(UI)) continue;
9324 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9325 // If storing TO the alloca, then the address isn't taken.
9326 if (SI->getOperand(1) == AI) continue;
9327 }
9328 isAddressTaken = true;
9329 break;
9330 }
9331
9332 if (!isAddressTaken)
9333 return false;
9334 }
9335
9336 return true;
9337}
9338
9339
9340// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9341// operator and they all are only used by the PHI, PHI together their
9342// inputs, and do the operation once, to the result of the PHI.
9343Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9344 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9345
9346 // Scan the instruction, looking for input operations that can be folded away.
9347 // If all input operands to the phi are the same instruction (e.g. a cast from
9348 // the same type or "+42") we can pull the operation through the PHI, reducing
9349 // code size and simplifying code.
9350 Constant *ConstantOp = 0;
9351 const Type *CastSrcTy = 0;
9352 bool isVolatile = false;
9353 if (isa<CastInst>(FirstInst)) {
9354 CastSrcTy = FirstInst->getOperand(0)->getType();
9355 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9356 // Can fold binop, compare or shift here if the RHS is a constant,
9357 // otherwise call FoldPHIArgBinOpIntoPHI.
9358 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9359 if (ConstantOp == 0)
9360 return FoldPHIArgBinOpIntoPHI(PN);
9361 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9362 isVolatile = LI->isVolatile();
9363 // We can't sink the load if the loaded value could be modified between the
9364 // load and the PHI.
9365 if (LI->getParent() != PN.getIncomingBlock(0) ||
9366 !isSafeToSinkLoad(LI))
9367 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009368
9369 // If the PHI is of volatile loads and the load block has multiple
9370 // successors, sinking it would remove a load of the volatile value from
9371 // the path through the other successor.
9372 if (isVolatile &&
9373 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9374 return 0;
9375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376 } else if (isa<GetElementPtrInst>(FirstInst)) {
9377 if (FirstInst->getNumOperands() == 2)
9378 return FoldPHIArgBinOpIntoPHI(PN);
9379 // Can't handle general GEPs yet.
9380 return 0;
9381 } else {
9382 return 0; // Cannot fold this operation.
9383 }
9384
9385 // Check to see if all arguments are the same operation.
9386 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9387 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9388 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9389 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9390 return 0;
9391 if (CastSrcTy) {
9392 if (I->getOperand(0)->getType() != CastSrcTy)
9393 return 0; // Cast operation must match.
9394 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9395 // We can't sink the load if the loaded value could be modified between
9396 // the load and the PHI.
9397 if (LI->isVolatile() != isVolatile ||
9398 LI->getParent() != PN.getIncomingBlock(i) ||
9399 !isSafeToSinkLoad(LI))
9400 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009401
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009402 // If the PHI is of volatile loads and the load block has multiple
9403 // successors, sinking it would remove a load of the volatile value from
9404 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +00009405 if (isVolatile &&
9406 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9407 return 0;
9408
9409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009410 } else if (I->getOperand(1) != ConstantOp) {
9411 return 0;
9412 }
9413 }
9414
9415 // Okay, they are all the same operation. Create a new PHI node of the
9416 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009417 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9418 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009419 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9420
9421 Value *InVal = FirstInst->getOperand(0);
9422 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9423
9424 // Add all operands to the new PHI.
9425 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9426 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9427 if (NewInVal != InVal)
9428 InVal = 0;
9429 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9430 }
9431
9432 Value *PhiVal;
9433 if (InVal) {
9434 // The new PHI unions all of the same values together. This is really
9435 // common, so we handle it intelligently here for compile-time speed.
9436 PhiVal = InVal;
9437 delete NewPN;
9438 } else {
9439 InsertNewInstBefore(NewPN, PN);
9440 PhiVal = NewPN;
9441 }
9442
9443 // Insert and return the new operation.
9444 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009445 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009446 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009447 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009448 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009449 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009450 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009451 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9452
9453 // If this was a volatile load that we are merging, make sure to loop through
9454 // and mark all the input loads as non-volatile. If we don't do this, we will
9455 // insert a new volatile load and the old ones will not be deletable.
9456 if (isVolatile)
9457 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9458 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9459
9460 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009461}
9462
9463/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9464/// that is dead.
9465static bool DeadPHICycle(PHINode *PN,
9466 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9467 if (PN->use_empty()) return true;
9468 if (!PN->hasOneUse()) return false;
9469
9470 // Remember this node, and if we find the cycle, return.
9471 if (!PotentiallyDeadPHIs.insert(PN))
9472 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009473
9474 // Don't scan crazily complex things.
9475 if (PotentiallyDeadPHIs.size() == 16)
9476 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477
9478 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9479 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9480
9481 return false;
9482}
9483
Chris Lattner27b695d2007-11-06 21:52:06 +00009484/// PHIsEqualValue - Return true if this phi node is always equal to
9485/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9486/// z = some value; x = phi (y, z); y = phi (x, z)
9487static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9488 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9489 // See if we already saw this PHI node.
9490 if (!ValueEqualPHIs.insert(PN))
9491 return true;
9492
9493 // Don't scan crazily complex things.
9494 if (ValueEqualPHIs.size() == 16)
9495 return false;
9496
9497 // Scan the operands to see if they are either phi nodes or are equal to
9498 // the value.
9499 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9500 Value *Op = PN->getIncomingValue(i);
9501 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9502 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9503 return false;
9504 } else if (Op != NonPhiInVal)
9505 return false;
9506 }
9507
9508 return true;
9509}
9510
9511
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009512// PHINode simplification
9513//
9514Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9515 // If LCSSA is around, don't mess with Phi nodes
9516 if (MustPreserveLCSSA) return 0;
9517
9518 if (Value *V = PN.hasConstantValue())
9519 return ReplaceInstUsesWith(PN, V);
9520
9521 // If all PHI operands are the same operation, pull them through the PHI,
9522 // reducing code size.
9523 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9524 PN.getIncomingValue(0)->hasOneUse())
9525 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9526 return Result;
9527
9528 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9529 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9530 // PHI)... break the cycle.
9531 if (PN.hasOneUse()) {
9532 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9533 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9534 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9535 PotentiallyDeadPHIs.insert(&PN);
9536 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9537 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9538 }
9539
9540 // If this phi has a single use, and if that use just computes a value for
9541 // the next iteration of a loop, delete the phi. This occurs with unused
9542 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9543 // common case here is good because the only other things that catch this
9544 // are induction variable analysis (sometimes) and ADCE, which is only run
9545 // late.
9546 if (PHIUser->hasOneUse() &&
9547 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9548 PHIUser->use_back() == &PN) {
9549 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9550 }
9551 }
9552
Chris Lattner27b695d2007-11-06 21:52:06 +00009553 // We sometimes end up with phi cycles that non-obviously end up being the
9554 // same value, for example:
9555 // z = some value; x = phi (y, z); y = phi (x, z)
9556 // where the phi nodes don't necessarily need to be in the same block. Do a
9557 // quick check to see if the PHI node only contains a single non-phi value, if
9558 // so, scan to see if the phi cycle is actually equal to that value.
9559 {
9560 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9561 // Scan for the first non-phi operand.
9562 while (InValNo != NumOperandVals &&
9563 isa<PHINode>(PN.getIncomingValue(InValNo)))
9564 ++InValNo;
9565
9566 if (InValNo != NumOperandVals) {
9567 Value *NonPhiInVal = PN.getOperand(InValNo);
9568
9569 // Scan the rest of the operands to see if there are any conflicts, if so
9570 // there is no need to recursively scan other phis.
9571 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9572 Value *OpVal = PN.getIncomingValue(InValNo);
9573 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9574 break;
9575 }
9576
9577 // If we scanned over all operands, then we have one unique value plus
9578 // phi values. Scan PHI nodes to see if they all merge in each other or
9579 // the value.
9580 if (InValNo == NumOperandVals) {
9581 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9582 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9583 return ReplaceInstUsesWith(PN, NonPhiInVal);
9584 }
9585 }
9586 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009587 return 0;
9588}
9589
9590static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9591 Instruction *InsertPoint,
9592 InstCombiner *IC) {
9593 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9594 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9595 // We must cast correctly to the pointer type. Ensure that we
9596 // sign extend the integer value if it is smaller as this is
9597 // used for address computation.
9598 Instruction::CastOps opcode =
9599 (VTySize < PtrSize ? Instruction::SExt :
9600 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9601 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9602}
9603
9604
9605Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9606 Value *PtrOp = GEP.getOperand(0);
9607 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9608 // If so, eliminate the noop.
9609 if (GEP.getNumOperands() == 1)
9610 return ReplaceInstUsesWith(GEP, PtrOp);
9611
9612 if (isa<UndefValue>(GEP.getOperand(0)))
9613 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9614
9615 bool HasZeroPointerIndex = false;
9616 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9617 HasZeroPointerIndex = C->isNullValue();
9618
9619 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9620 return ReplaceInstUsesWith(GEP, PtrOp);
9621
9622 // Eliminate unneeded casts for indices.
9623 bool MadeChange = false;
9624
9625 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009626 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9627 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +00009629 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009630 if (CI->getOpcode() == Instruction::ZExt ||
9631 CI->getOpcode() == Instruction::SExt) {
9632 const Type *SrcTy = CI->getOperand(0)->getType();
9633 // We can eliminate a cast from i32 to i64 iff the target
9634 // is a 32-bit pointer target.
9635 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9636 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +00009637 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009638 }
9639 }
9640 }
9641 // If we are using a wider index than needed for this platform, shrink it
9642 // to what we need. If the incoming value needs a cast instruction,
9643 // insert it. This explicit cast can make subsequent optimizations more
9644 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +00009645 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009646 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009647 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +00009648 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009649 MadeChange = true;
9650 } else {
9651 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9652 GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009653 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009654 MadeChange = true;
9655 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009656 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009657 }
9658 }
9659 if (MadeChange) return &GEP;
9660
9661 // If this GEP instruction doesn't move the pointer, and if the input operand
9662 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9663 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009664 if (GEP.hasAllZeroIndices()) {
9665 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9666 // If the bitcast is of an allocation, and the allocation will be
9667 // converted to match the type of the cast, don't touch this.
9668 if (isa<AllocationInst>(BCI->getOperand(0))) {
9669 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009670 if (Instruction *I = visitBitCast(*BCI)) {
9671 if (I != BCI) {
9672 I->takeName(BCI);
9673 BCI->getParent()->getInstList().insert(BCI, I);
9674 ReplaceInstUsesWith(*BCI, I);
9675 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009676 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009677 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009678 }
9679 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9680 }
9681 }
9682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009683 // Combine Indices - If the source pointer to this getelementptr instruction
9684 // is a getelementptr instruction, combine the indices of the two
9685 // getelementptr instructions into a single instruction.
9686 //
9687 SmallVector<Value*, 8> SrcGEPOperands;
9688 if (User *Src = dyn_castGetElementPtr(PtrOp))
9689 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9690
9691 if (!SrcGEPOperands.empty()) {
9692 // Note that if our source is a gep chain itself that we wait for that
9693 // chain to be resolved before we perform this transformation. This
9694 // avoids us creating a TON of code in some cases.
9695 //
9696 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9697 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9698 return 0; // Wait until our source is folded to completion.
9699
9700 SmallVector<Value*, 8> Indices;
9701
9702 // Find out whether the last index in the source GEP is a sequential idx.
9703 bool EndsWithSequential = false;
9704 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9705 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9706 EndsWithSequential = !isa<StructType>(*I);
9707
9708 // Can we combine the two pointer arithmetics offsets?
9709 if (EndsWithSequential) {
9710 // Replace: gep (gep %P, long B), long A, ...
9711 // With: T = long A+B; gep %P, T, ...
9712 //
9713 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9714 if (SO1 == Constant::getNullValue(SO1->getType())) {
9715 Sum = GO1;
9716 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9717 Sum = SO1;
9718 } else {
9719 // If they aren't the same type, convert both to an integer of the
9720 // target's pointer size.
9721 if (SO1->getType() != GO1->getType()) {
9722 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9723 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9724 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9725 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9726 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009727 unsigned PS = TD->getPointerSizeInBits();
9728 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009729 // Convert GO1 to SO1's type.
9730 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9731
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009732 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009733 // Convert SO1 to GO1's type.
9734 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9735 } else {
9736 const Type *PT = TD->getIntPtrType();
9737 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9738 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9739 }
9740 }
9741 }
9742 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9743 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9744 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009745 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009746 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9747 }
9748 }
9749
9750 // Recycle the GEP we already have if possible.
9751 if (SrcGEPOperands.size() == 2) {
9752 GEP.setOperand(0, SrcGEPOperands[0]);
9753 GEP.setOperand(1, Sum);
9754 return &GEP;
9755 } else {
9756 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9757 SrcGEPOperands.end()-1);
9758 Indices.push_back(Sum);
9759 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9760 }
9761 } else if (isa<Constant>(*GEP.idx_begin()) &&
9762 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9763 SrcGEPOperands.size() != 1) {
9764 // Otherwise we can do the fold if the first index of the GEP is a zero
9765 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9766 SrcGEPOperands.end());
9767 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9768 }
9769
9770 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009771 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9772 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009773
9774 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9775 // GEP of global variable. If all of the indices for this GEP are
9776 // constants, we can promote this to a constexpr instead of an instruction.
9777
9778 // Scan for nonconstants...
9779 SmallVector<Constant*, 8> Indices;
9780 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9781 for (; I != E && isa<Constant>(*I); ++I)
9782 Indices.push_back(cast<Constant>(*I));
9783
9784 if (I == E) { // If they are all constants...
9785 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9786 &Indices[0],Indices.size());
9787
9788 // Replace all uses of the GEP with the new constexpr...
9789 return ReplaceInstUsesWith(GEP, CE);
9790 }
9791 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9792 if (!isa<PointerType>(X->getType())) {
9793 // Not interesting. Source pointer must be a cast from pointer.
9794 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009795 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9796 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009797 //
9798 // This occurs when the program declares an array extern like "int X[];"
9799 //
9800 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9801 const PointerType *XTy = cast<PointerType>(X->getType());
9802 if (const ArrayType *XATy =
9803 dyn_cast<ArrayType>(XTy->getElementType()))
9804 if (const ArrayType *CATy =
9805 dyn_cast<ArrayType>(CPTy->getElementType()))
9806 if (CATy->getElementType() == XATy->getElementType()) {
9807 // At this point, we know that the cast source type is a pointer
9808 // to an array of the same type as the destination pointer
9809 // array. Because the array type is never stepped over (there
9810 // is a leading zero) we can fold the cast into this GEP.
9811 GEP.setOperand(0, X);
9812 return &GEP;
9813 }
9814 } else if (GEP.getNumOperands() == 2) {
9815 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009816 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9817 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009818 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9819 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9820 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009821 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9822 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009823 Value *Idx[2];
9824 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9825 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009826 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009827 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009828 // V and GEP are both pointer types --> BitCast
9829 return new BitCastInst(V, GEP.getType());
9830 }
9831
9832 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009833 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009834 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009835 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009836
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009837 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009838 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009839 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009840
9841 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9842 // allow either a mul, shift, or constant here.
9843 Value *NewIdx = 0;
9844 ConstantInt *Scale = 0;
9845 if (ArrayEltSize == 1) {
9846 NewIdx = GEP.getOperand(1);
9847 Scale = ConstantInt::get(NewIdx->getType(), 1);
9848 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9849 NewIdx = ConstantInt::get(CI->getType(), 1);
9850 Scale = CI;
9851 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9852 if (Inst->getOpcode() == Instruction::Shl &&
9853 isa<ConstantInt>(Inst->getOperand(1))) {
9854 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9855 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9856 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9857 NewIdx = Inst->getOperand(0);
9858 } else if (Inst->getOpcode() == Instruction::Mul &&
9859 isa<ConstantInt>(Inst->getOperand(1))) {
9860 Scale = cast<ConstantInt>(Inst->getOperand(1));
9861 NewIdx = Inst->getOperand(0);
9862 }
9863 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009864
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009865 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009866 // out, perform the transformation. Note, we don't know whether Scale is
9867 // signed or not. We'll use unsigned version of division/modulo
9868 // operation after making sure Scale doesn't have the sign bit set.
9869 if (Scale && Scale->getSExtValue() >= 0LL &&
9870 Scale->getZExtValue() % ArrayEltSize == 0) {
9871 Scale = ConstantInt::get(Scale->getType(),
9872 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009873 if (Scale->getZExtValue() != 1) {
9874 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009875 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +00009876 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009877 NewIdx = InsertNewInstBefore(Sc, GEP);
9878 }
9879
9880 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009881 Value *Idx[2];
9882 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9883 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009884 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +00009885 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009886 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9887 // The NewGEP must be pointer typed, so must the old one -> BitCast
9888 return new BitCastInst(NewGEP, GEP.getType());
9889 }
9890 }
9891 }
9892 }
9893
9894 return 0;
9895}
9896
9897Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9898 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009899 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009900 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9901 const Type *NewTy =
9902 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9903 AllocationInst *New = 0;
9904
9905 // Create and insert the replacement instruction...
9906 if (isa<MallocInst>(AI))
9907 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9908 else {
9909 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9910 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9911 }
9912
9913 InsertNewInstBefore(New, AI);
9914
9915 // Scan to the end of the allocation instructions, to skip over a block of
9916 // allocas if possible...
9917 //
9918 BasicBlock::iterator It = New;
9919 while (isa<AllocationInst>(*It)) ++It;
9920
9921 // Now that I is pointing to the first non-allocation-inst in the block,
9922 // insert our getelementptr instruction...
9923 //
9924 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009925 Value *Idx[2];
9926 Idx[0] = NullIdx;
9927 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +00009928 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9929 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009930
9931 // Now make everything use the getelementptr instead of the original
9932 // allocation.
9933 return ReplaceInstUsesWith(AI, V);
9934 } else if (isa<UndefValue>(AI.getArraySize())) {
9935 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9936 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009937 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009938
9939 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9940 // Note that we only do this for alloca's, because malloc should allocate and
9941 // return a unique pointer, even for a zero byte allocation.
9942 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009943 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009944 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9945
9946 return 0;
9947}
9948
9949Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9950 Value *Op = FI.getOperand(0);
9951
9952 // free undef -> unreachable.
9953 if (isa<UndefValue>(Op)) {
9954 // Insert a new store to null because we cannot modify the CFG here.
9955 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009956 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009957 return EraseInstFromFunction(FI);
9958 }
9959
9960 // If we have 'free null' delete the instruction. This can happen in stl code
9961 // when lots of inlining happens.
9962 if (isa<ConstantPointerNull>(Op))
9963 return EraseInstFromFunction(FI);
9964
9965 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9966 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9967 FI.setOperand(0, CI->getOperand(0));
9968 return &FI;
9969 }
9970
9971 // Change free (gep X, 0,0,0,0) into free(X)
9972 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9973 if (GEPI->hasAllZeroIndices()) {
9974 AddToWorkList(GEPI);
9975 FI.setOperand(0, GEPI->getOperand(0));
9976 return &FI;
9977 }
9978 }
9979
9980 // Change free(malloc) into nothing, if the malloc has a single use.
9981 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9982 if (MI->hasOneUse()) {
9983 EraseInstFromFunction(FI);
9984 return EraseInstFromFunction(*MI);
9985 }
9986
9987 return 0;
9988}
9989
9990
9991/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009992static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00009993 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009994 User *CI = cast<User>(LI.getOperand(0));
9995 Value *CastOp = CI->getOperand(0);
9996
Devang Patela0f8ea82007-10-18 19:52:32 +00009997 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9998 // Instead of loading constant c string, use corresponding integer value
9999 // directly if string length is small enough.
Evan Cheng833501d2008-06-30 07:31:25 +000010000 std::string Str;
10001 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010002 unsigned len = Str.length();
10003 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10004 unsigned numBits = Ty->getPrimitiveSizeInBits();
10005 // Replace LI with immediate integer store.
10006 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010007 APInt StrVal(numBits, 0);
10008 APInt SingleChar(numBits, 0);
10009 if (TD->isLittleEndian()) {
10010 for (signed i = len-1; i >= 0; i--) {
10011 SingleChar = (uint64_t) Str[i];
10012 StrVal = (StrVal << 8) | SingleChar;
10013 }
10014 } else {
10015 for (unsigned i = 0; i < len; i++) {
10016 SingleChar = (uint64_t) Str[i];
10017 StrVal = (StrVal << 8) | SingleChar;
10018 }
10019 // Append NULL at the end.
10020 SingleChar = 0;
10021 StrVal = (StrVal << 8) | SingleChar;
10022 }
10023 Value *NL = ConstantInt::get(StrVal);
10024 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010025 }
10026 }
10027 }
10028
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010029 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10030 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10031 const Type *SrcPTy = SrcTy->getElementType();
10032
10033 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10034 isa<VectorType>(DestPTy)) {
10035 // If the source is an array, the code below will not succeed. Check to
10036 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10037 // constants.
10038 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10039 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10040 if (ASrcTy->getNumElements() != 0) {
10041 Value *Idxs[2];
10042 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10043 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10044 SrcTy = cast<PointerType>(CastOp->getType());
10045 SrcPTy = SrcTy->getElementType();
10046 }
10047
10048 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10049 isa<VectorType>(SrcPTy)) &&
10050 // Do not allow turning this into a load of an integer, which is then
10051 // casted to a pointer, this pessimizes pointer analysis a lot.
10052 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10053 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10054 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10055
10056 // Okay, we are casting from one integer or pointer type to another of
10057 // the same size. Instead of casting the pointer before the load, cast
10058 // the result of the loaded value.
10059 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10060 CI->getName(),
10061 LI.isVolatile()),LI);
10062 // Now cast the result of the load.
10063 return new BitCastInst(NewLoad, LI.getType());
10064 }
10065 }
10066 }
10067 return 0;
10068}
10069
10070/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10071/// from this value cannot trap. If it is not obviously safe to load from the
10072/// specified pointer, we do a quick local scan of the basic block containing
10073/// ScanFrom, to determine if the address is already accessed.
10074static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010075 // If it is an alloca it is always safe to load from.
10076 if (isa<AllocaInst>(V)) return true;
10077
Duncan Sandse40a94a2007-09-19 10:25:38 +000010078 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010079 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010080 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010081 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082
10083 // Otherwise, be a little bit agressive by scanning the local block where we
10084 // want to check to see if the pointer is already being loaded or stored
10085 // from/to. If so, the previous load or store would have already trapped,
10086 // so there is no harm doing an extra load (also, CSE will later eliminate
10087 // the load entirely).
10088 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10089
10090 while (BBI != E) {
10091 --BBI;
10092
Chris Lattner476983a2008-06-20 05:12:56 +000010093 // If we see a free or a call (which might do a free) the pointer could be
10094 // marked invalid.
10095 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10096 return false;
10097
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010098 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10099 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010100 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010102 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010103
10104 }
10105 return false;
10106}
10107
Chris Lattner0270a112007-08-11 18:48:48 +000010108/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10109/// until we find the underlying object a pointer is referring to or something
10110/// we don't understand. Note that the returned pointer may be offset from the
10111/// input, because we ignore GEP indices.
10112static Value *GetUnderlyingObject(Value *Ptr) {
10113 while (1) {
10114 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10115 if (CE->getOpcode() == Instruction::BitCast ||
10116 CE->getOpcode() == Instruction::GetElementPtr)
10117 Ptr = CE->getOperand(0);
10118 else
10119 return Ptr;
10120 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10121 Ptr = BCI->getOperand(0);
10122 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10123 Ptr = GEP->getOperand(0);
10124 } else {
10125 return Ptr;
10126 }
10127 }
10128}
10129
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10131 Value *Op = LI.getOperand(0);
10132
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010133 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010134 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10135 if (KnownAlign >
10136 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10137 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010138 LI.setAlignment(KnownAlign);
10139
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140 // load (cast X) --> cast (load X) iff safe
10141 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010142 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010143 return Res;
10144
10145 // None of the following transforms are legal for volatile loads.
10146 if (LI.isVolatile()) return 0;
10147
10148 if (&LI.getParent()->front() != &LI) {
10149 BasicBlock::iterator BBI = &LI; --BBI;
10150 // If the instruction immediately before this is a store to the same
10151 // address, do a simple form of store->load forwarding.
10152 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10153 if (SI->getOperand(1) == LI.getOperand(0))
10154 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10155 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10156 if (LIB->getOperand(0) == LI.getOperand(0))
10157 return ReplaceInstUsesWith(LI, LIB);
10158 }
10159
Christopher Lamb2c175392007-12-29 07:56:53 +000010160 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10161 const Value *GEPI0 = GEPI->getOperand(0);
10162 // TODO: Consider a target hook for valid address spaces for this xform.
10163 if (isa<ConstantPointerNull>(GEPI0) &&
10164 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010165 // Insert a new store to null instruction before the load to indicate
10166 // that this code is not reachable. We do this instead of inserting
10167 // an unreachable instruction directly because we cannot modify the
10168 // CFG.
10169 new StoreInst(UndefValue::get(LI.getType()),
10170 Constant::getNullValue(Op->getType()), &LI);
10171 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10172 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010173 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010174
10175 if (Constant *C = dyn_cast<Constant>(Op)) {
10176 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010177 // TODO: Consider a target hook for valid address spaces for this xform.
10178 if (isa<UndefValue>(C) || (C->isNullValue() &&
10179 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010180 // Insert a new store to null instruction before the load to indicate that
10181 // this code is not reachable. We do this instead of inserting an
10182 // unreachable instruction directly because we cannot modify the CFG.
10183 new StoreInst(UndefValue::get(LI.getType()),
10184 Constant::getNullValue(Op->getType()), &LI);
10185 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10186 }
10187
10188 // Instcombine load (constant global) into the value loaded.
10189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10190 if (GV->isConstant() && !GV->isDeclaration())
10191 return ReplaceInstUsesWith(LI, GV->getInitializer());
10192
10193 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010194 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010195 if (CE->getOpcode() == Instruction::GetElementPtr) {
10196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10197 if (GV->isConstant() && !GV->isDeclaration())
10198 if (Constant *V =
10199 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10200 return ReplaceInstUsesWith(LI, V);
10201 if (CE->getOperand(0)->isNullValue()) {
10202 // Insert a new store to null instruction before the load to indicate
10203 // that this code is not reachable. We do this instead of inserting
10204 // an unreachable instruction directly because we cannot modify the
10205 // CFG.
10206 new StoreInst(UndefValue::get(LI.getType()),
10207 Constant::getNullValue(Op->getType()), &LI);
10208 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10209 }
10210
10211 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010212 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010213 return Res;
10214 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216 }
Chris Lattner0270a112007-08-11 18:48:48 +000010217
10218 // If this load comes from anywhere in a constant global, and if the global
10219 // is all undef or zero, we know what it loads.
10220 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10221 if (GV->isConstant() && GV->hasInitializer()) {
10222 if (GV->getInitializer()->isNullValue())
10223 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10224 else if (isa<UndefValue>(GV->getInitializer()))
10225 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10226 }
10227 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010228
10229 if (Op->hasOneUse()) {
10230 // Change select and PHI nodes to select values instead of addresses: this
10231 // helps alias analysis out a lot, allows many others simplifications, and
10232 // exposes redundancy in the code.
10233 //
10234 // Note that we cannot do the transformation unless we know that the
10235 // introduced loads cannot trap! Something like this is valid as long as
10236 // the condition is always false: load (select bool %C, int* null, int* %G),
10237 // but it would not be valid if we transformed it to load from null
10238 // unconditionally.
10239 //
10240 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10241 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10242 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10243 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10244 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10245 SI->getOperand(1)->getName()+".val"), LI);
10246 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10247 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010248 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010249 }
10250
10251 // load (select (cond, null, P)) -> load P
10252 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10253 if (C->isNullValue()) {
10254 LI.setOperand(0, SI->getOperand(2));
10255 return &LI;
10256 }
10257
10258 // load (select (cond, P, null)) -> load P
10259 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10260 if (C->isNullValue()) {
10261 LI.setOperand(0, SI->getOperand(1));
10262 return &LI;
10263 }
10264 }
10265 }
10266 return 0;
10267}
10268
10269/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10270/// when possible.
10271static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10272 User *CI = cast<User>(SI.getOperand(1));
10273 Value *CastOp = CI->getOperand(0);
10274
10275 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10276 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10277 const Type *SrcPTy = SrcTy->getElementType();
10278
10279 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10280 // If the source is an array, the code below will not succeed. Check to
10281 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10282 // constants.
10283 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10284 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10285 if (ASrcTy->getNumElements() != 0) {
10286 Value* Idxs[2];
10287 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10288 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10289 SrcTy = cast<PointerType>(CastOp->getType());
10290 SrcPTy = SrcTy->getElementType();
10291 }
10292
10293 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10294 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10295 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10296
10297 // Okay, we are casting from one integer or pointer type to another of
10298 // the same size. Instead of casting the pointer before
10299 // the store, cast the value to be stored.
10300 Value *NewCast;
10301 Value *SIOp0 = SI.getOperand(0);
10302 Instruction::CastOps opcode = Instruction::BitCast;
10303 const Type* CastSrcTy = SIOp0->getType();
10304 const Type* CastDstTy = SrcPTy;
10305 if (isa<PointerType>(CastDstTy)) {
10306 if (CastSrcTy->isInteger())
10307 opcode = Instruction::IntToPtr;
10308 } else if (isa<IntegerType>(CastDstTy)) {
10309 if (isa<PointerType>(SIOp0->getType()))
10310 opcode = Instruction::PtrToInt;
10311 }
10312 if (Constant *C = dyn_cast<Constant>(SIOp0))
10313 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10314 else
10315 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010316 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010317 SI);
10318 return new StoreInst(NewCast, CastOp);
10319 }
10320 }
10321 }
10322 return 0;
10323}
10324
10325Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10326 Value *Val = SI.getOperand(0);
10327 Value *Ptr = SI.getOperand(1);
10328
10329 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10330 EraseInstFromFunction(SI);
10331 ++NumCombined;
10332 return 0;
10333 }
10334
10335 // If the RHS is an alloca with a single use, zapify the store, making the
10336 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010337 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010338 if (isa<AllocaInst>(Ptr)) {
10339 EraseInstFromFunction(SI);
10340 ++NumCombined;
10341 return 0;
10342 }
10343
10344 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10345 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10346 GEP->getOperand(0)->hasOneUse()) {
10347 EraseInstFromFunction(SI);
10348 ++NumCombined;
10349 return 0;
10350 }
10351 }
10352
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010353 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010354 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10355 if (KnownAlign >
10356 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10357 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010358 SI.setAlignment(KnownAlign);
10359
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010360 // Do really simple DSE, to catch cases where there are several consequtive
10361 // stores to the same location, separated by a few arithmetic operations. This
10362 // situation often occurs with bitfield accesses.
10363 BasicBlock::iterator BBI = &SI;
10364 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10365 --ScanInsts) {
10366 --BBI;
10367
10368 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10369 // Prev store isn't volatile, and stores to the same location?
10370 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10371 ++NumDeadStore;
10372 ++BBI;
10373 EraseInstFromFunction(*PrevSI);
10374 continue;
10375 }
10376 break;
10377 }
10378
10379 // If this is a load, we have to stop. However, if the loaded value is from
10380 // the pointer we're loading and is producing the pointer we're storing,
10381 // then *this* store is dead (X = load P; store X -> P).
10382 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010383 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010384 EraseInstFromFunction(SI);
10385 ++NumCombined;
10386 return 0;
10387 }
10388 // Otherwise, this is a load from some other location. Stores before it
10389 // may not be dead.
10390 break;
10391 }
10392
10393 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010394 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010395 break;
10396 }
10397
10398
10399 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10400
10401 // store X, null -> turns into 'unreachable' in SimplifyCFG
10402 if (isa<ConstantPointerNull>(Ptr)) {
10403 if (!isa<UndefValue>(Val)) {
10404 SI.setOperand(0, UndefValue::get(Val->getType()));
10405 if (Instruction *U = dyn_cast<Instruction>(Val))
10406 AddToWorkList(U); // Dropped a use.
10407 ++NumCombined;
10408 }
10409 return 0; // Do not modify these!
10410 }
10411
10412 // store undef, Ptr -> noop
10413 if (isa<UndefValue>(Val)) {
10414 EraseInstFromFunction(SI);
10415 ++NumCombined;
10416 return 0;
10417 }
10418
10419 // If the pointer destination is a cast, see if we can fold the cast into the
10420 // source instead.
10421 if (isa<CastInst>(Ptr))
10422 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10423 return Res;
10424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10425 if (CE->isCast())
10426 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10427 return Res;
10428
10429
10430 // If this store is the last instruction in the basic block, and if the block
10431 // ends with an unconditional branch, try to move it to the successor block.
10432 BBI = &SI; ++BBI;
10433 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10434 if (BI->isUnconditional())
10435 if (SimplifyStoreAtEndOfBlock(SI))
10436 return 0; // xform done!
10437
10438 return 0;
10439}
10440
10441/// SimplifyStoreAtEndOfBlock - Turn things like:
10442/// if () { *P = v1; } else { *P = v2 }
10443/// into a phi node with a store in the successor.
10444///
10445/// Simplify things like:
10446/// *P = v1; if () { *P = v2; }
10447/// into a phi node with a store in the successor.
10448///
10449bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10450 BasicBlock *StoreBB = SI.getParent();
10451
10452 // Check to see if the successor block has exactly two incoming edges. If
10453 // so, see if the other predecessor contains a store to the same location.
10454 // if so, insert a PHI node (if needed) and move the stores down.
10455 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10456
10457 // Determine whether Dest has exactly two predecessors and, if so, compute
10458 // the other predecessor.
10459 pred_iterator PI = pred_begin(DestBB);
10460 BasicBlock *OtherBB = 0;
10461 if (*PI != StoreBB)
10462 OtherBB = *PI;
10463 ++PI;
10464 if (PI == pred_end(DestBB))
10465 return false;
10466
10467 if (*PI != StoreBB) {
10468 if (OtherBB)
10469 return false;
10470 OtherBB = *PI;
10471 }
10472 if (++PI != pred_end(DestBB))
10473 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000010474
10475 // Bail out if all the relevant blocks aren't distinct (this can happen,
10476 // for example, if SI is in an infinite loop)
10477 if (StoreBB == DestBB || OtherBB == DestBB)
10478 return false;
10479
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010480 // Verify that the other block ends in a branch and is not otherwise empty.
10481 BasicBlock::iterator BBI = OtherBB->getTerminator();
10482 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10483 if (!OtherBr || BBI == OtherBB->begin())
10484 return false;
10485
10486 // If the other block ends in an unconditional branch, check for the 'if then
10487 // else' case. there is an instruction before the branch.
10488 StoreInst *OtherStore = 0;
10489 if (OtherBr->isUnconditional()) {
10490 // If this isn't a store, or isn't a store to the same location, bail out.
10491 --BBI;
10492 OtherStore = dyn_cast<StoreInst>(BBI);
10493 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10494 return false;
10495 } else {
10496 // Otherwise, the other block ended with a conditional branch. If one of the
10497 // destinations is StoreBB, then we have the if/then case.
10498 if (OtherBr->getSuccessor(0) != StoreBB &&
10499 OtherBr->getSuccessor(1) != StoreBB)
10500 return false;
10501
10502 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10503 // if/then triangle. See if there is a store to the same ptr as SI that
10504 // lives in OtherBB.
10505 for (;; --BBI) {
10506 // Check to see if we find the matching store.
10507 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10508 if (OtherStore->getOperand(1) != SI.getOperand(1))
10509 return false;
10510 break;
10511 }
Eli Friedman3a311d52008-06-13 22:02:12 +000010512 // If we find something that may be using or overwriting the stored
10513 // value, or if we run out of instructions, we can't do the xform.
10514 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010515 BBI == OtherBB->begin())
10516 return false;
10517 }
10518
10519 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000010520 // make sure nothing reads or overwrites the stored value in
10521 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010522 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10523 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000010524 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010525 return false;
10526 }
10527 }
10528
10529 // Insert a PHI node now if we need it.
10530 Value *MergedVal = OtherStore->getOperand(0);
10531 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010532 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010533 PN->reserveOperandSpace(2);
10534 PN->addIncoming(SI.getOperand(0), SI.getParent());
10535 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10536 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10537 }
10538
10539 // Advance to a place where it is safe to insert the new store and
10540 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000010541 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010542 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10543 OtherStore->isVolatile()), *BBI);
10544
10545 // Nuke the old stores.
10546 EraseInstFromFunction(SI);
10547 EraseInstFromFunction(*OtherStore);
10548 ++NumCombined;
10549 return true;
10550}
10551
10552
10553Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10554 // Change br (not X), label True, label False to: br X, label False, True
10555 Value *X = 0;
10556 BasicBlock *TrueDest;
10557 BasicBlock *FalseDest;
10558 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10559 !isa<Constant>(X)) {
10560 // Swap Destinations and condition...
10561 BI.setCondition(X);
10562 BI.setSuccessor(0, FalseDest);
10563 BI.setSuccessor(1, TrueDest);
10564 return &BI;
10565 }
10566
10567 // Cannonicalize fcmp_one -> fcmp_oeq
10568 FCmpInst::Predicate FPred; Value *Y;
10569 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10570 TrueDest, FalseDest)))
10571 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10572 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10573 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10574 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10575 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10576 NewSCC->takeName(I);
10577 // Swap Destinations and condition...
10578 BI.setCondition(NewSCC);
10579 BI.setSuccessor(0, FalseDest);
10580 BI.setSuccessor(1, TrueDest);
10581 RemoveFromWorkList(I);
10582 I->eraseFromParent();
10583 AddToWorkList(NewSCC);
10584 return &BI;
10585 }
10586
10587 // Cannonicalize icmp_ne -> icmp_eq
10588 ICmpInst::Predicate IPred;
10589 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10590 TrueDest, FalseDest)))
10591 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10592 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10593 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10594 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10595 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10596 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10597 NewSCC->takeName(I);
10598 // Swap Destinations and condition...
10599 BI.setCondition(NewSCC);
10600 BI.setSuccessor(0, FalseDest);
10601 BI.setSuccessor(1, TrueDest);
10602 RemoveFromWorkList(I);
10603 I->eraseFromParent();;
10604 AddToWorkList(NewSCC);
10605 return &BI;
10606 }
10607
10608 return 0;
10609}
10610
10611Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10612 Value *Cond = SI.getCondition();
10613 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10614 if (I->getOpcode() == Instruction::Add)
10615 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10616 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10617 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10618 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10619 AddRHS));
10620 SI.setOperand(0, I->getOperand(0));
10621 AddToWorkList(I);
10622 return &SI;
10623 }
10624 }
10625 return 0;
10626}
10627
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010628Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10629 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman3d328112008-06-16 12:57:37 +000010630 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
Matthijs Kooijman4138edb2008-06-16 13:13:08 +000010631 EV.idx_end(), &EV))
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010632 return ReplaceInstUsesWith(EV, Elt);
10633
10634 // No changes
10635 return 0;
10636}
10637
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010638/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10639/// is to leave as a vector operation.
10640static bool CheapToScalarize(Value *V, bool isConstant) {
10641 if (isa<ConstantAggregateZero>(V))
10642 return true;
10643 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10644 if (isConstant) return true;
10645 // If all elts are the same, we can extract.
10646 Constant *Op0 = C->getOperand(0);
10647 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10648 if (C->getOperand(i) != Op0)
10649 return false;
10650 return true;
10651 }
10652 Instruction *I = dyn_cast<Instruction>(V);
10653 if (!I) return false;
10654
10655 // Insert element gets simplified to the inserted element or is deleted if
10656 // this is constant idx extract element and its a constant idx insertelt.
10657 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10658 isa<ConstantInt>(I->getOperand(2)))
10659 return true;
10660 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10661 return true;
10662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10663 if (BO->hasOneUse() &&
10664 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10665 CheapToScalarize(BO->getOperand(1), isConstant)))
10666 return true;
10667 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10668 if (CI->hasOneUse() &&
10669 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10670 CheapToScalarize(CI->getOperand(1), isConstant)))
10671 return true;
10672
10673 return false;
10674}
10675
10676/// Read and decode a shufflevector mask.
10677///
10678/// It turns undef elements into values that are larger than the number of
10679/// elements in the input.
10680static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10681 unsigned NElts = SVI->getType()->getNumElements();
10682 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10683 return std::vector<unsigned>(NElts, 0);
10684 if (isa<UndefValue>(SVI->getOperand(2)))
10685 return std::vector<unsigned>(NElts, 2*NElts);
10686
10687 std::vector<unsigned> Result;
10688 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000010689 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10690 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010691 Result.push_back(NElts*2); // undef -> 8
10692 else
Gabor Greif17396002008-06-12 21:37:33 +000010693 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010694 return Result;
10695}
10696
10697/// FindScalarElement - Given a vector and an element number, see if the scalar
10698/// value is already around as a register, for example if it were inserted then
10699/// extracted from the vector.
10700static Value *FindScalarElement(Value *V, unsigned EltNo) {
10701 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10702 const VectorType *PTy = cast<VectorType>(V->getType());
10703 unsigned Width = PTy->getNumElements();
10704 if (EltNo >= Width) // Out of range access.
10705 return UndefValue::get(PTy->getElementType());
10706
10707 if (isa<UndefValue>(V))
10708 return UndefValue::get(PTy->getElementType());
10709 else if (isa<ConstantAggregateZero>(V))
10710 return Constant::getNullValue(PTy->getElementType());
10711 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10712 return CP->getOperand(EltNo);
10713 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10714 // If this is an insert to a variable element, we don't know what it is.
10715 if (!isa<ConstantInt>(III->getOperand(2)))
10716 return 0;
10717 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10718
10719 // If this is an insert to the element we are looking for, return the
10720 // inserted value.
10721 if (EltNo == IIElt)
10722 return III->getOperand(1);
10723
10724 // Otherwise, the insertelement doesn't modify the value, recurse on its
10725 // vector input.
10726 return FindScalarElement(III->getOperand(0), EltNo);
10727 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10728 unsigned InEl = getShuffleMask(SVI)[EltNo];
10729 if (InEl < Width)
10730 return FindScalarElement(SVI->getOperand(0), InEl);
10731 else if (InEl < Width*2)
10732 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10733 else
10734 return UndefValue::get(PTy->getElementType());
10735 }
10736
10737 // Otherwise, we don't know.
10738 return 0;
10739}
10740
10741Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010742 // If vector val is undef, replace extract with scalar undef.
10743 if (isa<UndefValue>(EI.getOperand(0)))
10744 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10745
10746 // If vector val is constant 0, replace extract with scalar 0.
10747 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10748 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10749
10750 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000010751 // If vector val is constant with all elements the same, replace EI with
10752 // that element. When the elements are not identical, we cannot replace yet
10753 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010754 Constant *op0 = C->getOperand(0);
10755 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10756 if (C->getOperand(i) != op0) {
10757 op0 = 0;
10758 break;
10759 }
10760 if (op0)
10761 return ReplaceInstUsesWith(EI, op0);
10762 }
10763
10764 // If extracting a specified index from the vector, see if we can recursively
10765 // find a previously computed scalar that was inserted into the vector.
10766 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10767 unsigned IndexVal = IdxC->getZExtValue();
10768 unsigned VectorWidth =
10769 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10770
10771 // If this is extracting an invalid index, turn this into undef, to avoid
10772 // crashing the code below.
10773 if (IndexVal >= VectorWidth)
10774 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10775
10776 // This instruction only demands the single element from the input vector.
10777 // If the input vector has a single use, simplify it based on this use
10778 // property.
10779 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10780 uint64_t UndefElts;
10781 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10782 1 << IndexVal,
10783 UndefElts)) {
10784 EI.setOperand(0, V);
10785 return &EI;
10786 }
10787 }
10788
10789 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10790 return ReplaceInstUsesWith(EI, Elt);
10791
10792 // If the this extractelement is directly using a bitcast from a vector of
10793 // the same number of elements, see if we can find the source element from
10794 // it. In this case, we will end up needing to bitcast the scalars.
10795 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10796 if (const VectorType *VT =
10797 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10798 if (VT->getNumElements() == VectorWidth)
10799 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10800 return new BitCastInst(Elt, EI.getType());
10801 }
10802 }
10803
10804 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10805 if (I->hasOneUse()) {
10806 // Push extractelement into predecessor operation if legal and
10807 // profitable to do so
10808 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10809 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10810 if (CheapToScalarize(BO, isConstantElt)) {
10811 ExtractElementInst *newEI0 =
10812 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10813 EI.getName()+".lhs");
10814 ExtractElementInst *newEI1 =
10815 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10816 EI.getName()+".rhs");
10817 InsertNewInstBefore(newEI0, EI);
10818 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000010819 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010820 }
10821 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010822 unsigned AS =
10823 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010824 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10825 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010826 GetElementPtrInst *GEP =
10827 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010828 InsertNewInstBefore(GEP, EI);
10829 return new LoadInst(GEP);
10830 }
10831 }
10832 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10833 // Extracting the inserted element?
10834 if (IE->getOperand(2) == EI.getOperand(1))
10835 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10836 // If the inserted and extracted elements are constants, they must not
10837 // be the same value, extract from the pre-inserted value instead.
10838 if (isa<Constant>(IE->getOperand(2)) &&
10839 isa<Constant>(EI.getOperand(1))) {
10840 AddUsesToWorkList(EI);
10841 EI.setOperand(0, IE->getOperand(0));
10842 return &EI;
10843 }
10844 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10845 // If this is extracting an element from a shufflevector, figure out where
10846 // it came from and extract from the appropriate input element instead.
10847 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10848 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10849 Value *Src;
10850 if (SrcIdx < SVI->getType()->getNumElements())
10851 Src = SVI->getOperand(0);
10852 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10853 SrcIdx -= SVI->getType()->getNumElements();
10854 Src = SVI->getOperand(1);
10855 } else {
10856 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10857 }
10858 return new ExtractElementInst(Src, SrcIdx);
10859 }
10860 }
10861 }
10862 return 0;
10863}
10864
10865/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10866/// elements from either LHS or RHS, return the shuffle mask and true.
10867/// Otherwise, return false.
10868static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10869 std::vector<Constant*> &Mask) {
10870 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10871 "Invalid CollectSingleShuffleElements");
10872 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10873
10874 if (isa<UndefValue>(V)) {
10875 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10876 return true;
10877 } else if (V == LHS) {
10878 for (unsigned i = 0; i != NumElts; ++i)
10879 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10880 return true;
10881 } else if (V == RHS) {
10882 for (unsigned i = 0; i != NumElts; ++i)
10883 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10884 return true;
10885 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10886 // If this is an insert of an extract from some other vector, include it.
10887 Value *VecOp = IEI->getOperand(0);
10888 Value *ScalarOp = IEI->getOperand(1);
10889 Value *IdxOp = IEI->getOperand(2);
10890
10891 if (!isa<ConstantInt>(IdxOp))
10892 return false;
10893 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10894
10895 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10896 // Okay, we can handle this if the vector we are insertinting into is
10897 // transitively ok.
10898 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10899 // If so, update the mask to reflect the inserted undef.
10900 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10901 return true;
10902 }
10903 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10904 if (isa<ConstantInt>(EI->getOperand(1)) &&
10905 EI->getOperand(0)->getType() == V->getType()) {
10906 unsigned ExtractedIdx =
10907 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10908
10909 // This must be extracting from either LHS or RHS.
10910 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10911 // Okay, we can handle this if the vector we are insertinting into is
10912 // transitively ok.
10913 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10914 // If so, update the mask to reflect the inserted value.
10915 if (EI->getOperand(0) == LHS) {
10916 Mask[InsertedIdx & (NumElts-1)] =
10917 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10918 } else {
10919 assert(EI->getOperand(0) == RHS);
10920 Mask[InsertedIdx & (NumElts-1)] =
10921 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10922
10923 }
10924 return true;
10925 }
10926 }
10927 }
10928 }
10929 }
10930 // TODO: Handle shufflevector here!
10931
10932 return false;
10933}
10934
10935/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10936/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10937/// that computes V and the LHS value of the shuffle.
10938static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10939 Value *&RHS) {
10940 assert(isa<VectorType>(V->getType()) &&
10941 (RHS == 0 || V->getType() == RHS->getType()) &&
10942 "Invalid shuffle!");
10943 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10944
10945 if (isa<UndefValue>(V)) {
10946 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10947 return V;
10948 } else if (isa<ConstantAggregateZero>(V)) {
10949 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10950 return V;
10951 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10952 // If this is an insert of an extract from some other vector, include it.
10953 Value *VecOp = IEI->getOperand(0);
10954 Value *ScalarOp = IEI->getOperand(1);
10955 Value *IdxOp = IEI->getOperand(2);
10956
10957 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10958 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10959 EI->getOperand(0)->getType() == V->getType()) {
10960 unsigned ExtractedIdx =
10961 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10962 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10963
10964 // Either the extracted from or inserted into vector must be RHSVec,
10965 // otherwise we'd end up with a shuffle of three inputs.
10966 if (EI->getOperand(0) == RHS || RHS == 0) {
10967 RHS = EI->getOperand(0);
10968 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10969 Mask[InsertedIdx & (NumElts-1)] =
10970 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10971 return V;
10972 }
10973
10974 if (VecOp == RHS) {
10975 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10976 // Everything but the extracted element is replaced with the RHS.
10977 for (unsigned i = 0; i != NumElts; ++i) {
10978 if (i != InsertedIdx)
10979 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10980 }
10981 return V;
10982 }
10983
10984 // If this insertelement is a chain that comes from exactly these two
10985 // vectors, return the vector and the effective shuffle.
10986 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10987 return EI->getOperand(0);
10988
10989 }
10990 }
10991 }
10992 // TODO: Handle shufflevector here!
10993
10994 // Otherwise, can't do anything fancy. Return an identity vector.
10995 for (unsigned i = 0; i != NumElts; ++i)
10996 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10997 return V;
10998}
10999
11000Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11001 Value *VecOp = IE.getOperand(0);
11002 Value *ScalarOp = IE.getOperand(1);
11003 Value *IdxOp = IE.getOperand(2);
11004
11005 // Inserting an undef or into an undefined place, remove this.
11006 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11007 ReplaceInstUsesWith(IE, VecOp);
11008
11009 // If the inserted element was extracted from some other vector, and if the
11010 // indexes are constant, try to turn this into a shufflevector operation.
11011 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11012 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11013 EI->getOperand(0)->getType() == IE.getType()) {
11014 unsigned NumVectorElts = IE.getType()->getNumElements();
11015 unsigned ExtractedIdx =
11016 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11017 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11018
11019 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11020 return ReplaceInstUsesWith(IE, VecOp);
11021
11022 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11023 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11024
11025 // If we are extracting a value from a vector, then inserting it right
11026 // back into the same place, just use the input vector.
11027 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11028 return ReplaceInstUsesWith(IE, VecOp);
11029
11030 // We could theoretically do this for ANY input. However, doing so could
11031 // turn chains of insertelement instructions into a chain of shufflevector
11032 // instructions, and right now we do not merge shufflevectors. As such,
11033 // only do this in a situation where it is clear that there is benefit.
11034 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11035 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11036 // the values of VecOp, except then one read from EIOp0.
11037 // Build a new shuffle mask.
11038 std::vector<Constant*> Mask;
11039 if (isa<UndefValue>(VecOp))
11040 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11041 else {
11042 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11043 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11044 NumVectorElts));
11045 }
11046 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11047 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11048 ConstantVector::get(Mask));
11049 }
11050
11051 // If this insertelement isn't used by some other insertelement, turn it
11052 // (and any insertelements it points to), into one big shuffle.
11053 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11054 std::vector<Constant*> Mask;
11055 Value *RHS = 0;
11056 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11057 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11058 // We now have a shuffle of LHS, RHS, Mask.
11059 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11060 }
11061 }
11062 }
11063
11064 return 0;
11065}
11066
11067
11068Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11069 Value *LHS = SVI.getOperand(0);
11070 Value *RHS = SVI.getOperand(1);
11071 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11072
11073 bool MadeChange = false;
11074
11075 // Undefined shuffle mask -> undefined value.
11076 if (isa<UndefValue>(SVI.getOperand(2)))
11077 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11078
11079 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11080 // the undef, change them to undefs.
11081 if (isa<UndefValue>(SVI.getOperand(1))) {
11082 // Scan to see if there are any references to the RHS. If so, replace them
11083 // with undef element refs and set MadeChange to true.
11084 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11085 if (Mask[i] >= e && Mask[i] != 2*e) {
11086 Mask[i] = 2*e;
11087 MadeChange = true;
11088 }
11089 }
11090
11091 if (MadeChange) {
11092 // Remap any references to RHS to use LHS.
11093 std::vector<Constant*> Elts;
11094 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11095 if (Mask[i] == 2*e)
11096 Elts.push_back(UndefValue::get(Type::Int32Ty));
11097 else
11098 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11099 }
11100 SVI.setOperand(2, ConstantVector::get(Elts));
11101 }
11102 }
11103
11104 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11105 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11106 if (LHS == RHS || isa<UndefValue>(LHS)) {
11107 if (isa<UndefValue>(LHS) && LHS == RHS) {
11108 // shuffle(undef,undef,mask) -> undef.
11109 return ReplaceInstUsesWith(SVI, LHS);
11110 }
11111
11112 // Remap any references to RHS to use LHS.
11113 std::vector<Constant*> Elts;
11114 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11115 if (Mask[i] >= 2*e)
11116 Elts.push_back(UndefValue::get(Type::Int32Ty));
11117 else {
11118 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11119 (Mask[i] < e && isa<UndefValue>(LHS)))
11120 Mask[i] = 2*e; // Turn into undef.
11121 else
11122 Mask[i] &= (e-1); // Force to LHS.
11123 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11124 }
11125 }
11126 SVI.setOperand(0, SVI.getOperand(1));
11127 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11128 SVI.setOperand(2, ConstantVector::get(Elts));
11129 LHS = SVI.getOperand(0);
11130 RHS = SVI.getOperand(1);
11131 MadeChange = true;
11132 }
11133
11134 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11135 bool isLHSID = true, isRHSID = true;
11136
11137 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11138 if (Mask[i] >= e*2) continue; // Ignore undef values.
11139 // Is this an identity shuffle of the LHS value?
11140 isLHSID &= (Mask[i] == i);
11141
11142 // Is this an identity shuffle of the RHS value?
11143 isRHSID &= (Mask[i]-e == i);
11144 }
11145
11146 // Eliminate identity shuffles.
11147 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11148 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11149
11150 // If the LHS is a shufflevector itself, see if we can combine it with this
11151 // one without producing an unusual shuffle. Here we are really conservative:
11152 // we are absolutely afraid of producing a shuffle mask not in the input
11153 // program, because the code gen may not be smart enough to turn a merged
11154 // shuffle into two specific shuffles: it may produce worse code. As such,
11155 // we only merge two shuffles if the result is one of the two input shuffle
11156 // masks. In this case, merging the shuffles just removes one instruction,
11157 // which we know is safe. This is good for things like turning:
11158 // (splat(splat)) -> splat.
11159 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11160 if (isa<UndefValue>(RHS)) {
11161 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11162
11163 std::vector<unsigned> NewMask;
11164 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11165 if (Mask[i] >= 2*e)
11166 NewMask.push_back(2*e);
11167 else
11168 NewMask.push_back(LHSMask[Mask[i]]);
11169
11170 // If the result mask is equal to the src shuffle or this shuffle mask, do
11171 // the replacement.
11172 if (NewMask == LHSMask || NewMask == Mask) {
11173 std::vector<Constant*> Elts;
11174 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11175 if (NewMask[i] >= e*2) {
11176 Elts.push_back(UndefValue::get(Type::Int32Ty));
11177 } else {
11178 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11179 }
11180 }
11181 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11182 LHSSVI->getOperand(1),
11183 ConstantVector::get(Elts));
11184 }
11185 }
11186 }
11187
11188 return MadeChange ? &SVI : 0;
11189}
11190
11191
11192
11193
11194/// TryToSinkInstruction - Try to move the specified instruction from its
11195/// current block into the beginning of DestBlock, which can only happen if it's
11196/// safe to move the instruction past all of the instructions between it and the
11197/// end of its block.
11198static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11199 assert(I->hasOneUse() && "Invariants didn't hold!");
11200
11201 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011202 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11203 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011204
11205 // Do not sink alloca instructions out of the entry block.
11206 if (isa<AllocaInst>(I) && I->getParent() ==
11207 &DestBlock->getParent()->getEntryBlock())
11208 return false;
11209
11210 // We can only sink load instructions if there is nothing between the load and
11211 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011212 if (I->mayReadFromMemory()) {
11213 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214 Scan != E; ++Scan)
11215 if (Scan->mayWriteToMemory())
11216 return false;
11217 }
11218
Dan Gohman514277c2008-05-23 21:05:58 +000011219 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011220
11221 I->moveBefore(InsertPos);
11222 ++NumSunkInst;
11223 return true;
11224}
11225
11226
11227/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11228/// all reachable code to the worklist.
11229///
11230/// This has a couple of tricks to make the code faster and more powerful. In
11231/// particular, we constant fold and DCE instructions as we go, to avoid adding
11232/// them to the worklist (this significantly speeds up instcombine on code where
11233/// many instructions are dead or constant). Additionally, if we find a branch
11234/// whose condition is a known constant, we only visit the reachable successors.
11235///
11236static void AddReachableCodeToWorklist(BasicBlock *BB,
11237 SmallPtrSet<BasicBlock*, 64> &Visited,
11238 InstCombiner &IC,
11239 const TargetData *TD) {
11240 std::vector<BasicBlock*> Worklist;
11241 Worklist.push_back(BB);
11242
11243 while (!Worklist.empty()) {
11244 BB = Worklist.back();
11245 Worklist.pop_back();
11246
11247 // We have now visited this block! If we've already been here, ignore it.
11248 if (!Visited.insert(BB)) continue;
11249
11250 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11251 Instruction *Inst = BBI++;
11252
11253 // DCE instruction if trivially dead.
11254 if (isInstructionTriviallyDead(Inst)) {
11255 ++NumDeadInst;
11256 DOUT << "IC: DCE: " << *Inst;
11257 Inst->eraseFromParent();
11258 continue;
11259 }
11260
11261 // ConstantProp instruction if trivially constant.
11262 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11263 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11264 Inst->replaceAllUsesWith(C);
11265 ++NumConstProp;
11266 Inst->eraseFromParent();
11267 continue;
11268 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011269
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011270 IC.AddToWorkList(Inst);
11271 }
11272
11273 // Recursively visit successors. If this is a branch or switch on a
11274 // constant, only visit the reachable successor.
11275 TerminatorInst *TI = BB->getTerminator();
11276 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11277 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11278 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011279 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011280 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011281 continue;
11282 }
11283 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11284 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11285 // See if this is an explicit destination.
11286 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11287 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011288 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011289 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011290 continue;
11291 }
11292
11293 // Otherwise it is the default destination.
11294 Worklist.push_back(SI->getSuccessor(0));
11295 continue;
11296 }
11297 }
11298
11299 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11300 Worklist.push_back(TI->getSuccessor(i));
11301 }
11302}
11303
11304bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11305 bool Changed = false;
11306 TD = &getAnalysis<TargetData>();
11307
11308 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11309 << F.getNameStr() << "\n");
11310
11311 {
11312 // Do a depth-first traversal of the function, populate the worklist with
11313 // the reachable instructions. Ignore blocks that are not reachable. Keep
11314 // track of which blocks we visit.
11315 SmallPtrSet<BasicBlock*, 64> Visited;
11316 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11317
11318 // Do a quick scan over the function. If we find any blocks that are
11319 // unreachable, remove any instructions inside of them. This prevents
11320 // the instcombine code from having to deal with some bad special cases.
11321 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11322 if (!Visited.count(BB)) {
11323 Instruction *Term = BB->getTerminator();
11324 while (Term != BB->begin()) { // Remove instrs bottom-up
11325 BasicBlock::iterator I = Term; --I;
11326
11327 DOUT << "IC: DCE: " << *I;
11328 ++NumDeadInst;
11329
11330 if (!I->use_empty())
11331 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11332 I->eraseFromParent();
11333 }
11334 }
11335 }
11336
11337 while (!Worklist.empty()) {
11338 Instruction *I = RemoveOneFromWorkList();
11339 if (I == 0) continue; // skip null values.
11340
11341 // Check to see if we can DCE the instruction.
11342 if (isInstructionTriviallyDead(I)) {
11343 // Add operands to the worklist.
11344 if (I->getNumOperands() < 4)
11345 AddUsesToWorkList(*I);
11346 ++NumDeadInst;
11347
11348 DOUT << "IC: DCE: " << *I;
11349
11350 I->eraseFromParent();
11351 RemoveFromWorkList(I);
11352 continue;
11353 }
11354
11355 // Instruction isn't dead, see if we can constant propagate it.
11356 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11357 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11358
11359 // Add operands to the worklist.
11360 AddUsesToWorkList(*I);
11361 ReplaceInstUsesWith(*I, C);
11362
11363 ++NumConstProp;
11364 I->eraseFromParent();
11365 RemoveFromWorkList(I);
11366 continue;
11367 }
11368
Nick Lewyckyadb67922008-05-25 20:56:15 +000011369 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11370 // See if we can constant fold its operands.
11371 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11373 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11374 i->set(NewC);
11375 }
11376 }
11377 }
11378
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011379 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011380 // FIXME: Remove GetResultInst test when first class support for aggregates
11381 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011382 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011383 BasicBlock *BB = I->getParent();
11384 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11385 if (UserParent != BB) {
11386 bool UserIsSuccessor = false;
11387 // See if the user is one of our successors.
11388 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11389 if (*SI == UserParent) {
11390 UserIsSuccessor = true;
11391 break;
11392 }
11393
11394 // If the user is one of our immediate successors, and if that successor
11395 // only has us as a predecessors (we'd have to split the critical edge
11396 // otherwise), we can keep going.
11397 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11398 next(pred_begin(UserParent)) == pred_end(UserParent))
11399 // Okay, the CFG is simple enough, try to sink this instruction.
11400 Changed |= TryToSinkInstruction(I, UserParent);
11401 }
11402 }
11403
11404 // Now that we have an instruction, try combining it to simplify it...
11405#ifndef NDEBUG
11406 std::string OrigI;
11407#endif
11408 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11409 if (Instruction *Result = visit(*I)) {
11410 ++NumCombined;
11411 // Should we replace the old instruction with a new one?
11412 if (Result != I) {
11413 DOUT << "IC: Old = " << *I
11414 << " New = " << *Result;
11415
11416 // Everything uses the new instruction now.
11417 I->replaceAllUsesWith(Result);
11418
11419 // Push the new instruction and any users onto the worklist.
11420 AddToWorkList(Result);
11421 AddUsersToWorkList(*Result);
11422
11423 // Move the name to the new instruction first.
11424 Result->takeName(I);
11425
11426 // Insert the new instruction into the basic block...
11427 BasicBlock *InstParent = I->getParent();
11428 BasicBlock::iterator InsertPos = I;
11429
11430 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11431 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11432 ++InsertPos;
11433
11434 InstParent->getInstList().insert(InsertPos, Result);
11435
11436 // Make sure that we reprocess all operands now that we reduced their
11437 // use counts.
11438 AddUsesToWorkList(*I);
11439
11440 // Instructions can end up on the worklist more than once. Make sure
11441 // we do not process an instruction that has been deleted.
11442 RemoveFromWorkList(I);
11443
11444 // Erase the old instruction.
11445 InstParent->getInstList().erase(I);
11446 } else {
11447#ifndef NDEBUG
11448 DOUT << "IC: Mod = " << OrigI
11449 << " New = " << *I;
11450#endif
11451
11452 // If the instruction was modified, it's possible that it is now dead.
11453 // if so, remove it.
11454 if (isInstructionTriviallyDead(I)) {
11455 // Make sure we process all operands now that we are reducing their
11456 // use counts.
11457 AddUsesToWorkList(*I);
11458
11459 // Instructions may end up in the worklist more than once. Erase all
11460 // occurrences of this instruction.
11461 RemoveFromWorkList(I);
11462 I->eraseFromParent();
11463 } else {
11464 AddToWorkList(I);
11465 AddUsersToWorkList(*I);
11466 }
11467 }
11468 Changed = true;
11469 }
11470 }
11471
11472 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011473
11474 // Do an explicit clear, this shrinks the map if needed.
11475 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011476 return Changed;
11477}
11478
11479
11480bool InstCombiner::runOnFunction(Function &F) {
11481 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11482
11483 bool EverMadeChange = false;
11484
11485 // Iterate while there is work to do.
11486 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011487 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011488 EverMadeChange = true;
11489 return EverMadeChange;
11490}
11491
11492FunctionPass *llvm::createInstructionCombiningPass() {
11493 return new InstCombiner();
11494}
11495